From 94a0819fe3a0d679c3042a77bfe6a2afc505daea Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:11:28 +0200 Subject: Adding upstream version 1.66.0+dfsg1. Signed-off-by: Daniel Baumann --- .../annotate-snippets-0.8.0/.cargo-checksum.json | 1 - vendor/annotate-snippets-0.8.0/CHANGELOG.md | 29 - vendor/annotate-snippets-0.8.0/Cargo.lock | 630 - vendor/annotate-snippets-0.8.0/Cargo.toml | 62 - vendor/annotate-snippets-0.8.0/LICENSE-APACHE | 201 - vendor/annotate-snippets-0.8.0/LICENSE-MIT | 19 - vendor/annotate-snippets-0.8.0/README.md | 92 - vendor/annotate-snippets-0.8.0/benches/simple.rs | 74 - .../examples/expected_type.rs | 43 - vendor/annotate-snippets-0.8.0/examples/footer.rs | 39 - vendor/annotate-snippets-0.8.0/examples/format.rs | 61 - .../annotate-snippets-0.8.0/examples/multislice.rs | 38 - .../src/display_list/from_snippet.rs | 517 - .../src/display_list/mod.rs | 37 - .../src/display_list/structs.rs | 191 - .../annotate-snippets-0.8.0/src/formatter/mod.rs | 397 - .../annotate-snippets-0.8.0/src/formatter/style.rs | 52 - vendor/annotate-snippets-0.8.0/src/lib.rs | 54 - vendor/annotate-snippets-0.8.0/src/snippet.rs | 88 - .../src/stylesheets/color.rs | 50 - .../annotate-snippets-0.8.0/src/stylesheets/mod.rs | 11 - .../src/stylesheets/no_color.rs | 31 - vendor/annotate-snippets-0.8.0/tests/diff/mod.rs | 43 - .../tests/dl_from_snippet.rs | 401 - .../fixtures/no-color/multiline_annotation.toml | 40 - .../fixtures/no-color/multiline_annotation.txt | 14 - .../fixtures/no-color/multiline_annotation2.toml | 18 - .../fixtures/no-color/multiline_annotation2.txt | 9 - .../fixtures/no-color/multiline_annotation3.toml | 18 - .../fixtures/no-color/multiline_annotation3.txt | 9 - .../fixtures/no-color/multiple_annotations.toml | 25 - .../fixtures/no-color/multiple_annotations.txt | 14 - .../tests/fixtures/no-color/simple.toml | 18 - .../tests/fixtures/no-color/simple.txt | 9 - .../annotate-snippets-0.8.0/tests/fixtures_test.rs | 45 - vendor/annotate-snippets-0.8.0/tests/formatter.rs | 552 - .../annotate-snippets-0.8.0/tests/snippet/mod.rs | 167 - vendor/anyhow/.cargo-checksum.json | 2 +- vendor/anyhow/Cargo.toml | 2 +- vendor/anyhow/build.rs | 32 +- vendor/anyhow/src/backtrace.rs | 2 +- vendor/anyhow/src/context.rs | 25 +- vendor/anyhow/src/ensure.rs | 20 +- vendor/anyhow/src/error.rs | 40 +- vendor/anyhow/src/kind.rs | 4 +- vendor/anyhow/src/lib.rs | 6 +- vendor/anyhow/src/macros.rs | 32 +- vendor/anyhow/src/wrapper.rs | 13 +- vendor/anyhow/tests/test_ensure.rs | 2 +- vendor/anyhow/tests/ui/must-use.stderr | 2 +- vendor/anyhow/tests/ui/no-impl.stderr | 12 +- vendor/block-buffer-0.7.3/.cargo-checksum.json | 1 - vendor/block-buffer-0.7.3/Cargo.toml | 36 - vendor/block-buffer-0.7.3/LICENSE-APACHE | 201 - vendor/block-buffer-0.7.3/LICENSE-MIT | 25 - vendor/block-buffer-0.7.3/src/lib.rs | 210 - vendor/block-padding/.cargo-checksum.json | 1 - vendor/block-padding/Cargo.toml | 26 - vendor/block-padding/LICENSE-APACHE | 201 - vendor/block-padding/LICENSE-MIT | 25 - vendor/block-padding/src/lib.rs | 323 - vendor/byte-tools/.cargo-checksum.json | 1 - vendor/byte-tools/Cargo.toml | 21 - vendor/byte-tools/LICENSE-APACHE | 201 - vendor/byte-tools/LICENSE-MIT | 25 - vendor/byte-tools/src/lib.rs | 29 - vendor/byteorder/.cargo-checksum.json | 1 - vendor/byteorder/CHANGELOG.md | 139 - vendor/byteorder/COPYING | 3 - vendor/byteorder/Cargo.toml | 43 - vendor/byteorder/LICENSE-MIT | 21 - vendor/byteorder/README.md | 63 - vendor/byteorder/UNLICENSE | 24 - vendor/byteorder/benches/bench.rs | 324 - vendor/byteorder/rustfmt.toml | 2 - vendor/byteorder/src/io.rs | 1592 -- vendor/byteorder/src/lib.rs | 4052 ----- vendor/camino/.cargo-checksum.json | 2 +- vendor/camino/CHANGELOG.md | 22 +- vendor/camino/Cargo.toml | 2 +- vendor/camino/build.rs | 27 +- vendor/camino/src/lib.rs | 137 + vendor/clap-3.2.20/.cargo-checksum.json | 1 + vendor/clap-3.2.20/Cargo.lock | 746 + vendor/clap-3.2.20/Cargo.toml | 471 + vendor/clap-3.2.20/LICENSE-APACHE | 201 + vendor/clap-3.2.20/LICENSE-MIT | 21 + vendor/clap-3.2.20/README.md | 43 + .../clap-3.2.20/examples/cargo-example-derive.md | 43 + .../clap-3.2.20/examples/cargo-example-derive.rs | 20 + vendor/clap-3.2.20/examples/cargo-example.md | 43 + vendor/clap-3.2.20/examples/cargo-example.rs | 19 + vendor/clap-3.2.20/examples/demo.md | 19 + vendor/clap-3.2.20/examples/demo.rs | 22 + .../examples/derive_ref/augment_args.rs | 27 + .../examples/derive_ref/augment_subcommands.rs | 21 + .../clap-3.2.20/examples/derive_ref/custom-bool.md | 47 + .../clap-3.2.20/examples/derive_ref/custom-bool.rs | 32 + .../examples/derive_ref/flatten_hand_args.rs | 81 + .../examples/derive_ref/hand_subcommand.rs | 81 + .../examples/derive_ref/interop_tests.md | 256 + .../examples/escaped-positional-derive.md | 63 + .../examples/escaped-positional-derive.rs | 25 + vendor/clap-3.2.20/examples/escaped-positional.md | 63 + vendor/clap-3.2.20/examples/escaped-positional.rs | 36 + vendor/clap-3.2.20/examples/git-derive.md | 138 + vendor/clap-3.2.20/examples/git-derive.rs | 105 + vendor/clap-3.2.20/examples/git.md | 136 + vendor/clap-3.2.20/examples/git.rs | 101 + vendor/clap-3.2.20/examples/multicall-busybox.md | 42 + vendor/clap-3.2.20/examples/multicall-busybox.rs | 48 + vendor/clap-3.2.20/examples/multicall-hostname.md | 10 + vendor/clap-3.2.20/examples/multicall-hostname.rs | 17 + vendor/clap-3.2.20/examples/pacman.md | 85 + vendor/clap-3.2.20/examples/pacman.rs | 111 + vendor/clap-3.2.20/examples/repl.rs | 92 + .../examples/tutorial_builder/01_quick.md | 37 + .../examples/tutorial_builder/01_quick.rs | 63 + .../examples/tutorial_builder/02_app_settings.md | 19 + .../examples/tutorial_builder/02_app_settings.rs | 19 + .../examples/tutorial_builder/02_apps.md | 19 + .../examples/tutorial_builder/02_apps.rs | 20 + .../examples/tutorial_builder/02_crate.md | 18 + .../examples/tutorial_builder/02_crate.rs | 18 + .../examples/tutorial_builder/03_01_flag_bool.md | 23 + .../examples/tutorial_builder/03_01_flag_bool.rs | 14 + .../examples/tutorial_builder/03_01_flag_count.md | 23 + .../examples/tutorial_builder/03_01_flag_count.rs | 9 + .../examples/tutorial_builder/03_02_option.md | 32 + .../examples/tutorial_builder/03_02_option.rs | 9 + .../examples/tutorial_builder/03_03_positional.md | 22 + .../examples/tutorial_builder/03_03_positional.rs | 9 + .../examples/tutorial_builder/03_04_subcommands.md | 64 + .../examples/tutorial_builder/03_04_subcommands.rs | 22 + .../tutorial_builder/03_05_default_values.md | 22 + .../tutorial_builder/03_05_default_values.rs | 14 + .../examples/tutorial_builder/04_01_enum.md | 29 + .../examples/tutorial_builder/04_01_enum.rs | 66 + .../examples/tutorial_builder/04_01_possible.md | 29 + .../examples/tutorial_builder/04_01_possible.rs | 26 + .../examples/tutorial_builder/04_02_parse.md | 31 + .../examples/tutorial_builder/04_02_parse.rs | 17 + .../examples/tutorial_builder/04_02_validate.md | 31 + .../examples/tutorial_builder/04_02_validate.rs | 36 + .../examples/tutorial_builder/04_03_relations.md | 58 + .../examples/tutorial_builder/04_03_relations.rs | 80 + .../examples/tutorial_builder/04_04_custom.md | 57 + .../examples/tutorial_builder/04_04_custom.rs | 88 + .../examples/tutorial_builder/05_01_assert.rs | 25 + .../examples/tutorial_derive/01_quick.md | 37 + .../examples/tutorial_derive/01_quick.rs | 69 + .../examples/tutorial_derive/02_app_settings.md | 19 + .../examples/tutorial_derive/02_app_settings.rs | 19 + .../examples/tutorial_derive/02_apps.md | 19 + .../examples/tutorial_derive/02_apps.rs | 20 + .../examples/tutorial_derive/02_crate.md | 18 + .../examples/tutorial_derive/02_crate.rs | 17 + .../examples/tutorial_derive/03_01_flag_bool.md | 23 + .../examples/tutorial_derive/03_01_flag_bool.rs | 14 + .../examples/tutorial_derive/03_01_flag_count.md | 23 + .../examples/tutorial_derive/03_01_flag_count.rs | 14 + .../examples/tutorial_derive/03_02_option.md | 32 + .../examples/tutorial_derive/03_02_option.rs | 14 + .../examples/tutorial_derive/03_03_positional.md | 22 + .../examples/tutorial_derive/03_03_positional.rs | 14 + .../examples/tutorial_derive/03_04_subcommands.md | 64 + .../examples/tutorial_derive/03_04_subcommands.rs | 30 + .../tutorial_derive/03_04_subcommands_alt.rs | 33 + .../tutorial_derive/03_05_default_values.md | 22 + .../tutorial_derive/03_05_default_values.rs | 14 + .../examples/tutorial_derive/04_01_enum.md | 29 + .../examples/tutorial_derive/04_01_enum.rs | 28 + .../examples/tutorial_derive/04_02_parse.md | 31 + .../examples/tutorial_derive/04_02_parse.rs | 15 + .../examples/tutorial_derive/04_02_validate.md | 31 + .../examples/tutorial_derive/04_02_validate.rs | 34 + .../examples/tutorial_derive/04_03_relations.md | 58 + .../examples/tutorial_derive/04_03_relations.rs | 72 + .../examples/tutorial_derive/04_04_custom.md | 57 + .../examples/tutorial_derive/04_04_custom.rs | 93 + .../examples/tutorial_derive/05_01_assert.rs | 21 + vendor/clap-3.2.20/examples/typed-derive.md | 84 + vendor/clap-3.2.20/examples/typed-derive.rs | 44 + vendor/clap-3.2.20/src/_cookbook/cargo_example.rs | 7 + .../clap-3.2.20/src/_cookbook/cargo_example_derive | 0 .../src/_cookbook/cargo_example_derive.rs | 7 + .../src/_cookbook/escaped_positional.rs | 7 + .../src/_cookbook/escaped_positional_derive.rs | 7 + vendor/clap-3.2.20/src/_cookbook/git.rs | 7 + vendor/clap-3.2.20/src/_cookbook/git_derive.rs | 7 + vendor/clap-3.2.20/src/_cookbook/mod.rs | 55 + .../clap-3.2.20/src/_cookbook/multicall_busybox.rs | 7 + .../src/_cookbook/multicall_hostname.rs | 7 + vendor/clap-3.2.20/src/_cookbook/pacman.rs | 7 + vendor/clap-3.2.20/src/_cookbook/repl.rs | 5 + vendor/clap-3.2.20/src/_cookbook/typed_derive.rs | 7 + vendor/clap-3.2.20/src/_derive/_tutorial.rs | 205 + vendor/clap-3.2.20/src/_derive/mod.rs | 510 + vendor/clap-3.2.20/src/_faq.rs | 95 + vendor/clap-3.2.20/src/_features.rs | 27 + vendor/clap-3.2.20/src/_tutorial.rs | 204 + vendor/clap-3.2.20/src/bin/stdio-fixture.rs | 14 + vendor/clap-3.2.20/src/builder/action.rs | 325 + vendor/clap-3.2.20/src/builder/app_settings.rs | 864 + vendor/clap-3.2.20/src/builder/arg.rs | 5494 ++++++ vendor/clap-3.2.20/src/builder/arg_group.rs | 633 + vendor/clap-3.2.20/src/builder/arg_predicate.rs | 14 + vendor/clap-3.2.20/src/builder/arg_settings.rs | 456 + vendor/clap-3.2.20/src/builder/command.rs | 5189 ++++++ vendor/clap-3.2.20/src/builder/debug_asserts.rs | 851 + vendor/clap-3.2.20/src/builder/macros.rs | 180 + vendor/clap-3.2.20/src/builder/mod.rs | 61 + vendor/clap-3.2.20/src/builder/possible_value.rs | 259 + vendor/clap-3.2.20/src/builder/regex.rs | 88 + vendor/clap-3.2.20/src/builder/tests.rs | 56 + vendor/clap-3.2.20/src/builder/usage_parser.rs | 1277 ++ vendor/clap-3.2.20/src/builder/value_hint.rs | 95 + vendor/clap-3.2.20/src/builder/value_parser.rs | 2089 +++ vendor/clap-3.2.20/src/derive.rs | 577 + vendor/clap-3.2.20/src/error/context.rs | 55 + vendor/clap-3.2.20/src/error/kind.rs | 440 + vendor/clap-3.2.20/src/error/mod.rs | 1153 ++ vendor/clap-3.2.20/src/lib.rs | 232 + vendor/clap-3.2.20/src/macros.rs | 1058 ++ vendor/clap-3.2.20/src/mkeymap.rs | 193 + vendor/clap-3.2.20/src/output/fmt.rs | 158 + vendor/clap-3.2.20/src/output/help.rs | 1176 ++ vendor/clap-3.2.20/src/output/mod.rs | 7 + vendor/clap-3.2.20/src/output/usage.rs | 449 + vendor/clap-3.2.20/src/parser/arg_matcher.rs | 280 + vendor/clap-3.2.20/src/parser/error.rs | 67 + vendor/clap-3.2.20/src/parser/features/mod.rs | 1 + .../clap-3.2.20/src/parser/features/suggestions.rs | 105 + vendor/clap-3.2.20/src/parser/matches/any_value.rs | 112 + .../clap-3.2.20/src/parser/matches/arg_matches.rs | 1896 +++ .../clap-3.2.20/src/parser/matches/matched_arg.rs | 240 + vendor/clap-3.2.20/src/parser/matches/mod.rs | 17 + .../clap-3.2.20/src/parser/matches/value_source.rs | 11 + vendor/clap-3.2.20/src/parser/mod.rs | 27 + vendor/clap-3.2.20/src/parser/parser.rs | 1729 ++ vendor/clap-3.2.20/src/parser/validator.rs | 692 + vendor/clap-3.2.20/src/util/color.rs | 62 + vendor/clap-3.2.20/src/util/fnv.rs | 46 + vendor/clap-3.2.20/src/util/graph.rs | 49 + vendor/clap-3.2.20/src/util/id.rs | 92 + vendor/clap-3.2.20/src/util/mod.rs | 40 + vendor/clap-3.2.20/src/util/str_to_bool.rs | 21 + vendor/clap/.cargo-checksum.json | 1 - vendor/clap/Cargo.lock | 745 - vendor/clap/Cargo.toml | 493 - vendor/clap/LICENSE-APACHE | 201 - vendor/clap/LICENSE-MIT | 21 - vendor/clap/README.md | 179 - vendor/clap/examples/README.md | 40 - vendor/clap/examples/cargo-example-derive.md | 45 - vendor/clap/examples/cargo-example-derive.rs | 22 - vendor/clap/examples/cargo-example.md | 45 - vendor/clap/examples/cargo-example.rs | 21 - vendor/clap/examples/demo.md | 20 - vendor/clap/examples/demo.rs | 24 - vendor/clap/examples/derive_ref/README.md | 440 - vendor/clap/examples/derive_ref/augment_args.rs | 30 - .../examples/derive_ref/augment_subcommands.rs | 21 - vendor/clap/examples/derive_ref/custom-bool.md | 47 - vendor/clap/examples/derive_ref/custom-bool.rs | 32 - .../clap/examples/derive_ref/flatten_hand_args.rs | 81 - vendor/clap/examples/derive_ref/hand_subcommand.rs | 81 - vendor/clap/examples/derive_ref/interop_tests.md | 256 - vendor/clap/examples/escaped-positional-derive.md | 65 - vendor/clap/examples/escaped-positional-derive.rs | 27 - vendor/clap/examples/escaped-positional.md | 65 - vendor/clap/examples/escaped-positional.rs | 41 - vendor/clap/examples/git-derive.md | 140 - vendor/clap/examples/git-derive.rs | 107 - vendor/clap/examples/git.md | 138 - vendor/clap/examples/git.rs | 103 - vendor/clap/examples/multicall-busybox.md | 46 - vendor/clap/examples/multicall-busybox.rs | 48 - vendor/clap/examples/multicall-hostname.md | 14 - vendor/clap/examples/multicall-hostname.rs | 17 - vendor/clap/examples/pacman.md | 87 - vendor/clap/examples/pacman.rs | 114 - vendor/clap/examples/repl.rs | 92 - vendor/clap/examples/tutorial_builder/01_quick.rs | 65 - .../examples/tutorial_builder/02_app_settings.rs | 21 - vendor/clap/examples/tutorial_builder/02_apps.rs | 20 - vendor/clap/examples/tutorial_builder/02_crate.rs | 19 - .../examples/tutorial_builder/03_01_flag_bool.rs | 21 - .../examples/tutorial_builder/03_01_flag_count.rs | 16 - .../clap/examples/tutorial_builder/03_02_option.rs | 11 - .../examples/tutorial_builder/03_03_positional.rs | 9 - .../examples/tutorial_builder/03_04_subcommands.rs | 24 - .../tutorial_builder/03_05_default_values.rs | 16 - .../clap/examples/tutorial_builder/04_01_enum.rs | 32 - .../examples/tutorial_builder/04_01_possible.rs | 28 - .../clap/examples/tutorial_builder/04_02_parse.rs | 19 - .../examples/tutorial_builder/04_02_validate.rs | 38 - .../examples/tutorial_builder/04_03_relations.rs | 82 - .../clap/examples/tutorial_builder/04_04_custom.rs | 93 - .../clap/examples/tutorial_builder/05_01_assert.rs | 26 - vendor/clap/examples/tutorial_builder/README.md | 658 - vendor/clap/examples/tutorial_derive/01_quick.rs | 69 - .../examples/tutorial_derive/02_app_settings.rs | 19 - vendor/clap/examples/tutorial_derive/02_apps.rs | 20 - vendor/clap/examples/tutorial_derive/02_crate.rs | 17 - .../examples/tutorial_derive/03_01_flag_bool.rs | 14 - .../examples/tutorial_derive/03_01_flag_count.rs | 14 - .../clap/examples/tutorial_derive/03_02_option.rs | 14 - .../examples/tutorial_derive/03_03_positional.rs | 14 - .../examples/tutorial_derive/03_04_subcommands.rs | 30 - .../tutorial_derive/03_04_subcommands_alt.rs | 33 - .../tutorial_derive/03_05_default_values.rs | 14 - vendor/clap/examples/tutorial_derive/04_01_enum.rs | 28 - .../clap/examples/tutorial_derive/04_02_parse.rs | 15 - .../examples/tutorial_derive/04_02_validate.rs | 34 - .../examples/tutorial_derive/04_03_relations.rs | 72 - .../clap/examples/tutorial_derive/04_04_custom.rs | 93 - .../clap/examples/tutorial_derive/05_01_assert.rs | 21 - vendor/clap/examples/tutorial_derive/README.md | 639 - vendor/clap/examples/typed-derive.md | 86 - vendor/clap/examples/typed-derive.rs | 46 - vendor/clap/src/bin/stdio-fixture.rs | 14 - vendor/clap/src/builder/action.rs | 325 - vendor/clap/src/builder/app_settings.rs | 862 - vendor/clap/src/builder/arg.rs | 5474 ------ vendor/clap/src/builder/arg_group.rs | 633 - vendor/clap/src/builder/arg_predicate.rs | 14 - vendor/clap/src/builder/arg_settings.rs | 457 - vendor/clap/src/builder/command.rs | 5109 ------ vendor/clap/src/builder/debug_asserts.rs | 851 - vendor/clap/src/builder/macros.rs | 180 - vendor/clap/src/builder/mod.rs | 61 - vendor/clap/src/builder/possible_value.rs | 259 - vendor/clap/src/builder/regex.rs | 88 - vendor/clap/src/builder/tests.rs | 56 - vendor/clap/src/builder/usage_parser.rs | 1277 -- vendor/clap/src/builder/value_hint.rs | 95 - vendor/clap/src/builder/value_parser.rs | 2089 --- vendor/clap/src/derive.rs | 585 - vendor/clap/src/error/context.rs | 55 - vendor/clap/src/error/kind.rs | 440 - vendor/clap/src/error/mod.rs | 1158 -- vendor/clap/src/lib.rs | 149 - vendor/clap/src/macros.rs | 1062 -- vendor/clap/src/mkeymap.rs | 193 - vendor/clap/src/output/fmt.rs | 158 - vendor/clap/src/output/help.rs | 1176 -- vendor/clap/src/output/mod.rs | 7 - vendor/clap/src/output/usage.rs | 458 - vendor/clap/src/parser/arg_matcher.rs | 282 - vendor/clap/src/parser/error.rs | 56 - vendor/clap/src/parser/features/mod.rs | 1 - vendor/clap/src/parser/features/suggestions.rs | 105 - vendor/clap/src/parser/matches/any_value.rs | 112 - vendor/clap/src/parser/matches/arg_matches.rs | 1828 -- vendor/clap/src/parser/matches/matched_arg.rs | 240 - vendor/clap/src/parser/matches/mod.rs | 17 - vendor/clap/src/parser/matches/value_source.rs | 11 - vendor/clap/src/parser/mod.rs | 27 - vendor/clap/src/parser/parser.rs | 1727 -- vendor/clap/src/parser/validator.rs | 692 - vendor/clap/src/util/color.rs | 62 - vendor/clap/src/util/fnv.rs | 46 - vendor/clap/src/util/graph.rs | 49 - vendor/clap/src/util/id.rs | 92 - vendor/clap/src/util/mod.rs | 40 - vendor/clap/src/util/str_to_bool.rs | 21 - vendor/clap_derive/.cargo-checksum.json | 2 +- vendor/clap_derive/Cargo.toml | 5 +- vendor/clap_derive/LICENSE-MIT | 2 +- vendor/clap_derive/README.md | 4 +- vendor/clap_derive/src/attrs.rs | 159 +- vendor/clap_derive/src/derives/value_enum.rs | 2 +- vendor/clap_derive/src/parse.rs | 4 + vendor/clap_lex-0.2.2/.cargo-checksum.json | 1 + vendor/clap_lex-0.2.2/Cargo.toml | 89 + vendor/clap_lex-0.2.2/LICENSE-APACHE | 201 + vendor/clap_lex-0.2.2/LICENSE-MIT | 21 + vendor/clap_lex-0.2.2/README.md | 19 + vendor/clap_lex-0.2.2/src/lib.rs | 484 + vendor/clap_lex/.cargo-checksum.json | 1 - vendor/clap_lex/Cargo.toml | 89 - vendor/clap_lex/LICENSE-APACHE | 201 - vendor/clap_lex/LICENSE-MIT | 21 - vendor/clap_lex/README.md | 19 - vendor/clap_lex/src/lib.rs | 484 - vendor/compiler_builtins/.cargo-checksum.json | 2 +- vendor/compiler_builtins/Cargo.lock | 6 +- vendor/compiler_builtins/Cargo.toml | 2 +- vendor/compiler_builtins/LICENSE.txt | 91 + vendor/compiler_builtins/build.rs | 10 +- vendor/compiler_builtins/libm/src/math/acosh.rs | 1 + vendor/compiler_builtins/libm/src/math/acoshf.rs | 1 + vendor/compiler_builtins/libm/src/math/asinh.rs | 1 + vendor/compiler_builtins/libm/src/math/asinhf.rs | 1 + vendor/compiler_builtins/libm/src/math/atanh.rs | 1 + vendor/compiler_builtins/libm/src/math/atanhf.rs | 1 + vendor/compiler_builtins/libm/src/math/copysign.rs | 1 + .../compiler_builtins/libm/src/math/copysignf.rs | 1 + vendor/compiler_builtins/libm/src/math/erf.rs | 1 + vendor/compiler_builtins/libm/src/math/erff.rs | 1 + vendor/compiler_builtins/libm/src/math/exp10.rs | 5 +- vendor/compiler_builtins/libm/src/math/exp10f.rs | 5 +- vendor/compiler_builtins/libm/src/math/fenv.rs | 6 - vendor/compiler_builtins/libm/src/math/fmaf.rs | 35 +- vendor/compiler_builtins/libm/src/math/ilogb.rs | 1 + vendor/compiler_builtins/libm/src/math/ilogbf.rs | 1 + vendor/compiler_builtins/libm/src/math/lgamma.rs | 1 + vendor/compiler_builtins/libm/src/math/lgamma_r.rs | 3 +- vendor/compiler_builtins/libm/src/math/lgammaf.rs | 1 + .../compiler_builtins/libm/src/math/lgammaf_r.rs | 3 +- .../libm/src/math/rem_pio2_large.rs | 2 +- vendor/compiler_builtins/libm/src/math/sincos.rs | 1 + vendor/compiler_builtins/libm/src/math/sincosf.rs | 1 + vendor/compiler_builtins/libm/src/math/tgamma.rs | 13 +- vendor/compiler_builtins/libm/src/math/tgammaf.rs | 1 + vendor/compiler_builtins/src/arm.rs | 4 + vendor/compiler_builtins/src/arm_linux.rs | 110 +- vendor/compiler_builtins/src/float/conv.rs | 14 +- vendor/compiler_builtins/src/float/div.rs | 6 +- .../src/int/specialized_div_rem/mod.rs | 5 +- vendor/compiler_builtins/src/lib.rs | 2 + vendor/compiler_builtins/src/macros.rs | 13 +- vendor/compiler_builtins/src/math.rs | 24 +- vendor/compiler_builtins/src/mem/impls.rs | 14 + vendor/compiler_builtins/src/mem/mod.rs | 11 +- vendor/compiler_builtins/src/mem/x86_64.rs | 150 +- vendor/compiletest_rs/.cargo-checksum.json | 2 +- vendor/compiletest_rs/Cargo.toml | 2 +- vendor/compiletest_rs/README.md | 4 +- vendor/compiletest_rs/src/runtest.rs | 47 +- vendor/crossbeam-channel/.cargo-checksum.json | 2 +- vendor/crossbeam-channel/CHANGELOG.md | 4 + vendor/crossbeam-channel/Cargo.lock | 10 +- vendor/crossbeam-channel/Cargo.toml | 4 +- vendor/crossbeam-channel/README.md | 4 +- vendor/crossbeam-channel/src/flavors/array.rs | 4 +- vendor/crossbeam-channel/src/flavors/list.rs | 18 +- vendor/crossbeam-channel/src/flavors/zero.rs | 10 +- vendor/crossbeam-channel/tests/array.rs | 6 +- vendor/crossbeam-channel/tests/golang.rs | 7 +- vendor/crossbeam-channel/tests/list.rs | 3 +- vendor/crossbeam-channel/tests/mpsc.rs | 15 +- vendor/crossbeam-channel/tests/select.rs | 1 - vendor/crossbeam-channel/tests/select_macro.rs | 1 - vendor/crossbeam-channel/tests/thread_locals.rs | 2 +- vendor/crossbeam-channel/tests/zero.rs | 8 +- vendor/crossbeam-deque/.cargo-checksum.json | 2 +- vendor/crossbeam-deque/CHANGELOG.md | 18 + vendor/crossbeam-deque/Cargo.toml | 26 +- vendor/crossbeam-deque/README.md | 4 +- vendor/crossbeam-deque/src/deque.rs | 76 +- vendor/crossbeam-deque/src/lib.rs | 1 + vendor/crossbeam-deque/tests/fifo.rs | 21 +- vendor/crossbeam-deque/tests/injector.rs | 28 +- vendor/crossbeam-deque/tests/lifo.rs | 23 +- vendor/crossbeam-epoch/.cargo-checksum.json | 2 +- vendor/crossbeam-epoch/CHANGELOG.md | 11 + vendor/crossbeam-epoch/Cargo.lock | 119 +- vendor/crossbeam-epoch/Cargo.toml | 9 +- vendor/crossbeam-epoch/README.md | 4 +- vendor/crossbeam-epoch/build.rs | 12 +- vendor/crossbeam-epoch/no_atomic.rs | 6 + vendor/crossbeam-epoch/src/atomic.rs | 108 +- vendor/crossbeam-epoch/src/collector.rs | 6 +- vendor/crossbeam-epoch/src/default.rs | 34 +- vendor/crossbeam-epoch/src/deferred.rs | 19 +- vendor/crossbeam-epoch/src/guard.rs | 6 + vendor/crossbeam-epoch/src/internal.rs | 109 +- vendor/crossbeam-epoch/src/lib.rs | 2 +- vendor/crossbeam-epoch/src/sync/mod.rs | 3 + vendor/crossbeam-epoch/src/sync/once_lock.rs | 103 + vendor/crossbeam-queue/.cargo-checksum.json | 1 - vendor/crossbeam-queue/CHANGELOG.md | 54 - vendor/crossbeam-queue/Cargo.toml | 51 - vendor/crossbeam-queue/LICENSE-APACHE | 201 - vendor/crossbeam-queue/LICENSE-MIT | 27 - vendor/crossbeam-queue/README.md | 54 - vendor/crossbeam-queue/build.rs | 41 - vendor/crossbeam-queue/no_atomic.rs | 73 - vendor/crossbeam-queue/src/array_queue.rs | 522 - vendor/crossbeam-queue/src/lib.rs | 34 - vendor/crossbeam-queue/src/seg_queue.rs | 545 - vendor/crossbeam-queue/tests/array_queue.rs | 359 - vendor/crossbeam-queue/tests/seg_queue.rs | 190 - vendor/crossbeam-utils/.cargo-checksum.json | 2 +- vendor/crossbeam-utils/CHANGELOG.md | 9 + vendor/crossbeam-utils/Cargo.toml | 10 +- vendor/crossbeam-utils/README.md | 4 +- vendor/crossbeam-utils/build.rs | 7 +- vendor/crossbeam-utils/no_atomic.rs | 6 + vendor/crossbeam-utils/src/atomic/atomic_cell.rs | 17 +- vendor/crossbeam-utils/src/backoff.rs | 2 + vendor/crossbeam-utils/src/cache_padded.rs | 6 +- vendor/crossbeam-utils/src/sync/mod.rs | 2 + vendor/crossbeam-utils/src/sync/once_lock.rs | 103 + vendor/crossbeam-utils/src/sync/parker.rs | 6 +- vendor/crossbeam-utils/src/sync/sharded_lock.rs | 24 +- vendor/crossbeam-utils/src/sync/wait_group.rs | 5 +- vendor/crossbeam-utils/tests/wait_group.rs | 5 +- vendor/crossbeam/.cargo-checksum.json | 1 - vendor/crossbeam/CHANGELOG.md | 93 - vendor/crossbeam/Cargo.toml | 59 - vendor/crossbeam/LICENSE-APACHE | 201 - vendor/crossbeam/LICENSE-MIT | 27 - vendor/crossbeam/README.md | 158 - vendor/crossbeam/no_atomic.rs | 59 - vendor/crossbeam/src/lib.rs | 96 - vendor/crossbeam/tests/subcrates.rs | 47 - vendor/dashmap/.cargo-checksum.json | 2 +- vendor/dashmap/Cargo.toml | 13 +- vendor/dashmap/src/lib.rs | 59 +- vendor/dashmap/src/rayon/map.rs | 4 +- vendor/dashmap/src/rayon/read_only.rs | 96 + vendor/dashmap/src/read_only.rs | 2 +- vendor/dashmap/src/table.rs | 81 - vendor/digest-0.8.1/.cargo-checksum.json | 1 - vendor/digest-0.8.1/Cargo.toml | 36 - vendor/digest-0.8.1/LICENSE-APACHE | 201 - vendor/digest-0.8.1/LICENSE-MIT | 25 - vendor/digest-0.8.1/src/dev.rs | 218 - vendor/digest-0.8.1/src/digest.rs | 86 - vendor/digest-0.8.1/src/dyn_digest.rs | 63 - vendor/digest-0.8.1/src/errors.rs | 20 - vendor/digest-0.8.1/src/lib.rs | 141 - vendor/either/.cargo-checksum.json | 2 +- vendor/either/Cargo.toml | 4 +- vendor/either/README.rst | 13 +- vendor/either/src/lib.rs | 71 + vendor/fake-simd/.cargo-checksum.json | 1 - vendor/fake-simd/Cargo.toml | 9 - vendor/fake-simd/LICENSE-APACHE | 201 - vendor/fake-simd/LICENSE-MIT | 26 - vendor/fake-simd/src/lib.rs | 108 - vendor/form_urlencoded/.cargo-checksum.json | 2 +- vendor/form_urlencoded/Cargo.toml | 18 +- vendor/form_urlencoded/src/lib.rs | 6 +- vendor/fortanix-sgx-abi/.cargo-checksum.json | 2 +- vendor/fortanix-sgx-abi/Cargo.toml | 36 +- vendor/fortanix-sgx-abi/src/lib.rs | 164 +- vendor/fs-err/.cargo-checksum.json | 2 +- vendor/fs-err/CHANGELOG.md | 19 +- vendor/fs-err/Cargo.toml | 45 +- vendor/fs-err/README.md | 2 +- vendor/fs-err/README.tpl | 28 - vendor/fs-err/src/dir.rs | 13 +- vendor/fs-err/src/errors.rs | 30 +- vendor/fs-err/src/file.rs | 76 +- vendor/fs-err/src/lib.rs | 43 +- vendor/fs-err/src/open_options.rs | 1 + vendor/fs-err/src/os/unix.rs | 6 +- vendor/fs-err/src/os/windows.rs | 4 +- vendor/fs-err/src/path.rs | 2 +- vendor/fs-err/tests/version-numbers.rs | 9 - vendor/generic-array-0.12.4/.cargo-checksum.json | 1 - vendor/generic-array-0.12.4/CHANGELOG.md | 51 - vendor/generic-array-0.12.4/Cargo.toml | 40 - vendor/generic-array-0.12.4/LICENSE | 21 - vendor/generic-array-0.12.4/README.md | 34 - vendor/generic-array-0.12.4/rustfmt.toml | 3 - vendor/generic-array-0.12.4/src/arr.rs | 126 - vendor/generic-array-0.12.4/src/functional.rs | 94 - vendor/generic-array-0.12.4/src/hex.rs | 102 - vendor/generic-array-0.12.4/src/impl_serde.rs | 108 - vendor/generic-array-0.12.4/src/impls.rs | 182 - vendor/generic-array-0.12.4/src/iter.rs | 190 - vendor/generic-array-0.12.4/src/lib.rs | 632 - vendor/generic-array-0.12.4/src/sequence.rs | 320 - vendor/generic-array-0.12.4/tests/arr.rs | 27 - vendor/generic-array-0.12.4/tests/generics.rs | 98 - vendor/generic-array-0.12.4/tests/hex.rs | 61 - vendor/generic-array-0.12.4/tests/import_name.rs | 10 - vendor/generic-array-0.12.4/tests/iter.rs | 164 - vendor/generic-array-0.12.4/tests/mod.rs | 287 - vendor/getrandom/.cargo-checksum.json | 2 +- vendor/getrandom/CHANGELOG.md | 18 +- vendor/getrandom/Cargo.toml | 38 +- vendor/getrandom/src/bsd_arandom.rs | 1 + vendor/getrandom/src/dragonfly.rs | 1 + vendor/getrandom/src/error.rs | 4 - vendor/getrandom/src/lib.rs | 2 +- vendor/getrandom/src/linux_android.rs | 1 + vendor/getrandom/src/macos.rs | 1 + vendor/getrandom/src/openbsd.rs | 1 + vendor/getrandom/src/solaris_illumos.rs | 1 + vendor/getrandom/src/util_libc.rs | 57 +- vendor/getrandom/src/wasi.rs | 12 +- vendor/getrandom/src/windows.rs | 1 + vendor/gimli/.cargo-checksum.json | 2 +- vendor/gimli/CHANGELOG.md | 22 + vendor/gimli/Cargo.lock | 37 +- vendor/gimli/Cargo.toml | 79 +- vendor/gimli/README.md | 6 +- vendor/gimli/examples/dwarf-validate.rs | 2 +- vendor/gimli/examples/dwarfdump.rs | 45 +- vendor/gimli/examples/simple.rs | 2 +- vendor/gimli/examples/simple_line.rs | 13 +- vendor/gimli/fixtures/self/README.md | 2 +- vendor/gimli/src/constants.rs | 2 +- vendor/gimli/src/lib.rs | 2 +- vendor/gimli/src/read/abbrev.rs | 2 +- vendor/gimli/src/read/aranges.rs | 2 +- vendor/gimli/src/read/cfi.rs | 134 +- vendor/gimli/src/read/line.rs | 2 +- vendor/gimli/src/read/lists.rs | 1 + vendor/gimli/src/read/loclists.rs | 4 +- vendor/gimli/src/read/mod.rs | 2 +- vendor/gimli/src/read/op.rs | 21 +- vendor/gimli/src/read/pubnames.rs | 2 +- vendor/gimli/src/read/pubtypes.rs | 2 +- vendor/gimli/src/read/rnglists.rs | 4 +- vendor/gimli/src/read/str.rs | 4 +- vendor/gimli/src/read/unit.rs | 4 +- vendor/gimli/src/read/util.rs | 2 +- vendor/gimli/src/read/value.rs | 2 - vendor/gimli/src/write/cfi.rs | 15 +- vendor/gimli/src/write/op.rs | 6 +- vendor/gimli/tests/convert_self.rs | 2 +- vendor/handlebars/.cargo-checksum.json | 2 +- vendor/handlebars/CHANGELOG.md | 75 + vendor/handlebars/Cargo.lock | 1384 +- vendor/handlebars/Cargo.toml | 89 +- vendor/handlebars/README.md | 26 +- vendor/handlebars/examples/dev_mode.rs | 24 +- vendor/handlebars/examples/error.rs | 52 +- vendor/handlebars/examples/helper_macro.rs | 63 + vendor/handlebars/examples/partials.rs | 19 +- vendor/handlebars/examples/script.rs | 7 - vendor/handlebars/release.toml | 2 + vendor/handlebars/src/context.rs | 19 +- vendor/handlebars/src/decorators/mod.rs | 12 +- vendor/handlebars/src/error.rs | 98 +- vendor/handlebars/src/grammar.pest | 27 +- vendor/handlebars/src/grammar.rs | 29 +- vendor/handlebars/src/helpers/helper_each.rs | 94 +- vendor/handlebars/src/helpers/helper_if.rs | 40 +- vendor/handlebars/src/helpers/helper_lookup.rs | 12 +- vendor/handlebars/src/helpers/helper_with.rs | 15 +- vendor/handlebars/src/helpers/mod.rs | 3 +- vendor/handlebars/src/helpers/scripting.rs | 14 +- vendor/handlebars/src/json/path.rs | 4 +- vendor/handlebars/src/lib.rs | 21 +- vendor/handlebars/src/macros.rs | 7 +- vendor/handlebars/src/output.rs | 6 + vendor/handlebars/src/partial.rs | 363 +- vendor/handlebars/src/registry.rs | 272 +- vendor/handlebars/src/render.rs | 93 +- vendor/handlebars/src/support.rs | 58 + vendor/handlebars/src/template.rs | 233 +- vendor/handlebars/tests/embed.rs | 29 + vendor/handlebars/tests/escape.rs | 42 +- vendor/handlebars/tests/helper_macro.rs | 13 + vendor/handlebars/tests/helper_with_space.rs | 54 + vendor/handlebars/tests/templates/hello.hbs | 1 + vendor/handlebars/tests/whitespace.rs | 24 + vendor/hermit-abi/.cargo-checksum.json | 2 +- vendor/hermit-abi/Cargo.toml | 31 +- vendor/hermit-abi/src/errno.rs | 397 + vendor/hermit-abi/src/lib.rs | 74 +- vendor/home/.cargo-checksum.json | 2 +- vendor/home/Cargo.toml | 26 +- vendor/home/src/env.rs | 106 + vendor/home/src/lib.rs | 48 +- vendor/idna/.cargo-checksum.json | 2 +- vendor/idna/Cargo.toml | 23 +- vendor/idna/LICENSE-MIT | 2 +- vendor/idna/src/lib.rs | 3 +- vendor/idna/src/uts46.rs | 76 +- vendor/idna/tests/punycode.rs | 4 +- vendor/idna/tests/tests.rs | 12 +- vendor/idna/tests/uts46.rs | 13 +- vendor/itertools/.cargo-checksum.json | 2 +- vendor/itertools/CHANGELOG.md | 7 + vendor/itertools/Cargo.lock | 726 - vendor/itertools/Cargo.toml | 4 +- vendor/itertools/README.md | 2 +- vendor/itertools/benches/extra/zipslices.rs | 2 +- vendor/itertools/clippy.toml | 1 + vendor/itertools/src/adaptors/coalesce.rs | 4 +- vendor/itertools/src/adaptors/mod.rs | 14 +- vendor/itertools/src/adaptors/multi_product.rs | 4 +- .../itertools/src/combinations_with_replacement.rs | 4 +- vendor/itertools/src/concat_impl.rs | 3 +- vendor/itertools/src/duplicates_impl.rs | 1 - vendor/itertools/src/either_or_both.rs | 49 + vendor/itertools/src/exactly_one_err.rs | 4 +- vendor/itertools/src/extrema_set.rs | 48 + vendor/itertools/src/flatten_ok.rs | 33 +- vendor/itertools/src/free.rs | 26 +- vendor/itertools/src/groupbylazy.rs | 12 +- vendor/itertools/src/grouping_map.rs | 7 +- vendor/itertools/src/impl_macros.rs | 1 + vendor/itertools/src/intersperse.rs | 5 +- vendor/itertools/src/kmerge_impl.rs | 8 +- vendor/itertools/src/lazy_buffer.rs | 20 +- vendor/itertools/src/lib.rs | 230 +- vendor/itertools/src/merge_join.rs | 4 +- vendor/itertools/src/multipeek_impl.rs | 10 +- vendor/itertools/src/pad_tail.rs | 2 +- vendor/itertools/src/peeking_take_while.rs | 2 +- vendor/itertools/src/permutations.rs | 7 +- vendor/itertools/src/rciter_impl.rs | 1 - vendor/itertools/src/size_hint.rs | 16 +- vendor/itertools/src/tuple_impl.rs | 2 +- vendor/itertools/src/unique_impl.rs | 7 +- vendor/itertools/src/unziptuple.rs | 8 +- vendor/itertools/src/ziptuple.rs | 1 + vendor/itertools/tests/adaptors_no_collect.rs | 11 +- vendor/itertools/tests/quick.rs | 116 +- vendor/itertools/tests/specializations.rs | 4 +- vendor/itertools/tests/test_core.rs | 15 +- vendor/itertools/tests/test_std.rs | 80 +- vendor/itertools/tests/zip.rs | 8 +- vendor/itoa/.cargo-checksum.json | 2 +- vendor/itoa/Cargo.toml | 12 +- vendor/itoa/README.md | 2 +- vendor/itoa/src/lib.rs | 10 +- vendor/itoa/src/udiv128.rs | 5 + vendor/lazycell/.cargo-checksum.json | 1 + vendor/lazycell/CHANGELOG.md | 197 + vendor/lazycell/Cargo.toml | 34 + vendor/lazycell/LICENSE-APACHE | 201 + vendor/lazycell/LICENSE-MIT | 26 + vendor/lazycell/README.md | 73 + vendor/lazycell/src/lib.rs | 680 + vendor/lazycell/src/serde_impl.rs | 86 + vendor/libc/.cargo-checksum.json | 2 +- vendor/libc/CONTRIBUTING.md | 4 + vendor/libc/Cargo.toml | 2 +- vendor/libc/README.md | 8 +- vendor/libc/build.rs | 15 +- vendor/libc/src/fuchsia/mod.rs | 38 +- vendor/libc/src/lib.rs | 10 +- vendor/libc/src/macros.rs | 16 - .../libc/src/unix/bsd/apple/b64/aarch64/align.rs | 1 + vendor/libc/src/unix/bsd/apple/mod.rs | 404 +- .../libc/src/unix/bsd/freebsdlike/dragonfly/mod.rs | 80 + .../unix/bsd/freebsdlike/freebsd/freebsd11/mod.rs | 8 + .../unix/bsd/freebsdlike/freebsd/freebsd12/mod.rs | 13 + .../unix/bsd/freebsdlike/freebsd/freebsd13/mod.rs | 13 + .../unix/bsd/freebsdlike/freebsd/freebsd14/mod.rs | 13 + .../libc/src/unix/bsd/freebsdlike/freebsd/mod.rs | 181 +- vendor/libc/src/unix/bsd/freebsdlike/mod.rs | 55 + vendor/libc/src/unix/bsd/mod.rs | 6 + vendor/libc/src/unix/bsd/netbsdlike/mod.rs | 11 - vendor/libc/src/unix/bsd/netbsdlike/netbsd/mod.rs | 197 +- vendor/libc/src/unix/bsd/netbsdlike/openbsd/mod.rs | 27 + vendor/libc/src/unix/haiku/mod.rs | 92 +- vendor/libc/src/unix/linux_like/android/b64/mod.rs | 3 + .../unix/linux_like/android/b64/riscv64/align.rs | 7 + .../src/unix/linux_like/android/b64/riscv64/mod.rs | 342 + .../src/unix/linux_like/android/b64/x86_64/mod.rs | 2 + vendor/libc/src/unix/linux_like/android/mod.rs | 238 +- vendor/libc/src/unix/linux_like/emscripten/mod.rs | 6 +- .../src/unix/linux_like/linux/arch/generic/mod.rs | 7 + .../src/unix/linux_like/linux/gnu/b32/arm/mod.rs | 8 + .../src/unix/linux_like/linux/gnu/b32/mips/mod.rs | 8 + .../src/unix/linux_like/linux/gnu/b32/powerpc.rs | 8 + .../unix/linux_like/linux/gnu/b32/riscv32/mod.rs | 8 + .../src/unix/linux_like/linux/gnu/b32/sparc/mod.rs | 8 + .../src/unix/linux_like/linux/gnu/b32/x86/mod.rs | 8 + .../unix/linux_like/linux/gnu/b64/aarch64/align.rs | 22 + .../unix/linux_like/linux/gnu/b64/aarch64/mod.rs | 24 + .../unix/linux_like/linux/gnu/b64/mips64/mod.rs | 8 + .../unix/linux_like/linux/gnu/b64/powerpc64/mod.rs | 8 + .../unix/linux_like/linux/gnu/b64/riscv64/mod.rs | 8 + .../src/unix/linux_like/linux/gnu/b64/s390x.rs | 8 + .../unix/linux_like/linux/gnu/b64/sparc64/mod.rs | 8 + .../unix/linux_like/linux/gnu/b64/x86_64/align.rs | 17 + .../unix/linux_like/linux/gnu/b64/x86_64/mod.rs | 22 + .../linux_like/linux/gnu/b64/x86_64/not_x32.rs | 8 + .../unix/linux_like/linux/gnu/b64/x86_64/x32.rs | 8 + vendor/libc/src/unix/linux_like/linux/gnu/mod.rs | 30 + vendor/libc/src/unix/linux_like/linux/mod.rs | 328 +- .../src/unix/linux_like/linux/musl/b32/arm/mod.rs | 8 + .../src/unix/linux_like/linux/musl/b32/mips/mod.rs | 8 + .../libc/src/unix/linux_like/linux/musl/b32/mod.rs | 1 + .../src/unix/linux_like/linux/musl/b32/powerpc.rs | 8 + .../unix/linux_like/linux/musl/b32/riscv32/mod.rs | 1 + .../src/unix/linux_like/linux/musl/b32/x86/mod.rs | 8 + .../linux_like/linux/musl/b64/aarch64/align.rs | 15 + .../unix/linux_like/linux/musl/b64/aarch64/mod.rs | 9 + .../src/unix/linux_like/linux/musl/b64/mips64.rs | 11 +- .../unix/linux_like/linux/musl/b64/powerpc64.rs | 9 + .../unix/linux_like/linux/musl/b64/riscv64/mod.rs | 1 + .../src/unix/linux_like/linux/musl/b64/s390x.rs | 10 + .../unix/linux_like/linux/musl/b64/x86_64/align.rs | 18 + .../unix/linux_like/linux/musl/b64/x86_64/mod.rs | 9 + vendor/libc/src/unix/linux_like/linux/musl/mod.rs | 5 + .../src/unix/linux_like/linux/uclibc/arm/mod.rs | 1 + .../libc/src/unix/linux_like/linux/uclibc/mod.rs | 2 + .../src/unix/linux_like/linux/uclibc/x86_64/mod.rs | 1 + vendor/libc/src/unix/linux_like/mod.rs | 15 +- vendor/libc/src/unix/mod.rs | 16 +- vendor/libc/src/unix/newlib/espidf/mod.rs | 5 + vendor/libc/src/unix/newlib/mod.rs | 2 +- vendor/libc/src/unix/solarish/illumos.rs | 5 + vendor/libc/src/unix/solarish/mod.rs | 18 +- vendor/libc/src/unix/solarish/solaris.rs | 11 +- vendor/libc/src/unix/solarish/x86_64.rs | 31 + vendor/libc/src/windows/mod.rs | 12 +- vendor/lock_api/.cargo-checksum.json | 2 +- vendor/lock_api/Cargo.toml | 2 +- vendor/lock_api/src/mutex.rs | 29 +- vendor/lock_api/src/remutex.rs | 8 +- vendor/lock_api/src/rwlock.rs | 10 +- vendor/lsp-types/.cargo-checksum.json | 2 +- vendor/lsp-types/CHANGELOG.md | 6 + vendor/lsp-types/Cargo.toml | 3 +- vendor/lsp-types/README.md | 2 +- vendor/lsp-types/src/lib.rs | 5 +- vendor/lsp-types/src/semantic_tokens.rs | 32 +- vendor/matches/.cargo-checksum.json | 1 - vendor/matches/Cargo.toml | 24 - vendor/matches/LICENSE | 25 - vendor/matches/lib.rs | 128 - vendor/matches/tests/macro_use_one.rs | 11 - vendor/matches/tests/use_star.rs | 10 - vendor/memmap2/.cargo-checksum.json | 2 +- vendor/memmap2/CHANGELOG.md | 22 +- vendor/memmap2/Cargo.lock | 2 +- vendor/memmap2/Cargo.toml | 3 +- vendor/memmap2/src/lib.rs | 149 +- vendor/memmap2/src/unix.rs | 42 +- vendor/memmap2/src/windows.rs | 43 +- vendor/minifier/.cargo-checksum.json | 2 +- vendor/minifier/Cargo.lock | 2 +- vendor/minifier/Cargo.toml | 2 +- vendor/minifier/src/css/token.rs | 51 +- vendor/miniz_oxide/.cargo-checksum.json | 2 +- vendor/miniz_oxide/Cargo.toml | 27 +- vendor/miniz_oxide/src/inflate/mod.rs | 12 +- vendor/once_cell/.cargo-checksum.json | 2 +- vendor/once_cell/CHANGELOG.md | 17 + vendor/once_cell/Cargo.lock | 210 +- vendor/once_cell/Cargo.toml | 8 +- vendor/once_cell/examples/lazy_static.rs | 2 +- vendor/once_cell/src/imp_std.rs | 93 +- vendor/once_cell/src/lib.rs | 80 +- vendor/once_cell/tests/it.rs | 35 + vendor/opaque-debug/.cargo-checksum.json | 1 - vendor/opaque-debug/Cargo.toml | 22 - vendor/opaque-debug/LICENSE-APACHE | 201 - vendor/opaque-debug/LICENSE-MIT | 25 - vendor/opaque-debug/src/lib.rs | 24 - vendor/percent-encoding/.cargo-checksum.json | 2 +- vendor/percent-encoding/Cargo.toml | 21 +- vendor/percent-encoding/LICENSE-MIT | 2 +- vendor/percent-encoding/lib.rs | 442 - vendor/percent-encoding/src/lib.rs | 468 + vendor/pest/.cargo-checksum.json | 2 +- vendor/pest/Cargo.lock | 80 +- vendor/pest/Cargo.toml | 45 +- vendor/pest/_README.md | 23 +- vendor/pest/examples/parens.rs | 4 +- vendor/pest/src/error.rs | 172 +- vendor/pest/src/iterators/flat_pairs.rs | 9 +- vendor/pest/src/iterators/pair.rs | 22 +- vendor/pest/src/iterators/pairs.rs | 19 +- vendor/pest/src/iterators/tokens.rs | 14 +- vendor/pest/src/lib.rs | 20 +- vendor/pest/src/macros.rs | 114 +- vendor/pest/src/parser.rs | 6 +- vendor/pest/src/parser_state.rs | 132 +- vendor/pest/src/position.rs | 81 +- vendor/pest/src/prec_climber.rs | 171 +- vendor/pest/src/span.rs | 189 +- vendor/pest/src/stack.rs | 4 +- vendor/pest/src/token.rs | 2 +- vendor/pest/src/unicode/binary.rs | 3210 ++-- vendor/pest/src/unicode/category.rs | 2175 +-- vendor/pest/src/unicode/mod.rs | 2 + vendor/pest/tests/calculator.rs | 18 +- vendor/pest/tests/json.rs | 75 +- vendor/pest_derive/.cargo-checksum.json | 2 +- vendor/pest_derive/Cargo.toml | 40 +- vendor/pest_derive/_README.md | 37 +- vendor/pest_derive/src/lib.rs | 7 +- vendor/pest_derive/tests/grammar.pest | 4 + vendor/pest_derive/tests/grammar.rs | 31 + vendor/pest_derive/tests/grammar_inline.rs | 4 + vendor/pest_derive/tests/lists.rs | 4 + vendor/pest_derive/tests/reporting.rs | 4 + vendor/pest_generator/.cargo-checksum.json | 2 +- vendor/pest_generator/Cargo.toml | 34 +- vendor/pest_generator/_README.md | 23 +- vendor/pest_generator/src/generator.rs | 72 +- vendor/pest_generator/src/macros.rs | 14 +- vendor/pest_meta/.cargo-checksum.json | 2 +- vendor/pest_meta/Cargo.toml | 46 +- vendor/pest_meta/_README.md | 23 +- vendor/pest_meta/src/ast.rs | 2 +- vendor/pest_meta/src/grammar.pest | 2 +- vendor/pest_meta/src/grammar.rs | 2 +- vendor/pest_meta/src/lib.rs | 20 +- vendor/pest_meta/src/optimizer/concatenator.rs | 39 +- vendor/pest_meta/src/optimizer/factorizer.rs | 61 +- vendor/pest_meta/src/optimizer/lister.rs | 42 + vendor/pest_meta/src/optimizer/mod.rs | 104 +- vendor/pest_meta/src/optimizer/restorer.rs | 14 +- vendor/pest_meta/src/optimizer/rotater.rs | 13 +- vendor/pest_meta/src/optimizer/skipper.rs | 39 +- vendor/pest_meta/src/optimizer/unroller.rs | 107 +- vendor/pest_meta/src/parser.rs | 93 +- vendor/pest_meta/src/validator.rs | 222 +- .../pretty_assertions-0.7.2/.cargo-checksum.json | 1 - vendor/pretty_assertions-0.7.2/CHANGELOG.md | 38 - vendor/pretty_assertions-0.7.2/Cargo.lock | 102 - vendor/pretty_assertions-0.7.2/Cargo.toml | 36 - vendor/pretty_assertions-0.7.2/LICENSE-APACHE | 202 - vendor/pretty_assertions-0.7.2/LICENSE-MIT | 21 - vendor/pretty_assertions-0.7.2/README.md | 91 - .../examples/pretty_assertion.png | Bin 21419 -> 0 bytes .../examples/pretty_assertion.rs | 3 - .../examples/pretty_assertion_v0_6_1.png | Bin 21236 -> 0 bytes .../examples/standard_assertion.png | Bin 21727 -> 0 bytes .../examples/standard_assertion.rs | 21 - vendor/pretty_assertions-0.7.2/scripts/check | 9 - vendor/pretty_assertions-0.7.2/scripts/install | 6 - vendor/pretty_assertions-0.7.2/scripts/publish | 11 - vendor/pretty_assertions-0.7.2/src/lib.rs | 475 - vendor/pretty_assertions-0.7.2/src/printer.rs | 474 - vendor/pretty_assertions/.cargo-checksum.json | 1 + vendor/pretty_assertions/CHANGELOG.md | 38 + vendor/pretty_assertions/Cargo.lock | 102 + vendor/pretty_assertions/Cargo.toml | 36 + vendor/pretty_assertions/LICENSE-APACHE | 202 + vendor/pretty_assertions/LICENSE-MIT | 21 + vendor/pretty_assertions/README.md | 91 + .../examples/pretty_assertion.png | Bin 0 -> 21419 bytes .../pretty_assertions/examples/pretty_assertion.rs | 3 + .../examples/pretty_assertion_v0_6_1.png | Bin 0 -> 21236 bytes .../examples/standard_assertion.png | Bin 0 -> 21727 bytes .../examples/standard_assertion.rs | 21 + vendor/pretty_assertions/scripts/check | 9 + vendor/pretty_assertions/scripts/install | 6 + vendor/pretty_assertions/scripts/publish | 11 + vendor/pretty_assertions/src/lib.rs | 475 + vendor/pretty_assertions/src/printer.rs | 474 + vendor/proc-macro2/.cargo-checksum.json | 2 +- vendor/proc-macro2/Cargo.toml | 12 +- vendor/proc-macro2/build.rs | 5 +- vendor/proc-macro2/src/detection.rs | 2 +- vendor/proc-macro2/src/fallback.rs | 197 +- vendor/proc-macro2/src/lib.rs | 63 +- vendor/proc-macro2/src/marker.rs | 4 +- vendor/proc-macro2/src/parse.rs | 77 +- vendor/proc-macro2/src/rcvec.rs | 142 + vendor/proc-macro2/src/wrapper.rs | 30 +- vendor/proc-macro2/tests/comments.rs | 2 + vendor/proc-macro2/tests/test.rs | 22 +- vendor/quick-error-1.2.3/.cargo-checksum.json | 1 - vendor/quick-error-1.2.3/Cargo.lock | 6 - vendor/quick-error-1.2.3/Cargo.toml | 23 - vendor/quick-error-1.2.3/LICENSE-APACHE | 202 - vendor/quick-error-1.2.3/LICENSE-MIT | 19 - vendor/quick-error-1.2.3/README.rst | 66 - vendor/quick-error-1.2.3/bulk.yaml | 8 - vendor/quick-error-1.2.3/examples/context.rs | 48 - vendor/quick-error-1.2.3/src/lib.rs | 1262 -- vendor/quick-error-1.2.3/vagga.yaml | 36 - vendor/quick-error/.cargo-checksum.json | 2 +- vendor/quick-error/Cargo.lock | 3 +- vendor/quick-error/Cargo.toml | 3 +- vendor/quick-error/README.rst | 6 +- vendor/quick-error/examples/context.rs | 21 +- vendor/quick-error/src/lib.rs | 292 +- vendor/quick-error/vagga.yaml | 6 +- vendor/quote/.cargo-checksum.json | 2 +- vendor/quote/Cargo.toml | 7 +- vendor/quote/src/ext.rs | 4 +- vendor/quote/src/ident_fragment.rs | 2 +- vendor/quote/src/lib.rs | 2 +- vendor/quote/src/runtime.rs | 10 +- vendor/quote/src/to_tokens.rs | 6 +- .../ui/does-not-have-iter-interpolated-dup.stderr | 2 +- .../ui/does-not-have-iter-interpolated.stderr | 2 +- .../tests/ui/does-not-have-iter-separated.stderr | 2 +- vendor/quote/tests/ui/does-not-have-iter.stderr | 2 +- vendor/quote/tests/ui/not-repeatable.stderr | 76 +- vendor/redox_syscall/.cargo-checksum.json | 2 +- vendor/redox_syscall/Cargo.toml | 2 +- vendor/redox_syscall/src/arch/x86.rs | 105 + vendor/redox_syscall/src/io/mod.rs | 4 +- vendor/redox_syscall/src/lib.rs | 2 +- vendor/regex-syntax/.cargo-checksum.json | 2 +- vendor/regex-syntax/Cargo.toml | 2 +- vendor/regex-syntax/src/ast/mod.rs | 6 +- vendor/regex-syntax/src/ast/parse.rs | 144 +- vendor/regex-syntax/src/ast/visitor.rs | 12 +- vendor/regex-syntax/src/error.rs | 4 +- vendor/regex-syntax/src/hir/interval.rs | 4 +- vendor/regex-syntax/src/hir/literal/mod.rs | 28 +- vendor/regex-syntax/src/hir/mod.rs | 18 +- vendor/regex-syntax/src/hir/translate.rs | 20 +- vendor/regex-syntax/src/lib.rs | 2 +- vendor/regex-syntax/src/parser.rs | 2 +- vendor/regex-syntax/src/unicode.rs | 7 +- vendor/regex-syntax/src/unicode_tables/age.rs | 198 +- .../src/unicode_tables/case_folding_simple.rs | 98 +- .../src/unicode_tables/general_category.rs | 747 +- .../src/unicode_tables/grapheme_cluster_break.rs | 49 +- .../src/unicode_tables/perl_decimal.rs | 11 +- .../regex-syntax/src/unicode_tables/perl_space.rs | 6 +- .../regex-syntax/src/unicode_tables/perl_word.rs | 128 +- .../src/unicode_tables/property_bool.rs | 1128 +- .../src/unicode_tables/property_names.rs | 6 +- .../src/unicode_tables/property_values.rs | 26 +- vendor/regex-syntax/src/unicode_tables/script.rs | 222 +- .../src/unicode_tables/script_extension.rs | 229 +- .../src/unicode_tables/sentence_break.rs | 182 +- .../regex-syntax/src/unicode_tables/word_break.rs | 134 +- vendor/regex-syntax/src/utf8.rs | 6 +- vendor/regex/.cargo-checksum.json | 2 +- vendor/regex/CHANGELOG.md | 21 + vendor/regex/Cargo.lock | 18 +- vendor/regex/Cargo.toml | 4 +- vendor/regex/src/backtrack.rs | 12 +- vendor/regex/src/compile.rs | 57 +- vendor/regex/src/dfa.rs | 38 +- vendor/regex/src/exec.rs | 14 +- vendor/regex/src/expand.rs | 8 +- vendor/regex/src/input.rs | 4 +- vendor/regex/src/lib.rs | 1 - vendor/regex/src/literal/imp.rs | 4 +- vendor/regex/src/pattern.rs | 2 +- vendor/regex/src/pikevm.rs | 2 +- vendor/regex/src/prog.rs | 2 +- vendor/regex/src/re_bytes.rs | 12 +- vendor/regex/src/re_set.rs | 44 +- vendor/regex/src/re_trait.rs | 13 +- vendor/regex/src/re_unicode.rs | 24 +- vendor/regex/src/utf8.rs | 2 +- vendor/regex/tests/unicode.rs | 17 + vendor/rowan/.cargo-checksum.json | 2 +- vendor/rowan/Cargo.lock | 10 +- vendor/rowan/Cargo.toml | 3 +- vendor/rowan/src/cursor.rs | 2 +- vendor/rustc_tools_util/.cargo-checksum.json | 2 +- vendor/rustc_tools_util/Cargo.toml | 25 +- vendor/rustc_tools_util/LICENSE-APACHE | 201 + vendor/rustc_tools_util/LICENSE-MIT | 27 + vendor/rustc_tools_util/README.md | 10 +- vendor/rustc_tools_util/src/lib.rs | 34 +- vendor/ryu/.cargo-checksum.json | 2 +- vendor/ryu/Cargo.lock | 54 +- vendor/ryu/Cargo.toml | 8 +- vendor/ryu/README.md | 2 +- vendor/ryu/src/lib.rs | 4 +- vendor/semver/.cargo-checksum.json | 2 +- vendor/semver/Cargo.toml | 7 +- vendor/semver/build.rs | 2 +- vendor/semver/src/backport.rs | 9 + vendor/semver/src/identifier.rs | 8 +- vendor/semver/src/lib.rs | 2 +- vendor/serde/.cargo-checksum.json | 2 +- vendor/serde/Cargo.toml | 9 +- vendor/serde/src/de/ignored_any.rs | 2 +- vendor/serde/src/de/impls.rs | 8 +- vendor/serde/src/de/mod.rs | 24 +- vendor/serde/src/de/value.rs | 37 +- vendor/serde/src/lib.rs | 24 +- vendor/serde/src/private/de.rs | 11 + vendor/serde/src/private/ser.rs | 6 +- vendor/serde/src/ser/impls.rs | 15 +- vendor/serde/src/ser/mod.rs | 8 +- vendor/serde_derive/.cargo-checksum.json | 2 +- vendor/serde_derive/Cargo.toml | 4 +- vendor/serde_derive/src/lib.rs | 2 +- vendor/serde_json/.cargo-checksum.json | 2 +- vendor/serde_json/Cargo.toml | 11 +- vendor/serde_json/src/lib.rs | 3 +- vendor/serde_json/src/number.rs | 48 +- vendor/serde_json/src/value/mod.rs | 22 +- vendor/serde_json/src/value/ser.rs | 10 +- vendor/serde_json/tests/debug.rs | 43 +- vendor/serde_json/tests/regression/issue795.rs | 2 + vendor/serde_json/tests/stream.rs | 1 + vendor/serde_json/tests/test.rs | 7 +- vendor/serde_json/tests/ui/missing_colon.stderr | 2 +- vendor/serde_json/tests/ui/missing_value.stderr | 2 +- vendor/serde_repr/.cargo-checksum.json | 2 +- vendor/serde_repr/Cargo.toml | 11 +- vendor/serde_repr/README.md | 2 +- vendor/serde_repr/src/lib.rs | 2 +- vendor/serde_repr/tests/test.rs | 1 + vendor/sha-1-0.8.2/.cargo-checksum.json | 1 - vendor/sha-1-0.8.2/Cargo.lock | 148 - vendor/sha-1-0.8.2/Cargo.toml | 58 - vendor/sha-1-0.8.2/LICENSE-APACHE | 201 - vendor/sha-1-0.8.2/LICENSE-MIT | 27 - vendor/sha-1-0.8.2/benches/lib.rs | 7 - vendor/sha-1-0.8.2/examples/sha1sum.rs | 49 - vendor/sha-1-0.8.2/src/aarch64.rs | 9 - vendor/sha-1-0.8.2/src/consts.rs | 19 - vendor/sha-1-0.8.2/src/lib.rs | 141 - vendor/sha-1-0.8.2/src/utils.rs | 300 - vendor/sha-1-0.8.2/tests/data/one_million_a.bin | 1 - vendor/sha-1-0.8.2/tests/data/sha1.blb | 1 - vendor/sha-1-0.8.2/tests/lib.rs | 14 - vendor/smallvec/.cargo-checksum.json | 2 +- vendor/smallvec/Cargo.toml | 31 +- vendor/smallvec/debug_metadata/README.md | 111 + vendor/smallvec/debug_metadata/smallvec.natvis | 35 + vendor/smallvec/scripts/run_miri.sh | 3 + vendor/smallvec/src/lib.rs | 7 + vendor/smallvec/tests/debugger_visualizer.rs | 68 + vendor/syn/.cargo-checksum.json | 2 +- vendor/syn/Cargo.toml | 13 +- vendor/syn/benches/file.rs | 36 +- vendor/syn/benches/rust.rs | 11 +- vendor/syn/src/buffer.rs | 199 +- vendor/syn/src/expr.rs | 21 +- vendor/syn/src/gen/clone.rs | 2 +- vendor/syn/src/gen/debug.rs | 10 +- vendor/syn/src/gen/eq.rs | 6 +- vendor/syn/src/gen/fold.rs | 6 +- vendor/syn/src/gen/hash.rs | 6 +- vendor/syn/src/gen/visit.rs | 6 +- vendor/syn/src/gen/visit_mut.rs | 6 +- vendor/syn/src/item.rs | 14 +- vendor/syn/src/lib.rs | 13 +- vendor/syn/src/lit.rs | 2 +- vendor/syn/src/parse_macro_input.rs | 4 +- vendor/syn/src/pat.rs | 35 +- vendor/syn/src/path.rs | 46 +- vendor/syn/src/stmt.rs | 6 +- vendor/syn/src/ty.rs | 53 +- vendor/syn/tests/.gitignore | 1 - vendor/syn/tests/common/eq.rs | 109 +- vendor/syn/tests/debug/gen.rs | 12 +- vendor/syn/tests/regression/issue1108.rs | 2 +- vendor/syn/tests/repo/mod.rs | 77 +- vendor/syn/tests/test_derive_input.rs | 2 +- vendor/syn/tests/test_parse_stream.rs | 8 +- vendor/syn/tests/test_precedence.rs | 19 +- vendor/syn/tests/test_size.rs | 8 +- vendor/syn/tests/test_stmt.rs | 2 +- vendor/thin-vec/.cargo-checksum.json | 1 + vendor/thin-vec/Cargo.toml | 33 + vendor/thin-vec/README.md | 9 + vendor/thin-vec/src/lib.rs | 3117 ++++ vendor/thiserror-impl/.cargo-checksum.json | 2 +- vendor/thiserror-impl/Cargo.toml | 4 +- vendor/thiserror-impl/src/expand.rs | 108 +- vendor/thiserror-impl/src/generics.rs | 1 + vendor/thiserror-impl/src/lib.rs | 5 +- vendor/thiserror-impl/src/valid.rs | 6 +- vendor/thiserror/.cargo-checksum.json | 2 +- vendor/thiserror/Cargo.toml | 14 +- vendor/thiserror/README.md | 32 +- vendor/thiserror/build.rs | 66 + vendor/thiserror/src/aserror.rs | 9 +- vendor/thiserror/src/lib.rs | 44 +- vendor/thiserror/src/provide.rs | 15 + vendor/thiserror/tests/compiletest.rs | 3 +- vendor/thiserror/tests/test_backtrace.rs | 85 +- vendor/thiserror/tests/test_deprecated.rs | 10 + vendor/thiserror/tests/test_display.rs | 2 - vendor/thiserror/tests/test_error.rs | 1 - vendor/thiserror/tests/test_expr.rs | 3 +- vendor/thiserror/tests/test_from.rs | 2 - vendor/thiserror/tests/test_generics.rs | 2 +- vendor/thiserror/tests/test_option.rs | 6 +- vendor/thiserror/tests/test_path.rs | 2 - vendor/thiserror/tests/test_source.rs | 2 - vendor/thiserror/tests/test_transparent.rs | 2 - vendor/thiserror/tests/ui/concat-display.stderr | 2 +- .../thiserror/tests/ui/from-backtrace-backtrace.rs | 10 + .../tests/ui/from-backtrace-backtrace.stderr | 5 + vendor/thiserror/tests/ui/no-display.stderr | 12 +- .../tests/ui/source-enum-not-error.stderr | 44 +- .../tests/ui/source-struct-not-error.stderr | 42 +- vendor/tracing-attributes/.cargo-checksum.json | 2 +- vendor/tracing-attributes/CHANGELOG.md | 21 + vendor/tracing-attributes/Cargo.toml | 18 +- vendor/tracing-attributes/README.md | 4 +- vendor/tracing-attributes/src/expand.rs | 118 +- vendor/tracing-attributes/src/lib.rs | 60 +- vendor/tracing-attributes/tests/async_fn.rs | 13 + vendor/tracing-attributes/tests/instrument.rs | 9 + vendor/tracing-attributes/tests/ui.rs | 7 + .../tests/ui/async_instrument.rs | 46 + .../tests/ui/async_instrument.stderr | 98 + vendor/tracing-core/.cargo-checksum.json | 2 +- vendor/tracing-core/CHANGELOG.md | 41 + vendor/tracing-core/Cargo.toml | 6 +- vendor/tracing-core/README.md | 26 +- vendor/tracing-core/src/callsite.rs | 10 + vendor/tracing-core/src/dispatcher.rs | 128 +- vendor/tracing-core/src/field.rs | 44 + vendor/tracing-core/src/metadata.rs | 89 +- vendor/tracing-core/src/subscriber.rs | 27 +- .../tracing-subscriber-0.3.3/.cargo-checksum.json | 1 + vendor/tracing-subscriber-0.3.3/CHANGELOG.md | 902 + vendor/tracing-subscriber-0.3.3/Cargo.toml | 150 + vendor/tracing-subscriber-0.3.3/LICENSE | 25 + vendor/tracing-subscriber-0.3.3/README.md | 61 + vendor/tracing-subscriber-0.3.3/benches/enter.rs | 64 + vendor/tracing-subscriber-0.3.3/benches/filter.rs | 308 + .../tracing-subscriber-0.3.3/benches/filter_log.rs | 315 + vendor/tracing-subscriber-0.3.3/benches/fmt.rs | 331 + .../benches/support/mod.rs | 49 + vendor/tracing-subscriber-0.3.3/src/field/debug.rs | 111 + .../src/field/delimited.rs | 184 + .../tracing-subscriber-0.3.3/src/field/display.rs | 117 + vendor/tracing-subscriber-0.3.3/src/field/mod.rs | 366 + .../src/filter/directive.rs | 424 + .../src/filter/env/directive.rs | 846 + .../src/filter/env/field.rs | 416 + .../tracing-subscriber-0.3.3/src/filter/env/mod.rs | 738 + .../src/filter/filter_fn.rs | 749 + .../src/filter/layer_filters.rs | 830 + .../tracing-subscriber-0.3.3/src/filter/level.rs | 27 + vendor/tracing-subscriber-0.3.3/src/filter/mod.rs | 66 + .../tracing-subscriber-0.3.3/src/filter/targets.rs | 681 + .../tracing-subscriber-0.3.3/src/fmt/fmt_layer.rs | 1205 ++ .../src/fmt/format/json.rs | 750 + .../tracing-subscriber-0.3.3/src/fmt/format/mod.rs | 1798 ++ .../src/fmt/format/pretty.rs | 415 + vendor/tracing-subscriber-0.3.3/src/fmt/mod.rs | 1275 ++ .../src/fmt/time/datetime.rs | 410 + .../tracing-subscriber-0.3.3/src/fmt/time/mod.rs | 134 + .../src/fmt/time/time_crate.rs | 276 + vendor/tracing-subscriber-0.3.3/src/fmt/writer.rs | 1464 ++ .../tracing-subscriber-0.3.3/src/layer/context.rs | 434 + .../tracing-subscriber-0.3.3/src/layer/layered.rs | 471 + vendor/tracing-subscriber-0.3.3/src/layer/mod.rs | 1285 ++ vendor/tracing-subscriber-0.3.3/src/layer/tests.rs | 308 + vendor/tracing-subscriber-0.3.3/src/lib.rs | 218 + vendor/tracing-subscriber-0.3.3/src/macros.rs | 28 + vendor/tracing-subscriber-0.3.3/src/prelude.rs | 19 + .../src/registry/extensions.rs | 274 + .../tracing-subscriber-0.3.3/src/registry/mod.rs | 604 + .../src/registry/sharded.rs | 904 + .../tracing-subscriber-0.3.3/src/registry/stack.rs | 77 + vendor/tracing-subscriber-0.3.3/src/reload.rs | 237 + vendor/tracing-subscriber-0.3.3/src/sync.rs | 57 + vendor/tracing-subscriber-0.3.3/src/util.rs | 153 + ...cached_layer_filters_dont_break_other_layers.rs | 123 + .../tests/duplicate_spans.rs | 48 + .../tracing-subscriber-0.3.3/tests/field_filter.rs | 115 + vendor/tracing-subscriber-0.3.3/tests/filter.rs | 187 + .../tracing-subscriber-0.3.3/tests/filter_log.rs | 63 + .../tests/fmt_max_level_hint.rs | 10 + ...hinted_layer_filters_dont_break_other_layers.rs | 131 + .../tests/layer_filter_interests_are_cached.rs | 69 + .../tests/layer_filters/boxed.rs | 42 + .../tests/layer_filters/downcast_raw.rs | 68 + .../tests/layer_filters/filter_scopes.rs | 131 + .../tests/layer_filters/main.rs | 188 + .../tests/layer_filters/targets.rs | 59 + .../tests/layer_filters/trees.rs | 146 + .../multiple_layer_filter_interests_cached.rs | 131 + .../tests/registry_max_level_hint.rs | 11 + .../tests/registry_with_subscriber.rs | 25 + vendor/tracing-subscriber-0.3.3/tests/reload.rs | 81 + .../tests/same_len_filters.rs | 81 + vendor/tracing-subscriber-0.3.3/tests/support.rs | 412 + ...hinted_layer_filters_dont_break_other_layers.rs | 123 + vendor/tracing-subscriber-0.3.3/tests/utils.rs | 39 + vendor/tracing-subscriber/.cargo-checksum.json | 1 - vendor/tracing-subscriber/CHANGELOG.md | 1212 -- vendor/tracing-subscriber/Cargo.toml | 232 - vendor/tracing-subscriber/LICENSE | 25 - vendor/tracing-subscriber/README.md | 61 - vendor/tracing-subscriber/benches/enter.rs | 64 - vendor/tracing-subscriber/benches/filter.rs | 308 - vendor/tracing-subscriber/benches/filter_log.rs | 315 - vendor/tracing-subscriber/benches/fmt.rs | 331 - vendor/tracing-subscriber/benches/support/mod.rs | 49 - vendor/tracing-subscriber/src/field/debug.rs | 111 - vendor/tracing-subscriber/src/field/delimited.rs | 184 - vendor/tracing-subscriber/src/field/display.rs | 117 - vendor/tracing-subscriber/src/field/mod.rs | 366 - vendor/tracing-subscriber/src/filter/directive.rs | 456 - .../tracing-subscriber/src/filter/env/builder.rs | 324 - .../tracing-subscriber/src/filter/env/directive.rs | 860 - vendor/tracing-subscriber/src/filter/env/field.rs | 626 - vendor/tracing-subscriber/src/filter/env/mod.rs | 991 -- vendor/tracing-subscriber/src/filter/filter_fn.rs | 749 - .../src/filter/layer_filters/combinator.rs | 469 - .../src/filter/layer_filters/mod.rs | 1135 -- vendor/tracing-subscriber/src/filter/level.rs | 27 - vendor/tracing-subscriber/src/filter/mod.rs | 66 - vendor/tracing-subscriber/src/filter/targets.rs | 710 - vendor/tracing-subscriber/src/fmt/fmt_layer.rs | 1368 -- vendor/tracing-subscriber/src/fmt/format/json.rs | 885 - vendor/tracing-subscriber/src/fmt/format/mod.rs | 2161 --- vendor/tracing-subscriber/src/fmt/format/pretty.rs | 511 - vendor/tracing-subscriber/src/fmt/mod.rs | 1324 -- vendor/tracing-subscriber/src/fmt/time/datetime.rs | 410 - vendor/tracing-subscriber/src/fmt/time/mod.rs | 138 - .../tracing-subscriber/src/fmt/time/time_crate.rs | 470 - vendor/tracing-subscriber/src/fmt/writer.rs | 1464 -- vendor/tracing-subscriber/src/layer/context.rs | 434 - vendor/tracing-subscriber/src/layer/layered.rs | 520 - vendor/tracing-subscriber/src/layer/mod.rs | 1798 -- vendor/tracing-subscriber/src/layer/tests.rs | 308 - vendor/tracing-subscriber/src/lib.rs | 252 - vendor/tracing-subscriber/src/macros.rs | 28 - vendor/tracing-subscriber/src/prelude.rs | 19 - .../tracing-subscriber/src/registry/extensions.rs | 274 - vendor/tracing-subscriber/src/registry/mod.rs | 600 - vendor/tracing-subscriber/src/registry/sharded.rs | 901 - vendor/tracing-subscriber/src/registry/stack.rs | 77 - vendor/tracing-subscriber/src/reload.rs | 350 - vendor/tracing-subscriber/src/sync.rs | 57 - vendor/tracing-subscriber/src/util.rs | 153 - ...cached_layer_filters_dont_break_other_layers.rs | 123 - vendor/tracing-subscriber/tests/duplicate_spans.rs | 47 - vendor/tracing-subscriber/tests/env_filter/main.rs | 547 - .../tests/env_filter/per_layer.rs | 305 - vendor/tracing-subscriber/tests/event_enabling.rs | 81 - vendor/tracing-subscriber/tests/field_filter.rs | 115 - vendor/tracing-subscriber/tests/filter_log.rs | 63 - .../tracing-subscriber/tests/fmt_max_level_hint.rs | 10 - ...hinted_layer_filters_dont_break_other_layers.rs | 131 - .../tests/layer_filter_interests_are_cached.rs | 69 - .../tests/layer_filters/boxed.rs | 42 - .../tests/layer_filters/combinators.rs | 42 - .../tests/layer_filters/downcast_raw.rs | 68 - .../tests/layer_filters/filter_scopes.rs | 131 - .../tracing-subscriber/tests/layer_filters/main.rs | 189 - .../tests/layer_filters/targets.rs | 59 - .../tests/layer_filters/trees.rs | 146 - .../tracing-subscriber/tests/layer_filters/vec.rs | 120 - .../multiple_layer_filter_interests_cached.rs | 131 - vendor/tracing-subscriber/tests/option.rs | 41 - .../tests/registry_max_level_hint.rs | 11 - .../tests/registry_with_subscriber.rs | 25 - vendor/tracing-subscriber/tests/reload.rs | 141 - .../tracing-subscriber/tests/same_len_filters.rs | 81 - vendor/tracing-subscriber/tests/support.rs | 407 - ...hinted_layer_filters_dont_break_other_layers.rs | 123 - vendor/tracing-subscriber/tests/utils.rs | 39 - vendor/tracing-subscriber/tests/vec.rs | 19 - .../vec_subscriber_filter_interests_cached.rs | 117 - vendor/tracing/.cargo-checksum.json | 2 +- vendor/tracing/CHANGELOG.md | 82 + vendor/tracing/Cargo.toml | 48 +- vendor/tracing/README.md | 10 +- vendor/tracing/benches/baseline.rs | 24 + vendor/tracing/benches/dispatch_get_clone.rs | 15 + vendor/tracing/benches/dispatch_get_ref.rs | 16 + vendor/tracing/benches/empty_span.rs | 43 + vendor/tracing/benches/enter_span.rs | 16 + vendor/tracing/benches/event.rs | 12 + vendor/tracing/benches/global_subscriber.rs | 136 - vendor/tracing/benches/no_subscriber.rs | 101 - vendor/tracing/benches/shared.rs | 160 + vendor/tracing/benches/span_fields.rs | 23 + vendor/tracing/benches/span_no_fields.rs | 13 + vendor/tracing/benches/span_repeated.rs | 20 + vendor/tracing/benches/subscriber.rs | 189 - vendor/tracing/src/dispatcher.rs | 2 +- vendor/tracing/src/lib.rs | 12 +- vendor/tracing/src/macros.rs | 38 +- vendor/tracing/src/span.rs | 18 +- vendor/tracing/src/subscriber.rs | 17 +- vendor/tracing/tests/event.rs | 24 + vendor/unicode-ident/.cargo-checksum.json | 2 +- vendor/unicode-ident/Cargo.toml | 18 +- vendor/unicode-ident/LICENSE-UNICODE | 46 + vendor/unicode-ident/README.md | 30 +- vendor/unicode-ident/src/tables.rs | 111 +- vendor/unicode-ident/tests/fst/xid_continue.fst | Bin 70255 -> 72750 bytes vendor/unicode-ident/tests/fst/xid_start.fst | Bin 62642 -> 64999 bytes vendor/unicode-ident/tests/static_size.rs | 8 +- vendor/unicode-ident/tests/trie/trie.rs | 222 +- vendor/unicode-normalization/.cargo-checksum.json | 2 +- vendor/unicode-normalization/Cargo.toml | 2 +- vendor/unicode-normalization/README.md | 2 +- vendor/unicode-normalization/scripts/unicode.py | 2 +- vendor/unicode-normalization/src/tables.rs | 16705 ++++++++++--------- vendor/unicode-script/.cargo-checksum.json | 2 +- vendor/unicode-script/Cargo.toml | 36 +- vendor/unicode-script/LICENSE-APACHE | 201 + vendor/unicode-script/LICENSE-MIT | 27 + vendor/unicode-script/README.md | 4 +- vendor/unicode-script/scripts/unicode.py | 4 +- vendor/unicode-script/src/lib.rs | 10 +- vendor/unicode-script/src/tables.rs | 2275 +-- vendor/unicode-security/.cargo-checksum.json | 2 +- vendor/unicode-security/Cargo.toml | 39 +- vendor/unicode-security/README.md | 4 +- vendor/unicode-security/scripts/unicode.py | 6 +- vendor/unicode-security/src/restriction_level.rs | 2 +- vendor/unicode-security/src/tables.rs | 2118 +-- vendor/unicode-segmentation/.cargo-checksum.json | 2 +- vendor/unicode-segmentation/Cargo.toml | 29 +- vendor/unicode-segmentation/scripts/unicode.py | 2 +- vendor/unicode-segmentation/src/tables.rs | 2372 +-- vendor/unicode-segmentation/src/testdata.rs | 6 +- vendor/unicode-width/.cargo-checksum.json | 2 +- vendor/unicode-width/Cargo.toml | 30 +- vendor/unicode-width/scripts/unicode.py | 748 +- vendor/unicode-width/src/tables.rs | 775 +- vendor/unicode-width/src/tests.rs | 20 +- vendor/unicode-xid/.cargo-checksum.json | 2 +- vendor/unicode-xid/Cargo.toml | 2 +- vendor/unicode-xid/README.md | 9 + vendor/unicode-xid/src/tables.rs | 45 +- vendor/url/.cargo-checksum.json | 2 +- vendor/url/Cargo.toml | 63 +- vendor/url/LICENSE-MIT | 2 +- vendor/url/README.md | 14 + vendor/url/src/host.rs | 86 +- vendor/url/src/lib.rs | 82 +- vendor/url/src/origin.rs | 3 +- vendor/url/src/parser.rs | 37 +- vendor/url/src/quirks.rs | 59 +- vendor/url/tests/data.rs | 79 +- vendor/url/tests/debugger_visualizer.rs | 102 + vendor/url/tests/unit.rs | 54 +- vendor/url/tests/urltestdata.json | 3661 ++-- .../.cargo-checksum.json | 1 - .../CODE_OF_CONDUCT.md | 49 - .../CONTRIBUTING.md | 8 - .../wasi-0.10.2+wasi-snapshot-preview1/Cargo.toml | 43 - .../LICENSE-APACHE | 201 - .../LICENSE-Apache-2.0_WITH_LLVM-exception | 220 - .../wasi-0.10.2+wasi-snapshot-preview1/LICENSE-MIT | 23 - .../ORG_CODE_OF_CONDUCT.md | 143 - .../wasi-0.10.2+wasi-snapshot-preview1/README.md | 94 - .../wasi-0.10.2+wasi-snapshot-preview1/SECURITY.md | 29 - .../src/error.rs | 52 - .../wasi-0.10.2+wasi-snapshot-preview1/src/lib.rs | 48 - .../src/lib_generated.rs | 1940 --- vendor/xflags-macros/.cargo-checksum.json | 2 +- vendor/xflags-macros/Cargo.toml | 6 +- vendor/xflags-macros/src/ast.rs | 13 + vendor/xflags-macros/src/emit.rs | 350 +- vendor/xflags-macros/src/lib.rs | 26 +- vendor/xflags-macros/src/parse.rs | 166 +- vendor/xflags-macros/src/update.rs | 3 +- vendor/xflags-macros/tests/data/help.rs | 26 + vendor/xflags-macros/tests/data/repeated_pos.rs | 8 + vendor/xflags-macros/tests/data/smoke.rs | 14 + vendor/xflags-macros/tests/data/subcommands.rs | 19 + vendor/xflags-macros/tests/it/help.rs | 84 +- vendor/xflags-macros/tests/it/main.rs | 36 +- vendor/xflags-macros/tests/it/repeated_pos.rs | 64 +- vendor/xflags-macros/tests/it/smoke.rs | 61 +- vendor/xflags-macros/tests/it/src/help.rs | 25 - vendor/xflags-macros/tests/it/src/repeated_pos.rs | 9 - vendor/xflags-macros/tests/it/src/smoke.rs | 15 - vendor/xflags-macros/tests/it/src/subcommands.rs | 20 - vendor/xflags-macros/tests/it/subcommands.rs | 174 +- vendor/xflags/.cargo-checksum.json | 2 +- vendor/xflags/Cargo.lock | 6 +- vendor/xflags/Cargo.toml | 9 +- vendor/xflags/LICENSE-APACHE | 201 - vendor/xflags/LICENSE-MIT | 23 - vendor/xflags/README.md | 49 - vendor/xflags/examples/hello-generated.rs | 13 +- vendor/xflags/examples/hello.rs | 3 +- vendor/xflags/examples/immediate-mode.rs | 16 + vendor/xflags/examples/longer.rs | 7 +- vendor/xflags/examples/non-utf8.rs | 3 +- vendor/xflags/src/lib.rs | 172 +- vendor/xflags/src/rt.rs | 14 +- 1462 files changed, 102221 insertions(+), 114510 deletions(-) delete mode 100644 vendor/annotate-snippets-0.8.0/.cargo-checksum.json delete mode 100644 vendor/annotate-snippets-0.8.0/CHANGELOG.md delete mode 100644 vendor/annotate-snippets-0.8.0/Cargo.lock delete mode 100644 vendor/annotate-snippets-0.8.0/Cargo.toml delete mode 100644 vendor/annotate-snippets-0.8.0/LICENSE-APACHE delete mode 100644 vendor/annotate-snippets-0.8.0/LICENSE-MIT delete mode 100644 vendor/annotate-snippets-0.8.0/README.md delete mode 100644 vendor/annotate-snippets-0.8.0/benches/simple.rs delete mode 100644 vendor/annotate-snippets-0.8.0/examples/expected_type.rs delete mode 100644 vendor/annotate-snippets-0.8.0/examples/footer.rs delete mode 100644 vendor/annotate-snippets-0.8.0/examples/format.rs delete mode 100644 vendor/annotate-snippets-0.8.0/examples/multislice.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/display_list/from_snippet.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/display_list/mod.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/display_list/structs.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/formatter/mod.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/formatter/style.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/lib.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/snippet.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/stylesheets/color.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/stylesheets/mod.rs delete mode 100644 vendor/annotate-snippets-0.8.0/src/stylesheets/no_color.rs delete mode 100644 vendor/annotate-snippets-0.8.0/tests/diff/mod.rs delete mode 100644 vendor/annotate-snippets-0.8.0/tests/dl_from_snippet.rs delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.toml delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.txt delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.toml delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.txt delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.toml delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.txt delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.toml delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.txt delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.toml delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.txt delete mode 100644 vendor/annotate-snippets-0.8.0/tests/fixtures_test.rs delete mode 100644 vendor/annotate-snippets-0.8.0/tests/formatter.rs delete mode 100644 vendor/annotate-snippets-0.8.0/tests/snippet/mod.rs delete mode 100644 vendor/block-buffer-0.7.3/.cargo-checksum.json delete mode 100644 vendor/block-buffer-0.7.3/Cargo.toml delete mode 100644 vendor/block-buffer-0.7.3/LICENSE-APACHE delete mode 100644 vendor/block-buffer-0.7.3/LICENSE-MIT delete mode 100644 vendor/block-buffer-0.7.3/src/lib.rs delete mode 100644 vendor/block-padding/.cargo-checksum.json delete mode 100644 vendor/block-padding/Cargo.toml delete mode 100644 vendor/block-padding/LICENSE-APACHE delete mode 100644 vendor/block-padding/LICENSE-MIT delete mode 100644 vendor/block-padding/src/lib.rs delete mode 100644 vendor/byte-tools/.cargo-checksum.json delete mode 100644 vendor/byte-tools/Cargo.toml delete mode 100644 vendor/byte-tools/LICENSE-APACHE delete mode 100644 vendor/byte-tools/LICENSE-MIT delete mode 100644 vendor/byte-tools/src/lib.rs delete mode 100644 vendor/byteorder/.cargo-checksum.json delete mode 100644 vendor/byteorder/CHANGELOG.md delete mode 100644 vendor/byteorder/COPYING delete mode 100644 vendor/byteorder/Cargo.toml delete mode 100644 vendor/byteorder/LICENSE-MIT delete mode 100644 vendor/byteorder/README.md delete mode 100644 vendor/byteorder/UNLICENSE delete mode 100644 vendor/byteorder/benches/bench.rs delete mode 100644 vendor/byteorder/rustfmt.toml delete mode 100644 vendor/byteorder/src/io.rs delete mode 100644 vendor/byteorder/src/lib.rs create mode 100644 vendor/clap-3.2.20/.cargo-checksum.json create mode 100644 vendor/clap-3.2.20/Cargo.lock create mode 100644 vendor/clap-3.2.20/Cargo.toml create mode 100644 vendor/clap-3.2.20/LICENSE-APACHE create mode 100644 vendor/clap-3.2.20/LICENSE-MIT create mode 100644 vendor/clap-3.2.20/README.md create mode 100644 vendor/clap-3.2.20/examples/cargo-example-derive.md create mode 100644 vendor/clap-3.2.20/examples/cargo-example-derive.rs create mode 100644 vendor/clap-3.2.20/examples/cargo-example.md create mode 100644 vendor/clap-3.2.20/examples/cargo-example.rs create mode 100644 vendor/clap-3.2.20/examples/demo.md create mode 100644 vendor/clap-3.2.20/examples/demo.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/augment_args.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/augment_subcommands.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/custom-bool.md create mode 100644 vendor/clap-3.2.20/examples/derive_ref/custom-bool.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/flatten_hand_args.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/hand_subcommand.rs create mode 100644 vendor/clap-3.2.20/examples/derive_ref/interop_tests.md create mode 100644 vendor/clap-3.2.20/examples/escaped-positional-derive.md create mode 100644 vendor/clap-3.2.20/examples/escaped-positional-derive.rs create mode 100644 vendor/clap-3.2.20/examples/escaped-positional.md create mode 100644 vendor/clap-3.2.20/examples/escaped-positional.rs create mode 100644 vendor/clap-3.2.20/examples/git-derive.md create mode 100644 vendor/clap-3.2.20/examples/git-derive.rs create mode 100644 vendor/clap-3.2.20/examples/git.md create mode 100644 vendor/clap-3.2.20/examples/git.rs create mode 100644 vendor/clap-3.2.20/examples/multicall-busybox.md create mode 100644 vendor/clap-3.2.20/examples/multicall-busybox.rs create mode 100644 vendor/clap-3.2.20/examples/multicall-hostname.md create mode 100644 vendor/clap-3.2.20/examples/multicall-hostname.rs create mode 100644 vendor/clap-3.2.20/examples/pacman.md create mode 100644 vendor/clap-3.2.20/examples/pacman.rs create mode 100644 vendor/clap-3.2.20/examples/repl.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/01_quick.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/01_quick.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_apps.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_apps.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_crate.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/02_crate.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_builder/05_01_assert.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/01_quick.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/01_quick.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_apps.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_apps.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_crate.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/02_crate.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands_alt.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.md create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.rs create mode 100644 vendor/clap-3.2.20/examples/tutorial_derive/05_01_assert.rs create mode 100644 vendor/clap-3.2.20/examples/typed-derive.md create mode 100644 vendor/clap-3.2.20/examples/typed-derive.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/cargo_example.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/cargo_example_derive create mode 100644 vendor/clap-3.2.20/src/_cookbook/cargo_example_derive.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/escaped_positional.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/escaped_positional_derive.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/git.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/git_derive.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/mod.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/multicall_busybox.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/multicall_hostname.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/pacman.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/repl.rs create mode 100644 vendor/clap-3.2.20/src/_cookbook/typed_derive.rs create mode 100644 vendor/clap-3.2.20/src/_derive/_tutorial.rs create mode 100644 vendor/clap-3.2.20/src/_derive/mod.rs create mode 100644 vendor/clap-3.2.20/src/_faq.rs create mode 100644 vendor/clap-3.2.20/src/_features.rs create mode 100644 vendor/clap-3.2.20/src/_tutorial.rs create mode 100644 vendor/clap-3.2.20/src/bin/stdio-fixture.rs create mode 100644 vendor/clap-3.2.20/src/builder/action.rs create mode 100644 vendor/clap-3.2.20/src/builder/app_settings.rs create mode 100644 vendor/clap-3.2.20/src/builder/arg.rs create mode 100644 vendor/clap-3.2.20/src/builder/arg_group.rs create mode 100644 vendor/clap-3.2.20/src/builder/arg_predicate.rs create mode 100644 vendor/clap-3.2.20/src/builder/arg_settings.rs create mode 100644 vendor/clap-3.2.20/src/builder/command.rs create mode 100644 vendor/clap-3.2.20/src/builder/debug_asserts.rs create mode 100644 vendor/clap-3.2.20/src/builder/macros.rs create mode 100644 vendor/clap-3.2.20/src/builder/mod.rs create mode 100644 vendor/clap-3.2.20/src/builder/possible_value.rs create mode 100644 vendor/clap-3.2.20/src/builder/regex.rs create mode 100644 vendor/clap-3.2.20/src/builder/tests.rs create mode 100644 vendor/clap-3.2.20/src/builder/usage_parser.rs create mode 100644 vendor/clap-3.2.20/src/builder/value_hint.rs create mode 100644 vendor/clap-3.2.20/src/builder/value_parser.rs create mode 100644 vendor/clap-3.2.20/src/derive.rs create mode 100644 vendor/clap-3.2.20/src/error/context.rs create mode 100644 vendor/clap-3.2.20/src/error/kind.rs create mode 100644 vendor/clap-3.2.20/src/error/mod.rs create mode 100644 vendor/clap-3.2.20/src/lib.rs create mode 100644 vendor/clap-3.2.20/src/macros.rs create mode 100644 vendor/clap-3.2.20/src/mkeymap.rs create mode 100644 vendor/clap-3.2.20/src/output/fmt.rs create mode 100644 vendor/clap-3.2.20/src/output/help.rs create mode 100644 vendor/clap-3.2.20/src/output/mod.rs create mode 100644 vendor/clap-3.2.20/src/output/usage.rs create mode 100644 vendor/clap-3.2.20/src/parser/arg_matcher.rs create mode 100644 vendor/clap-3.2.20/src/parser/error.rs create mode 100644 vendor/clap-3.2.20/src/parser/features/mod.rs create mode 100644 vendor/clap-3.2.20/src/parser/features/suggestions.rs create mode 100644 vendor/clap-3.2.20/src/parser/matches/any_value.rs create mode 100644 vendor/clap-3.2.20/src/parser/matches/arg_matches.rs create mode 100644 vendor/clap-3.2.20/src/parser/matches/matched_arg.rs create mode 100644 vendor/clap-3.2.20/src/parser/matches/mod.rs create mode 100644 vendor/clap-3.2.20/src/parser/matches/value_source.rs create mode 100644 vendor/clap-3.2.20/src/parser/mod.rs create mode 100644 vendor/clap-3.2.20/src/parser/parser.rs create mode 100644 vendor/clap-3.2.20/src/parser/validator.rs create mode 100644 vendor/clap-3.2.20/src/util/color.rs create mode 100644 vendor/clap-3.2.20/src/util/fnv.rs create mode 100644 vendor/clap-3.2.20/src/util/graph.rs create mode 100644 vendor/clap-3.2.20/src/util/id.rs create mode 100644 vendor/clap-3.2.20/src/util/mod.rs create mode 100644 vendor/clap-3.2.20/src/util/str_to_bool.rs delete mode 100644 vendor/clap/.cargo-checksum.json delete mode 100644 vendor/clap/Cargo.lock delete mode 100644 vendor/clap/Cargo.toml delete mode 100644 vendor/clap/LICENSE-APACHE delete mode 100644 vendor/clap/LICENSE-MIT delete mode 100644 vendor/clap/README.md delete mode 100644 vendor/clap/examples/README.md delete mode 100644 vendor/clap/examples/cargo-example-derive.md delete mode 100644 vendor/clap/examples/cargo-example-derive.rs delete mode 100644 vendor/clap/examples/cargo-example.md delete mode 100644 vendor/clap/examples/cargo-example.rs delete mode 100644 vendor/clap/examples/demo.md delete mode 100644 vendor/clap/examples/demo.rs delete mode 100644 vendor/clap/examples/derive_ref/README.md delete mode 100644 vendor/clap/examples/derive_ref/augment_args.rs delete mode 100644 vendor/clap/examples/derive_ref/augment_subcommands.rs delete mode 100644 vendor/clap/examples/derive_ref/custom-bool.md delete mode 100644 vendor/clap/examples/derive_ref/custom-bool.rs delete mode 100644 vendor/clap/examples/derive_ref/flatten_hand_args.rs delete mode 100644 vendor/clap/examples/derive_ref/hand_subcommand.rs delete mode 100644 vendor/clap/examples/derive_ref/interop_tests.md delete mode 100644 vendor/clap/examples/escaped-positional-derive.md delete mode 100644 vendor/clap/examples/escaped-positional-derive.rs delete mode 100644 vendor/clap/examples/escaped-positional.md delete mode 100644 vendor/clap/examples/escaped-positional.rs delete mode 100644 vendor/clap/examples/git-derive.md delete mode 100644 vendor/clap/examples/git-derive.rs delete mode 100644 vendor/clap/examples/git.md delete mode 100644 vendor/clap/examples/git.rs delete mode 100644 vendor/clap/examples/multicall-busybox.md delete mode 100644 vendor/clap/examples/multicall-busybox.rs delete mode 100644 vendor/clap/examples/multicall-hostname.md delete mode 100644 vendor/clap/examples/multicall-hostname.rs delete mode 100644 vendor/clap/examples/pacman.md delete mode 100644 vendor/clap/examples/pacman.rs delete mode 100644 vendor/clap/examples/repl.rs delete mode 100644 vendor/clap/examples/tutorial_builder/01_quick.rs delete mode 100644 vendor/clap/examples/tutorial_builder/02_app_settings.rs delete mode 100644 vendor/clap/examples/tutorial_builder/02_apps.rs delete mode 100644 vendor/clap/examples/tutorial_builder/02_crate.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_count.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_02_option.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_03_positional.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_04_subcommands.rs delete mode 100644 vendor/clap/examples/tutorial_builder/03_05_default_values.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_01_enum.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_01_possible.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_02_parse.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_02_validate.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_03_relations.rs delete mode 100644 vendor/clap/examples/tutorial_builder/04_04_custom.rs delete mode 100644 vendor/clap/examples/tutorial_builder/05_01_assert.rs delete mode 100644 vendor/clap/examples/tutorial_builder/README.md delete mode 100644 vendor/clap/examples/tutorial_derive/01_quick.rs delete mode 100644 vendor/clap/examples/tutorial_derive/02_app_settings.rs delete mode 100644 vendor/clap/examples/tutorial_derive/02_apps.rs delete mode 100644 vendor/clap/examples/tutorial_derive/02_crate.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_count.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_02_option.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_03_positional.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_04_subcommands.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs delete mode 100644 vendor/clap/examples/tutorial_derive/03_05_default_values.rs delete mode 100644 vendor/clap/examples/tutorial_derive/04_01_enum.rs delete mode 100644 vendor/clap/examples/tutorial_derive/04_02_parse.rs delete mode 100644 vendor/clap/examples/tutorial_derive/04_02_validate.rs delete mode 100644 vendor/clap/examples/tutorial_derive/04_03_relations.rs delete mode 100644 vendor/clap/examples/tutorial_derive/04_04_custom.rs delete mode 100644 vendor/clap/examples/tutorial_derive/05_01_assert.rs delete mode 100644 vendor/clap/examples/tutorial_derive/README.md delete mode 100644 vendor/clap/examples/typed-derive.md delete mode 100644 vendor/clap/examples/typed-derive.rs delete mode 100644 vendor/clap/src/bin/stdio-fixture.rs delete mode 100644 vendor/clap/src/builder/action.rs delete mode 100644 vendor/clap/src/builder/app_settings.rs delete mode 100644 vendor/clap/src/builder/arg.rs delete mode 100644 vendor/clap/src/builder/arg_group.rs delete mode 100644 vendor/clap/src/builder/arg_predicate.rs delete mode 100644 vendor/clap/src/builder/arg_settings.rs delete mode 100644 vendor/clap/src/builder/command.rs delete mode 100644 vendor/clap/src/builder/debug_asserts.rs delete mode 100644 vendor/clap/src/builder/macros.rs delete mode 100644 vendor/clap/src/builder/mod.rs delete mode 100644 vendor/clap/src/builder/possible_value.rs delete mode 100644 vendor/clap/src/builder/regex.rs delete mode 100644 vendor/clap/src/builder/tests.rs delete mode 100644 vendor/clap/src/builder/usage_parser.rs delete mode 100644 vendor/clap/src/builder/value_hint.rs delete mode 100644 vendor/clap/src/builder/value_parser.rs delete mode 100644 vendor/clap/src/derive.rs delete mode 100644 vendor/clap/src/error/context.rs delete mode 100644 vendor/clap/src/error/kind.rs delete mode 100644 vendor/clap/src/error/mod.rs delete mode 100644 vendor/clap/src/lib.rs delete mode 100644 vendor/clap/src/macros.rs delete mode 100644 vendor/clap/src/mkeymap.rs delete mode 100644 vendor/clap/src/output/fmt.rs delete mode 100644 vendor/clap/src/output/help.rs delete mode 100644 vendor/clap/src/output/mod.rs delete mode 100644 vendor/clap/src/output/usage.rs delete mode 100644 vendor/clap/src/parser/arg_matcher.rs delete mode 100644 vendor/clap/src/parser/error.rs delete mode 100644 vendor/clap/src/parser/features/mod.rs delete mode 100644 vendor/clap/src/parser/features/suggestions.rs delete mode 100644 vendor/clap/src/parser/matches/any_value.rs delete mode 100644 vendor/clap/src/parser/matches/arg_matches.rs delete mode 100644 vendor/clap/src/parser/matches/matched_arg.rs delete mode 100644 vendor/clap/src/parser/matches/mod.rs delete mode 100644 vendor/clap/src/parser/matches/value_source.rs delete mode 100644 vendor/clap/src/parser/mod.rs delete mode 100644 vendor/clap/src/parser/parser.rs delete mode 100644 vendor/clap/src/parser/validator.rs delete mode 100644 vendor/clap/src/util/color.rs delete mode 100644 vendor/clap/src/util/fnv.rs delete mode 100644 vendor/clap/src/util/graph.rs delete mode 100644 vendor/clap/src/util/id.rs delete mode 100644 vendor/clap/src/util/mod.rs delete mode 100644 vendor/clap/src/util/str_to_bool.rs create mode 100644 vendor/clap_lex-0.2.2/.cargo-checksum.json create mode 100644 vendor/clap_lex-0.2.2/Cargo.toml create mode 100644 vendor/clap_lex-0.2.2/LICENSE-APACHE create mode 100644 vendor/clap_lex-0.2.2/LICENSE-MIT create mode 100644 vendor/clap_lex-0.2.2/README.md create mode 100644 vendor/clap_lex-0.2.2/src/lib.rs delete mode 100644 vendor/clap_lex/.cargo-checksum.json delete mode 100644 vendor/clap_lex/Cargo.toml delete mode 100644 vendor/clap_lex/LICENSE-APACHE delete mode 100644 vendor/clap_lex/LICENSE-MIT delete mode 100644 vendor/clap_lex/README.md delete mode 100644 vendor/clap_lex/src/lib.rs create mode 100644 vendor/compiler_builtins/LICENSE.txt create mode 100644 vendor/crossbeam-epoch/src/sync/once_lock.rs delete mode 100644 vendor/crossbeam-queue/.cargo-checksum.json delete mode 100644 vendor/crossbeam-queue/CHANGELOG.md delete mode 100644 vendor/crossbeam-queue/Cargo.toml delete mode 100644 vendor/crossbeam-queue/LICENSE-APACHE delete mode 100644 vendor/crossbeam-queue/LICENSE-MIT delete mode 100644 vendor/crossbeam-queue/README.md delete mode 100644 vendor/crossbeam-queue/build.rs delete mode 100644 vendor/crossbeam-queue/no_atomic.rs delete mode 100644 vendor/crossbeam-queue/src/array_queue.rs delete mode 100644 vendor/crossbeam-queue/src/lib.rs delete mode 100644 vendor/crossbeam-queue/src/seg_queue.rs delete mode 100644 vendor/crossbeam-queue/tests/array_queue.rs delete mode 100644 vendor/crossbeam-queue/tests/seg_queue.rs create mode 100644 vendor/crossbeam-utils/src/sync/once_lock.rs delete mode 100644 vendor/crossbeam/.cargo-checksum.json delete mode 100644 vendor/crossbeam/CHANGELOG.md delete mode 100644 vendor/crossbeam/Cargo.toml delete mode 100644 vendor/crossbeam/LICENSE-APACHE delete mode 100644 vendor/crossbeam/LICENSE-MIT delete mode 100644 vendor/crossbeam/README.md delete mode 100644 vendor/crossbeam/no_atomic.rs delete mode 100644 vendor/crossbeam/src/lib.rs delete mode 100644 vendor/crossbeam/tests/subcrates.rs create mode 100644 vendor/dashmap/src/rayon/read_only.rs delete mode 100644 vendor/dashmap/src/table.rs delete mode 100644 vendor/digest-0.8.1/.cargo-checksum.json delete mode 100644 vendor/digest-0.8.1/Cargo.toml delete mode 100644 vendor/digest-0.8.1/LICENSE-APACHE delete mode 100644 vendor/digest-0.8.1/LICENSE-MIT delete mode 100644 vendor/digest-0.8.1/src/dev.rs delete mode 100644 vendor/digest-0.8.1/src/digest.rs delete mode 100644 vendor/digest-0.8.1/src/dyn_digest.rs delete mode 100644 vendor/digest-0.8.1/src/errors.rs delete mode 100644 vendor/digest-0.8.1/src/lib.rs delete mode 100644 vendor/fake-simd/.cargo-checksum.json delete mode 100644 vendor/fake-simd/Cargo.toml delete mode 100644 vendor/fake-simd/LICENSE-APACHE delete mode 100644 vendor/fake-simd/LICENSE-MIT delete mode 100644 vendor/fake-simd/src/lib.rs delete mode 100644 vendor/fs-err/README.tpl delete mode 100644 vendor/fs-err/tests/version-numbers.rs delete mode 100644 vendor/generic-array-0.12.4/.cargo-checksum.json delete mode 100644 vendor/generic-array-0.12.4/CHANGELOG.md delete mode 100644 vendor/generic-array-0.12.4/Cargo.toml delete mode 100644 vendor/generic-array-0.12.4/LICENSE delete mode 100644 vendor/generic-array-0.12.4/README.md delete mode 100644 vendor/generic-array-0.12.4/rustfmt.toml delete mode 100644 vendor/generic-array-0.12.4/src/arr.rs delete mode 100644 vendor/generic-array-0.12.4/src/functional.rs delete mode 100644 vendor/generic-array-0.12.4/src/hex.rs delete mode 100644 vendor/generic-array-0.12.4/src/impl_serde.rs delete mode 100644 vendor/generic-array-0.12.4/src/impls.rs delete mode 100644 vendor/generic-array-0.12.4/src/iter.rs delete mode 100644 vendor/generic-array-0.12.4/src/lib.rs delete mode 100644 vendor/generic-array-0.12.4/src/sequence.rs delete mode 100644 vendor/generic-array-0.12.4/tests/arr.rs delete mode 100644 vendor/generic-array-0.12.4/tests/generics.rs delete mode 100644 vendor/generic-array-0.12.4/tests/hex.rs delete mode 100644 vendor/generic-array-0.12.4/tests/import_name.rs delete mode 100644 vendor/generic-array-0.12.4/tests/iter.rs delete mode 100644 vendor/generic-array-0.12.4/tests/mod.rs create mode 100644 vendor/handlebars/examples/helper_macro.rs create mode 100644 vendor/handlebars/tests/embed.rs create mode 100644 vendor/handlebars/tests/templates/hello.hbs create mode 100644 vendor/handlebars/tests/whitespace.rs create mode 100644 vendor/hermit-abi/src/errno.rs create mode 100644 vendor/home/src/env.rs delete mode 100644 vendor/itertools/Cargo.lock create mode 100644 vendor/itertools/clippy.toml create mode 100644 vendor/itertools/src/extrema_set.rs create mode 100644 vendor/lazycell/.cargo-checksum.json create mode 100644 vendor/lazycell/CHANGELOG.md create mode 100644 vendor/lazycell/Cargo.toml create mode 100644 vendor/lazycell/LICENSE-APACHE create mode 100644 vendor/lazycell/LICENSE-MIT create mode 100644 vendor/lazycell/README.md create mode 100644 vendor/lazycell/src/lib.rs create mode 100644 vendor/lazycell/src/serde_impl.rs create mode 100644 vendor/libc/src/unix/linux_like/android/b64/riscv64/align.rs create mode 100644 vendor/libc/src/unix/linux_like/android/b64/riscv64/mod.rs delete mode 100644 vendor/matches/.cargo-checksum.json delete mode 100644 vendor/matches/Cargo.toml delete mode 100644 vendor/matches/LICENSE delete mode 100644 vendor/matches/lib.rs delete mode 100644 vendor/matches/tests/macro_use_one.rs delete mode 100644 vendor/matches/tests/use_star.rs delete mode 100644 vendor/opaque-debug/.cargo-checksum.json delete mode 100644 vendor/opaque-debug/Cargo.toml delete mode 100644 vendor/opaque-debug/LICENSE-APACHE delete mode 100644 vendor/opaque-debug/LICENSE-MIT delete mode 100644 vendor/opaque-debug/src/lib.rs delete mode 100644 vendor/percent-encoding/lib.rs create mode 100644 vendor/percent-encoding/src/lib.rs create mode 100644 vendor/pest_meta/src/optimizer/lister.rs delete mode 100644 vendor/pretty_assertions-0.7.2/.cargo-checksum.json delete mode 100644 vendor/pretty_assertions-0.7.2/CHANGELOG.md delete mode 100644 vendor/pretty_assertions-0.7.2/Cargo.lock delete mode 100644 vendor/pretty_assertions-0.7.2/Cargo.toml delete mode 100644 vendor/pretty_assertions-0.7.2/LICENSE-APACHE delete mode 100644 vendor/pretty_assertions-0.7.2/LICENSE-MIT delete mode 100644 vendor/pretty_assertions-0.7.2/README.md delete mode 100644 vendor/pretty_assertions-0.7.2/examples/pretty_assertion.png delete mode 100644 vendor/pretty_assertions-0.7.2/examples/pretty_assertion.rs delete mode 100644 vendor/pretty_assertions-0.7.2/examples/pretty_assertion_v0_6_1.png delete mode 100644 vendor/pretty_assertions-0.7.2/examples/standard_assertion.png delete mode 100644 vendor/pretty_assertions-0.7.2/examples/standard_assertion.rs delete mode 100755 vendor/pretty_assertions-0.7.2/scripts/check delete mode 100755 vendor/pretty_assertions-0.7.2/scripts/install delete mode 100755 vendor/pretty_assertions-0.7.2/scripts/publish delete mode 100644 vendor/pretty_assertions-0.7.2/src/lib.rs delete mode 100644 vendor/pretty_assertions-0.7.2/src/printer.rs create mode 100644 vendor/pretty_assertions/.cargo-checksum.json create mode 100644 vendor/pretty_assertions/CHANGELOG.md create mode 100644 vendor/pretty_assertions/Cargo.lock create mode 100644 vendor/pretty_assertions/Cargo.toml create mode 100644 vendor/pretty_assertions/LICENSE-APACHE create mode 100644 vendor/pretty_assertions/LICENSE-MIT create mode 100644 vendor/pretty_assertions/README.md create mode 100644 vendor/pretty_assertions/examples/pretty_assertion.png create mode 100644 vendor/pretty_assertions/examples/pretty_assertion.rs create mode 100644 vendor/pretty_assertions/examples/pretty_assertion_v0_6_1.png create mode 100644 vendor/pretty_assertions/examples/standard_assertion.png create mode 100644 vendor/pretty_assertions/examples/standard_assertion.rs create mode 100755 vendor/pretty_assertions/scripts/check create mode 100755 vendor/pretty_assertions/scripts/install create mode 100755 vendor/pretty_assertions/scripts/publish create mode 100644 vendor/pretty_assertions/src/lib.rs create mode 100644 vendor/pretty_assertions/src/printer.rs create mode 100644 vendor/proc-macro2/src/rcvec.rs delete mode 100644 vendor/quick-error-1.2.3/.cargo-checksum.json delete mode 100644 vendor/quick-error-1.2.3/Cargo.lock delete mode 100644 vendor/quick-error-1.2.3/Cargo.toml delete mode 100644 vendor/quick-error-1.2.3/LICENSE-APACHE delete mode 100644 vendor/quick-error-1.2.3/LICENSE-MIT delete mode 100644 vendor/quick-error-1.2.3/README.rst delete mode 100644 vendor/quick-error-1.2.3/bulk.yaml delete mode 100644 vendor/quick-error-1.2.3/examples/context.rs delete mode 100644 vendor/quick-error-1.2.3/src/lib.rs delete mode 100644 vendor/quick-error-1.2.3/vagga.yaml create mode 100644 vendor/redox_syscall/src/arch/x86.rs create mode 100644 vendor/rustc_tools_util/LICENSE-APACHE create mode 100644 vendor/rustc_tools_util/LICENSE-MIT delete mode 100644 vendor/sha-1-0.8.2/.cargo-checksum.json delete mode 100644 vendor/sha-1-0.8.2/Cargo.lock delete mode 100644 vendor/sha-1-0.8.2/Cargo.toml delete mode 100644 vendor/sha-1-0.8.2/LICENSE-APACHE delete mode 100644 vendor/sha-1-0.8.2/LICENSE-MIT delete mode 100644 vendor/sha-1-0.8.2/benches/lib.rs delete mode 100644 vendor/sha-1-0.8.2/examples/sha1sum.rs delete mode 100644 vendor/sha-1-0.8.2/src/aarch64.rs delete mode 100644 vendor/sha-1-0.8.2/src/consts.rs delete mode 100644 vendor/sha-1-0.8.2/src/lib.rs delete mode 100644 vendor/sha-1-0.8.2/src/utils.rs delete mode 100644 vendor/sha-1-0.8.2/tests/data/one_million_a.bin delete mode 100644 vendor/sha-1-0.8.2/tests/data/sha1.blb delete mode 100644 vendor/sha-1-0.8.2/tests/lib.rs create mode 100644 vendor/smallvec/debug_metadata/README.md create mode 100644 vendor/smallvec/debug_metadata/smallvec.natvis create mode 100644 vendor/smallvec/tests/debugger_visualizer.rs delete mode 100644 vendor/syn/tests/.gitignore create mode 100644 vendor/thin-vec/.cargo-checksum.json create mode 100644 vendor/thin-vec/Cargo.toml create mode 100644 vendor/thin-vec/README.md create mode 100644 vendor/thin-vec/src/lib.rs create mode 100644 vendor/thiserror/build.rs create mode 100644 vendor/thiserror/src/provide.rs create mode 100644 vendor/thiserror/tests/test_deprecated.rs create mode 100644 vendor/thiserror/tests/ui/from-backtrace-backtrace.rs create mode 100644 vendor/thiserror/tests/ui/from-backtrace-backtrace.stderr create mode 100644 vendor/tracing-attributes/tests/ui.rs create mode 100644 vendor/tracing-attributes/tests/ui/async_instrument.rs create mode 100644 vendor/tracing-attributes/tests/ui/async_instrument.stderr create mode 100644 vendor/tracing-subscriber-0.3.3/.cargo-checksum.json create mode 100644 vendor/tracing-subscriber-0.3.3/CHANGELOG.md create mode 100644 vendor/tracing-subscriber-0.3.3/Cargo.toml create mode 100644 vendor/tracing-subscriber-0.3.3/LICENSE create mode 100644 vendor/tracing-subscriber-0.3.3/README.md create mode 100644 vendor/tracing-subscriber-0.3.3/benches/enter.rs create mode 100644 vendor/tracing-subscriber-0.3.3/benches/filter.rs create mode 100644 vendor/tracing-subscriber-0.3.3/benches/filter_log.rs create mode 100644 vendor/tracing-subscriber-0.3.3/benches/fmt.rs create mode 100644 vendor/tracing-subscriber-0.3.3/benches/support/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/field/debug.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/field/delimited.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/field/display.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/field/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/directive.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/env/directive.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/env/field.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/env/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/filter_fn.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/layer_filters.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/level.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/filter/targets.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/fmt_layer.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/format/json.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/format/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/format/pretty.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/time/datetime.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/time/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/time/time_crate.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/fmt/writer.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/layer/context.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/layer/layered.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/layer/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/layer/tests.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/lib.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/macros.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/prelude.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/registry/extensions.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/registry/mod.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/registry/sharded.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/registry/stack.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/reload.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/sync.rs create mode 100644 vendor/tracing-subscriber-0.3.3/src/util.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/cached_layer_filters_dont_break_other_layers.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/duplicate_spans.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/field_filter.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/filter.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/filter_log.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/fmt_max_level_hint.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/hinted_layer_filters_dont_break_other_layers.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filter_interests_are_cached.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/boxed.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/downcast_raw.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/filter_scopes.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/main.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/targets.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/layer_filters/trees.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/multiple_layer_filter_interests_cached.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/registry_max_level_hint.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/registry_with_subscriber.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/reload.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/same_len_filters.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/support.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/unhinted_layer_filters_dont_break_other_layers.rs create mode 100644 vendor/tracing-subscriber-0.3.3/tests/utils.rs delete mode 100644 vendor/tracing-subscriber/.cargo-checksum.json delete mode 100644 vendor/tracing-subscriber/CHANGELOG.md delete mode 100644 vendor/tracing-subscriber/Cargo.toml delete mode 100644 vendor/tracing-subscriber/LICENSE delete mode 100644 vendor/tracing-subscriber/README.md delete mode 100644 vendor/tracing-subscriber/benches/enter.rs delete mode 100644 vendor/tracing-subscriber/benches/filter.rs delete mode 100644 vendor/tracing-subscriber/benches/filter_log.rs delete mode 100644 vendor/tracing-subscriber/benches/fmt.rs delete mode 100644 vendor/tracing-subscriber/benches/support/mod.rs delete mode 100644 vendor/tracing-subscriber/src/field/debug.rs delete mode 100644 vendor/tracing-subscriber/src/field/delimited.rs delete mode 100644 vendor/tracing-subscriber/src/field/display.rs delete mode 100644 vendor/tracing-subscriber/src/field/mod.rs delete mode 100644 vendor/tracing-subscriber/src/filter/directive.rs delete mode 100644 vendor/tracing-subscriber/src/filter/env/builder.rs delete mode 100644 vendor/tracing-subscriber/src/filter/env/directive.rs delete mode 100644 vendor/tracing-subscriber/src/filter/env/field.rs delete mode 100644 vendor/tracing-subscriber/src/filter/env/mod.rs delete mode 100644 vendor/tracing-subscriber/src/filter/filter_fn.rs delete mode 100644 vendor/tracing-subscriber/src/filter/layer_filters/combinator.rs delete mode 100644 vendor/tracing-subscriber/src/filter/layer_filters/mod.rs delete mode 100644 vendor/tracing-subscriber/src/filter/level.rs delete mode 100644 vendor/tracing-subscriber/src/filter/mod.rs delete mode 100644 vendor/tracing-subscriber/src/filter/targets.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/fmt_layer.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/format/json.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/format/mod.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/format/pretty.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/mod.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/time/datetime.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/time/mod.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/time/time_crate.rs delete mode 100644 vendor/tracing-subscriber/src/fmt/writer.rs delete mode 100644 vendor/tracing-subscriber/src/layer/context.rs delete mode 100644 vendor/tracing-subscriber/src/layer/layered.rs delete mode 100644 vendor/tracing-subscriber/src/layer/mod.rs delete mode 100644 vendor/tracing-subscriber/src/layer/tests.rs delete mode 100644 vendor/tracing-subscriber/src/lib.rs delete mode 100644 vendor/tracing-subscriber/src/macros.rs delete mode 100644 vendor/tracing-subscriber/src/prelude.rs delete mode 100644 vendor/tracing-subscriber/src/registry/extensions.rs delete mode 100644 vendor/tracing-subscriber/src/registry/mod.rs delete mode 100644 vendor/tracing-subscriber/src/registry/sharded.rs delete mode 100644 vendor/tracing-subscriber/src/registry/stack.rs delete mode 100644 vendor/tracing-subscriber/src/reload.rs delete mode 100644 vendor/tracing-subscriber/src/sync.rs delete mode 100644 vendor/tracing-subscriber/src/util.rs delete mode 100644 vendor/tracing-subscriber/tests/cached_layer_filters_dont_break_other_layers.rs delete mode 100644 vendor/tracing-subscriber/tests/duplicate_spans.rs delete mode 100644 vendor/tracing-subscriber/tests/env_filter/main.rs delete mode 100644 vendor/tracing-subscriber/tests/env_filter/per_layer.rs delete mode 100644 vendor/tracing-subscriber/tests/event_enabling.rs delete mode 100644 vendor/tracing-subscriber/tests/field_filter.rs delete mode 100644 vendor/tracing-subscriber/tests/filter_log.rs delete mode 100644 vendor/tracing-subscriber/tests/fmt_max_level_hint.rs delete mode 100644 vendor/tracing-subscriber/tests/hinted_layer_filters_dont_break_other_layers.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filter_interests_are_cached.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/boxed.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/combinators.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/downcast_raw.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/filter_scopes.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/main.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/targets.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/trees.rs delete mode 100644 vendor/tracing-subscriber/tests/layer_filters/vec.rs delete mode 100644 vendor/tracing-subscriber/tests/multiple_layer_filter_interests_cached.rs delete mode 100644 vendor/tracing-subscriber/tests/option.rs delete mode 100644 vendor/tracing-subscriber/tests/registry_max_level_hint.rs delete mode 100644 vendor/tracing-subscriber/tests/registry_with_subscriber.rs delete mode 100644 vendor/tracing-subscriber/tests/reload.rs delete mode 100644 vendor/tracing-subscriber/tests/same_len_filters.rs delete mode 100644 vendor/tracing-subscriber/tests/support.rs delete mode 100644 vendor/tracing-subscriber/tests/unhinted_layer_filters_dont_break_other_layers.rs delete mode 100644 vendor/tracing-subscriber/tests/utils.rs delete mode 100644 vendor/tracing-subscriber/tests/vec.rs delete mode 100644 vendor/tracing-subscriber/tests/vec_subscriber_filter_interests_cached.rs create mode 100644 vendor/tracing/benches/baseline.rs create mode 100644 vendor/tracing/benches/dispatch_get_clone.rs create mode 100644 vendor/tracing/benches/dispatch_get_ref.rs create mode 100644 vendor/tracing/benches/empty_span.rs create mode 100644 vendor/tracing/benches/enter_span.rs create mode 100644 vendor/tracing/benches/event.rs delete mode 100644 vendor/tracing/benches/global_subscriber.rs delete mode 100644 vendor/tracing/benches/no_subscriber.rs create mode 100644 vendor/tracing/benches/shared.rs create mode 100644 vendor/tracing/benches/span_fields.rs create mode 100644 vendor/tracing/benches/span_no_fields.rs create mode 100644 vendor/tracing/benches/span_repeated.rs delete mode 100644 vendor/tracing/benches/subscriber.rs create mode 100644 vendor/unicode-ident/LICENSE-UNICODE create mode 100644 vendor/unicode-script/LICENSE-APACHE create mode 100644 vendor/unicode-script/LICENSE-MIT create mode 100644 vendor/url/README.md create mode 100644 vendor/url/tests/debugger_visualizer.rs delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/.cargo-checksum.json delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/CODE_OF_CONDUCT.md delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/CONTRIBUTING.md delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/Cargo.toml delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/LICENSE-APACHE delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/LICENSE-Apache-2.0_WITH_LLVM-exception delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/LICENSE-MIT delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/ORG_CODE_OF_CONDUCT.md delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/README.md delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/SECURITY.md delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/src/error.rs delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/src/lib.rs delete mode 100644 vendor/wasi-0.10.2+wasi-snapshot-preview1/src/lib_generated.rs create mode 100644 vendor/xflags-macros/tests/data/help.rs create mode 100644 vendor/xflags-macros/tests/data/repeated_pos.rs create mode 100644 vendor/xflags-macros/tests/data/smoke.rs create mode 100644 vendor/xflags-macros/tests/data/subcommands.rs delete mode 100644 vendor/xflags-macros/tests/it/src/help.rs delete mode 100644 vendor/xflags-macros/tests/it/src/repeated_pos.rs delete mode 100644 vendor/xflags-macros/tests/it/src/smoke.rs delete mode 100644 vendor/xflags-macros/tests/it/src/subcommands.rs delete mode 100644 vendor/xflags/LICENSE-APACHE delete mode 100644 vendor/xflags/LICENSE-MIT delete mode 100644 vendor/xflags/README.md create mode 100644 vendor/xflags/examples/immediate-mode.rs (limited to 'vendor') diff --git a/vendor/annotate-snippets-0.8.0/.cargo-checksum.json b/vendor/annotate-snippets-0.8.0/.cargo-checksum.json deleted file mode 100644 index 413c71606..000000000 --- a/vendor/annotate-snippets-0.8.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"ca530d80d98754cf591aec37f089ade5a9334d358caea6262b556ae81ec0695e","Cargo.lock":"cec2d73c92b5db30dc134dd48d5233b7d589a5583a6a7a58f967776b5927de20","Cargo.toml":"acdebc9bab91be584c752d4a3e3b56c554d849f6ac8bc29f9b2270f8c6599404","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"49c0b000c03731d9e3970dc059ad4ca345d773681f4a612b0024435b663e0220","README.md":"3b0998e062248617e214b03ae83ff0da63ef6ecf08a9e84bd0deb0676958ed8a","benches/simple.rs":"f85dd74583e3addba780b2c136f250197155e173f09472ae106ebca96006ae76","examples/expected_type.rs":"ce9aad006f7aca50c460684dbc7b95007044d730583f8a079e33123c7d98b618","examples/footer.rs":"77bcb981711091d93b4fbfbbe318f262d90996485aa012ba3ff95ebd4dc3085f","examples/format.rs":"72f47847ce0b0a1025b56642a5b3fe191aaac775c16f42d76417362234298393","examples/multislice.rs":"bf10fc20f1948e6b0f325ed486ddf1b44e9a99fd22226012b81c5608846de983","src/display_list/from_snippet.rs":"49797d0f296a6af96bee70ccca8919050033fdaf7cbd1efe18ab2bead3430c6a","src/display_list/mod.rs":"a6aebdc9d666801280623b72798cfaae9172cb6f686ab9ef6c79a31dab6ef044","src/display_list/structs.rs":"3437d210c51b7bedc4a76db4e5492dda986d8328d87c0b3d5fbf548903543064","src/formatter/mod.rs":"bf40e1e852a116e90fcb0c47a3e59513d0fa7aa8a2be3575f819ed850ab7cc38","src/formatter/style.rs":"ab6e7cb90a8921bd9adfb914f234876f65cbc62cfd92b7dcfabfeeefb936d541","src/lib.rs":"fd655cb0518b4d11d5ff3a92eceefc0f45697c430197e95d3b8bed3bbf90325f","src/snippet.rs":"14a875640ac81eca9a29c351b5a99bb8e88a2970bcdddcf2ce1658de2fcbab85","src/stylesheets/color.rs":"5f8049f41a8d9636e55975e999e7c149d4b54b65b2518ea88be1ae69323b21a1","src/stylesheets/mod.rs":"16a439c043e55dd5a0084bd805154a57f4300a174775d90efd577f901784ef65","src/stylesheets/no_color.rs":"854529529a061df5cab0bf889ac43cb6d0203e674be38ae1cfb6724729beac31","tests/diff/mod.rs":"6e760d4bfda064934646da1461b940ef5ca1416a57428bda47871bb116f7add0","tests/dl_from_snippet.rs":"c1d8a69ea35b147853d392db6f94577ee7fb3bed7a0a8dfb07310d1b848b6fe7","tests/fixtures/no-color/multiline_annotation.toml":"352674f4e37f6a7cccce01cd50c0d190f9658ac344deafa06f445e222d2077f2","tests/fixtures/no-color/multiline_annotation.txt":"ee33c4a17fc72095f217a78f479c3718ad5499d745e4248937f7eaa028ee4328","tests/fixtures/no-color/multiline_annotation2.toml":"cb43d8ff232c16946b69e9b95205986a4a020bf338934212276e20384446a214","tests/fixtures/no-color/multiline_annotation2.txt":"4cdd277194e08b8f38b3045e08f3c180982b576029af66cae7519f43bfd81ca6","tests/fixtures/no-color/multiline_annotation3.toml":"93badadaaffca9382c25ac9286006b4aa59747a1e2cc2c717e003dbdd841c1a5","tests/fixtures/no-color/multiline_annotation3.txt":"66ee253f2566e40e69e8fdfb9837ee803c26bce2275d1cb950de28862bb8e0fe","tests/fixtures/no-color/multiple_annotations.toml":"c570a67e211c324edb2a1427148dba3a62cb2af0aaf5a522d1dd6a03594489b5","tests/fixtures/no-color/multiple_annotations.txt":"b284ab83d9de3aa9d014d3d04ac199517967885bc064f0462c15d6a4d71554aa","tests/fixtures/no-color/simple.toml":"6ef667b5e736fc112a1fb4722a2828aaf8049b8bbf6aacdb730a8f3427900f10","tests/fixtures/no-color/simple.txt":"2a8e4036837503bb53fca8ef761b658090e7869bf9b87197612530ca4e71b7f2","tests/fixtures_test.rs":"903f56c24c500135fed3fc0e40c77a89b98f72ce2e99322658242a6bfbf89a14","tests/formatter.rs":"0849bb94fe27f18faa174669e76694509dbe38a04687af809d1094dea2eddb23","tests/snippet/mod.rs":"06f962abc0eff7a83d3088cf774a86c26adc8889ff5652e3958cf14cc029d0c1"},"package":"d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5"} \ No newline at end of file diff --git a/vendor/annotate-snippets-0.8.0/CHANGELOG.md b/vendor/annotate-snippets-0.8.0/CHANGELOG.md deleted file mode 100644 index e0390a71b..000000000 --- a/vendor/annotate-snippets-0.8.0/CHANGELOG.md +++ /dev/null @@ -1,29 +0,0 @@ -# Changelog - -## Unreleased - - - … - -## annotate-snippets 0.8.0 (April 14, 2020) - - - Replace `ansi_term` with `yansi-term` for improved performance. (#30) - - Turn `Snippet` and `Slice` to work on borrowed slices, rather than Strings. (#32) - - Fix `\r\n` end of lines. (#29) - -## annotate-snippets 0.7.0 (March 30, 2020) - - - Refactor API to use `fmt::Display` (#27) - - Fix SourceAnnotation range (#27) - - Fix column numbers (#22) - - Derive `PartialEq` for `AnnotationType` (#19) - - Update `ansi_term` to 0.12. - -## annotate-snippets 0.6.1 (July 23, 2019) - - - Fix too many anonymized line numbers (#5) - -## annotate-snippets 0.6.0 (June 26, 2019) - - - Add an option to anonymize line numbers (#3) - - Transition the crate to rust-lang org. - - Update the syntax to Rust 2018 idioms. (#4) diff --git a/vendor/annotate-snippets-0.8.0/Cargo.lock b/vendor/annotate-snippets-0.8.0/Cargo.lock deleted file mode 100644 index 18d8f4c0e..000000000 --- a/vendor/annotate-snippets-0.8.0/Cargo.lock +++ /dev/null @@ -1,630 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "annotate-snippets" -version = "0.8.0" -dependencies = [ - "criterion 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", - "toml 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", - "yansi-term 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "hermit-abi 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.68 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "autocfg" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "bitflags" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "bstr" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "regex-automata 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "bumpalo" -version = "3.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "byteorder" -version = "1.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cast" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "clap" -version = "2.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "criterion" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", - "cast 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", - "criterion-plot 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "oorandom 11.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "plotters 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", - "rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 1.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", - "tinytemplate 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "criterion-plot" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cast 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "crossbeam-deque" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memoffset 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "crossbeam-queue" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "crossbeam-utils" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "csv" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bstr 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", - "csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "ryu 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "csv-core" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "difference" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "either" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "hermit-abi" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.68 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "itertools" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "itoa" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "js-sys" -version = "0.3.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "wasm-bindgen 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "libc" -version = "0.2.68" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "log" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "maybe-uninit" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "memchr" -version = "2.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "memoffset" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "num-traits" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "num_cpus" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "hermit-abi 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.68 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "oorandom" -version = "11.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "plotters" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "js-sys 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", - "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", - "web-sys 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro2" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "quote" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rayon" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", - "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", - "rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rayon-core" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "regex" -version = "1.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "regex-syntax 0.6.17 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "regex-automata" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "regex-syntax" -version = "0.6.17" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "ryu" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "serde" -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde_derive 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "serde_derive" -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "serde_json" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "ryu 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "syn" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tinytemplate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "toml" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unicode-width" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unicode-xid" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "walkdir" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-macro 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bumpalo 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-shared 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-macro-support 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-backend 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen-shared 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "web-sys" -version = "0.3.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "js-sys 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)", - "wasm-bindgen 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "winapi" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "winapi-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "yansi-term" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[metadata] -"checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" -"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" -"checksum bstr 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)" = "2889e6d50f394968c8bf4240dc3f2a7eb4680844d27308f798229ac9d4725f41" -"checksum bumpalo 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "12ae9db68ad7fac5fe51304d20f016c911539251075a214f8e663babefa35187" -"checksum byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" -"checksum cast 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4b9434b9a5aa1450faa3f9cb14ea0e8c53bb5d2b3c1bfd1ab4fc03e9f33fbfb0" -"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" -"checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" -"checksum criterion 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1fc755679c12bda8e5523a71e4d654b6bf2e14bd838dfc48cde6559a05caf7d1" -"checksum criterion-plot 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a01e15e0ea58e8234f96146b1f91fa9d0e4dd7a38da93ff7a75d42c0b9d3a545" -"checksum crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" -"checksum crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" -"checksum crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" -"checksum crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" -"checksum csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "00affe7f6ab566df61b4be3ce8cf16bc2576bca0963ceb0955e45d514bf9a279" -"checksum csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" -"checksum difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" -"checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" -"checksum glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" -"checksum hermit-abi 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "725cf19794cf90aa94e65050cb4191ff5d8fa87a498383774c47b332e3af952e" -"checksum itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" -"checksum itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" -"checksum js-sys 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)" = "6a27d435371a2fa5b6d2b028a74bbdb1234f308da363226a2854ca3ff8ba7055" -"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -"checksum libc 0.2.68 (registry+https://github.com/rust-lang/crates.io-index)" = "dea0c0405123bba743ee3f91f49b1c7cfb684eef0da0a50110f758ccf24cdff0" -"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" -"checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" -"checksum memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" -"checksum memoffset 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "b4fc2c02a7e374099d4ee95a193111f72d2110197fe200272371758f6c3643d8" -"checksum num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" -"checksum num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" -"checksum oorandom 11.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ebcec7c9c2a95cacc7cd0ecb89d8a8454eca13906f6deb55258ffff0adeb9405" -"checksum plotters 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)" = "4e3bb8da247d27ae212529352020f3e5ee16e83c0c258061d27b08ab92675eeb" -"checksum proc-macro2 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)" = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3" -"checksum quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f" -"checksum rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "db6ce3297f9c85e16621bb8cca38a06779ffc31bb8184e1be4bed2be4678a098" -"checksum rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "08a89b46efaf957e52b18062fb2f4660f8b8a4dde1807ca002690868ef2c85a9" -"checksum regex 1.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7f6946991529684867e47d86474e3a6d0c0ab9b82d5821e314b1ede31fa3a4b3" -"checksum regex-automata 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "ae1ded71d66a4a97f5e961fd0cb25a5f366a42a41570d16a763a69c092c26ae4" -"checksum regex-syntax 0.6.17 (registry+https://github.com/rust-lang/crates.io-index)" = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae" -"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -"checksum ryu 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "535622e6be132bccd223f4bb2b8ac8d53cda3c7a6394944d3b2b33fb974f9d76" -"checksum same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -"checksum scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -"checksum serde 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)" = "e707fbbf255b8fc8c3b99abb91e7257a622caeb20a9818cbadbeeede4e0932ff" -"checksum serde_derive 1.0.105 (registry+https://github.com/rust-lang/crates.io-index)" = "ac5d00fc561ba2724df6758a17de23df5914f20e41cb00f94d5b7ae42fffaff8" -"checksum serde_json 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)" = "78a7a12c167809363ec3bd7329fc0a3369056996de43c4b37ef3cd54a6ce4867" -"checksum syn 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)" = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" -"checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -"checksum tinytemplate 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "57a3c6667d3e65eb1bc3aed6fd14011c6cbc3a0665218ab7f5daf040b9ec371a" -"checksum toml 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ffc92d160b1eef40665be3a05630d003936a3bc7da7421277846c2613e92c71a" -"checksum unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" -"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" -"checksum walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" -"checksum wasm-bindgen 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "2cc57ce05287f8376e998cbddfb4c8cb43b84a7ec55cf4551d7c00eef317a47f" -"checksum wasm-bindgen-backend 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "d967d37bf6c16cca2973ca3af071d0a2523392e4a594548155d89a678f4237cd" -"checksum wasm-bindgen-macro 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "8bd151b63e1ea881bb742cd20e1d6127cef28399558f3b5d415289bc41eee3a4" -"checksum wasm-bindgen-macro-support 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "d68a5b36eef1be7868f668632863292e37739656a80fc4b9acec7b0bd35a4931" -"checksum wasm-bindgen-shared 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)" = "daf76fe7d25ac79748a37538b7daeed1c7a6867c92d3245c12c6222e4a20d639" -"checksum web-sys 0.3.37 (registry+https://github.com/rust-lang/crates.io-index)" = "2d6f51648d8c56c366144378a33290049eafdd784071077f6fe37dae64c1c4cb" -"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" -"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -"checksum winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" -"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -"checksum yansi-term 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7e44ab40470a13c8746f6a9b5e042ba56dbd55e5a48921e131779b4575935bc7" diff --git a/vendor/annotate-snippets-0.8.0/Cargo.toml b/vendor/annotate-snippets-0.8.0/Cargo.toml deleted file mode 100644 index 3cccbbe7c..000000000 --- a/vendor/annotate-snippets-0.8.0/Cargo.toml +++ /dev/null @@ -1,62 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -edition = "2018" -name = "annotate-snippets" -version = "0.8.0" -authors = ["Zibi Braniecki "] -description = "Library for building code annotations" -readme = "README.md" -keywords = ["code", "analysis", "ascii", "errors", "debug"] -license = "Apache-2.0/MIT" -repository = "https://github.com/rust-lang/annotate-snippets-rs" - -[[bench]] -name = "simple" -harness = false -[dependencies.yansi-term] -version = "0.1" -optional = true -[dev-dependencies.criterion] -version = "0.3" - -[dev-dependencies.difference] -version = "2.0" - -[dev-dependencies.glob] -version = "0.3" - -[dev-dependencies.serde] -version = "1.0" -features = ["derive"] - -[dev-dependencies.toml] -version = "0.5" - -[dev-dependencies.yansi-term] -version = "0.1" - -[features] -color = ["yansi-term"] -default = [] -[badges.coveralls] -branch = "master" -repository = "rust-lang/annotate-snippets-rs" -service = "github" - -[badges.maintenance] -status = "actively-developed" - -[badges.travis-ci] -branch = "master" -repository = "rust-lang/annotate-snippets-rs" diff --git a/vendor/annotate-snippets-0.8.0/LICENSE-APACHE b/vendor/annotate-snippets-0.8.0/LICENSE-APACHE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/annotate-snippets-0.8.0/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/annotate-snippets-0.8.0/LICENSE-MIT b/vendor/annotate-snippets-0.8.0/LICENSE-MIT deleted file mode 100644 index 5655fa311..000000000 --- a/vendor/annotate-snippets-0.8.0/LICENSE-MIT +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2017 Mozilla - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/annotate-snippets-0.8.0/README.md b/vendor/annotate-snippets-0.8.0/README.md deleted file mode 100644 index 592a51e14..000000000 --- a/vendor/annotate-snippets-0.8.0/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# annotate-snippets - -`annotate-snippets` is a Rust library for annotation of programming code slices. - -[![crates.io](https://meritbadge.herokuapp.com/annotate-snippets)](https://crates.io/crates/annotate-snippets) -[![Build Status](https://travis-ci.com/rust-lang/annotate-snippets-rs.svg?branch=master)](https://travis-ci.com/rust-lang/annotate-snippets-rs) -[![Coverage Status](https://coveralls.io/repos/github/rust-lang/annotate-snippets-rs/badge.svg?branch=master)](https://coveralls.io/github/rust-lang/annotate-snippets-rs?branch=master) - -The library helps visualize meta information annotating source code slices. -It takes a data structure called `Snippet` on the input and produces a `String` -which may look like this: - -```text -error[E0308]: mismatched types - --> src/format.rs:52:1 - | -51 | ) -> Option { - | -------------- expected `Option` because of return type -52 | / for ann in annotations { -53 | | match (ann.range.0, ann.range.1) { -54 | | (None, None) => continue, -55 | | (Some(start), Some(end)) if start > end_index => continue, -... | -71 | | } -72 | | } - | |_____^ expected enum `std::option::Option`, found () -``` - -[Documentation][] - -[Documentation]: https://docs.rs/annotate-snippets/ - -Usage ------ - -```rust -use annotate_snippets::{ - display_list::DisplayList, - formatter::DisplayListFormatter, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -fn main() { - let snippet = Snippet { - title: Some(Annotation { - label: Some("expected type, found `22`".to_string()), - id: None, - annotation_type: AnnotationType::Error, - }), - footer: vec![], - slices: vec![ - Slice { - source: r#" -This is an example -content of the slice -which will be annotated -with the list of annotations below. - "#.to_string(), - line_start: 26, - origin: Some("examples/example.txt".to_string()), - fold: false, - annotations: vec![ - SourceAnnotation { - label: "Example error annotation".to_string(), - annotation_type: AnnotationType::Error, - range: (13, 18), - }, - SourceAnnotation { - label: "and here's a warning".to_string(), - annotation_type: AnnotationType::Warning, - range: (34, 50), - }, - ], - }, - ], - }; - - let dl = DisplayList::from(snippet); - let dlf = DisplayListFormatter::new(true, false); - println!("{}", dlf.format(&dl)); -} -``` - -Local Development ------------------ - - cargo build - cargo test - -When submitting a PR please use [`cargo fmt`][] (nightly). - -[`cargo fmt`]: https://github.com/rust-lang/rustfmt diff --git a/vendor/annotate-snippets-0.8.0/benches/simple.rs b/vendor/annotate-snippets-0.8.0/benches/simple.rs deleted file mode 100644 index 4c13a8f00..000000000 --- a/vendor/annotate-snippets-0.8.0/benches/simple.rs +++ /dev/null @@ -1,74 +0,0 @@ -#![allow(clippy::unit_arg)] -#[macro_use] -extern crate criterion; - -use criterion::{black_box, Criterion}; - -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -fn create_snippet() { - let snippet = Snippet { - slices: vec![Slice { - source: r#") -> Option { - for ann in annotations { - match (ann.range.0, ann.range.1) { - (None, None) => continue, - (Some(start), Some(end)) if start > end_index => continue, - (Some(start), Some(end)) if start >= start_index => { - let label = if let Some(ref label) = ann.label { - format!(" {}", label) - } else { - String::from("") - }; - - return Some(format!( - "{}{}{}", - " ".repeat(start - start_index), - "^".repeat(end - start), - label - )); - } - _ => continue, - } - }"#, - line_start: 51, - origin: Some("src/format.rs"), - fold: false, - annotations: vec![ - SourceAnnotation { - label: "expected `Option` because of return type", - annotation_type: AnnotationType::Warning, - range: (5, 19), - }, - SourceAnnotation { - label: "expected enum `std::option::Option`", - annotation_type: AnnotationType::Error, - range: (26, 724), - }, - ], - }], - title: Some(Annotation { - label: Some("mismatched types"), - id: Some("E0308"), - annotation_type: AnnotationType::Error, - }), - footer: vec![], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - let dl = DisplayList::from(snippet); - let _result = dl.to_string(); -} - -pub fn criterion_benchmark(c: &mut Criterion) { - c.bench_function("format", |b| b.iter(|| black_box(create_snippet()))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/vendor/annotate-snippets-0.8.0/examples/expected_type.rs b/vendor/annotate-snippets-0.8.0/examples/expected_type.rs deleted file mode 100644 index 89f0ddc11..000000000 --- a/vendor/annotate-snippets-0.8.0/examples/expected_type.rs +++ /dev/null @@ -1,43 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -fn main() { - let snippet = Snippet { - title: Some(Annotation { - label: Some("expected type, found `22`"), - id: None, - annotation_type: AnnotationType::Error, - }), - footer: vec![], - slices: vec![Slice { - source: r#" annotations: vec![SourceAnnotation { - label: "expected struct `annotate_snippets::snippet::Slice`, found reference" - , - range: <22, 25>,"#, - line_start: 26, - origin: Some("examples/footer.rs"), - fold: true, - annotations: vec![ - SourceAnnotation { - label: "", - annotation_type: AnnotationType::Error, - range: (205, 207), - }, - SourceAnnotation { - label: "while parsing this struct", - annotation_type: AnnotationType::Info, - range: (34, 50), - }, - ], - }], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - let dl = DisplayList::from(snippet); - println!("{}", dl); -} diff --git a/vendor/annotate-snippets-0.8.0/examples/footer.rs b/vendor/annotate-snippets-0.8.0/examples/footer.rs deleted file mode 100644 index f3c15c410..000000000 --- a/vendor/annotate-snippets-0.8.0/examples/footer.rs +++ /dev/null @@ -1,39 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -fn main() { - let snippet = Snippet { - title: Some(Annotation { - label: Some("mismatched types"), - id: Some("E0308"), - annotation_type: AnnotationType::Error, - }), - footer: vec![Annotation { - label: Some( - "expected type: `snippet::Annotation`\n found type: `__&__snippet::Annotation`", - ), - id: None, - annotation_type: AnnotationType::Note, - }], - slices: vec![Slice { - source: " slices: vec![\"A\",", - line_start: 13, - origin: Some("src/multislice.rs"), - fold: false, - annotations: vec![SourceAnnotation { - label: "expected struct `annotate_snippets::snippet::Slice`, found reference", - range: (21, 24), - annotation_type: AnnotationType::Error, - }], - }], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - let dl = DisplayList::from(snippet); - println!("{}", dl); -} diff --git a/vendor/annotate-snippets-0.8.0/examples/format.rs b/vendor/annotate-snippets-0.8.0/examples/format.rs deleted file mode 100644 index 98b77a140..000000000 --- a/vendor/annotate-snippets-0.8.0/examples/format.rs +++ /dev/null @@ -1,61 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -fn main() { - let snippet = Snippet { - slices: vec![Slice { - source: r#") -> Option { - for ann in annotations { - match (ann.range.0, ann.range.1) { - (None, None) => continue, - (Some(start), Some(end)) if start > end_index => continue, - (Some(start), Some(end)) if start >= start_index => { - let label = if let Some(ref label) = ann.label { - format!(" {}", label) - } else { - String::from("") - }; - - return Some(format!( - "{}{}{}", - " ".repeat(start - start_index), - "^".repeat(end - start), - label - )); - } - _ => continue, - } - }"#, - line_start: 51, - origin: Some("src/format.rs"), - fold: false, - annotations: vec![ - SourceAnnotation { - label: "expected `Option` because of return type", - annotation_type: AnnotationType::Warning, - range: (5, 19), - }, - SourceAnnotation { - label: "expected enum `std::option::Option`", - annotation_type: AnnotationType::Error, - range: (26, 724), - }, - ], - }], - title: Some(Annotation { - label: Some("mismatched types"), - id: Some("E0308"), - annotation_type: AnnotationType::Error, - }), - footer: vec![], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - let dl = DisplayList::from(snippet); - println!("{}", dl); -} diff --git a/vendor/annotate-snippets-0.8.0/examples/multislice.rs b/vendor/annotate-snippets-0.8.0/examples/multislice.rs deleted file mode 100644 index 5675a07da..000000000 --- a/vendor/annotate-snippets-0.8.0/examples/multislice.rs +++ /dev/null @@ -1,38 +0,0 @@ -use annotate_snippets::{ - display_list::{DisplayList, FormatOptions}, - snippet::{Annotation, AnnotationType, Slice, Snippet}, -}; - -fn main() { - let snippet = Snippet { - title: Some(Annotation { - label: Some("mismatched types"), - id: None, - annotation_type: AnnotationType::Error, - }), - footer: vec![], - slices: vec![ - Slice { - source: "Foo", - line_start: 51, - origin: Some("src/format.rs"), - fold: false, - annotations: vec![], - }, - Slice { - source: "Faa", - line_start: 129, - origin: Some("src/display.rs"), - fold: false, - annotations: vec![], - }, - ], - opt: FormatOptions { - color: true, - ..Default::default() - }, - }; - - let dl = DisplayList::from(snippet); - println!("{}", dl); -} diff --git a/vendor/annotate-snippets-0.8.0/src/display_list/from_snippet.rs b/vendor/annotate-snippets-0.8.0/src/display_list/from_snippet.rs deleted file mode 100644 index b3ba5a3dd..000000000 --- a/vendor/annotate-snippets-0.8.0/src/display_list/from_snippet.rs +++ /dev/null @@ -1,517 +0,0 @@ -//! Trait for converting `Snippet` to `DisplayList`. -use super::*; -use crate::{formatter::get_term_style, snippet}; - -struct CursorLines<'a>(&'a str); - -impl<'a> CursorLines<'a> { - fn new(src: &str) -> CursorLines<'_> { - CursorLines(src) - } -} - -enum EndLine { - EOF = 0, - CRLF = 1, - LF = 2, -} - -impl<'a> Iterator for CursorLines<'a> { - type Item = (&'a str, EndLine); - - fn next(&mut self) -> Option { - if self.0.is_empty() { - None - } else { - self.0 - .find('\n') - .map(|x| { - let ret = if 0 < x { - if self.0.as_bytes()[x - 1] == b'\r' { - (&self.0[..x - 1], EndLine::LF) - } else { - (&self.0[..x], EndLine::CRLF) - } - } else { - ("", EndLine::CRLF) - }; - self.0 = &self.0[x + 1..]; - ret - }) - .or_else(|| { - let ret = Some((&self.0[..], EndLine::EOF)); - self.0 = ""; - ret - }) - } - } -} - -fn format_label( - label: Option<&str>, - style: Option, -) -> Vec> { - let mut result = vec![]; - if let Some(label) = label { - for (idx, element) in label.split("__").enumerate() { - let element_style = match style { - Some(s) => s, - None => { - if idx % 2 == 0 { - DisplayTextStyle::Regular - } else { - DisplayTextStyle::Emphasis - } - } - }; - result.push(DisplayTextFragment { - content: element, - style: element_style, - }); - } - } - result -} - -fn format_title(annotation: snippet::Annotation<'_>) -> DisplayLine<'_> { - let label = annotation.label.unwrap_or_default(); - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::from(annotation.annotation_type), - id: annotation.id, - label: format_label(Some(&label), Some(DisplayTextStyle::Emphasis)), - }, - source_aligned: false, - continuation: false, - }) -} - -fn format_annotation(annotation: snippet::Annotation<'_>) -> Vec> { - let mut result = vec![]; - let label = annotation.label.unwrap_or_default(); - for (i, line) in label.lines().enumerate() { - result.push(DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::from(annotation.annotation_type), - id: None, - label: format_label(Some(line), None), - }, - source_aligned: true, - continuation: i != 0, - })); - } - result -} - -fn format_slice( - mut slice: snippet::Slice<'_>, - is_first: bool, - has_footer: bool, -) -> Vec> { - let main_range = slice.annotations.get(0).map(|x| x.range.0); - let row = slice.line_start; - let origin = slice.origin.take(); - let mut body = format_body(slice, has_footer); - let header = format_header(origin, main_range, row, &body, is_first); - let mut result = vec![]; - - if let Some(header) = header { - result.push(header); - } - result.append(&mut body); - result -} - -fn format_header<'a>( - origin: Option<&'a str>, - main_range: Option, - mut row: usize, - body: &[DisplayLine<'_>], - is_first: bool, -) -> Option> { - let display_header = if is_first { - DisplayHeaderType::Initial - } else { - DisplayHeaderType::Continuation - }; - - if let Some(main_range) = main_range { - let mut col = 1; - - for item in body { - if let DisplayLine::Source { - line: DisplaySourceLine::Content { range, .. }, - .. - } = item - { - if main_range >= range.0 && main_range <= range.1 { - col = main_range - range.0 + 1; - break; - } - row += 1; - } - } - if let Some(path) = origin { - return Some(DisplayLine::Raw(DisplayRawLine::Origin { - path, - pos: Some((row, col)), - header_type: display_header, - })); - } - } - if let Some(path) = origin { - return Some(DisplayLine::Raw(DisplayRawLine::Origin { - path, - pos: None, - header_type: display_header, - })); - } - None -} - -fn fold_body(mut body: Vec>) -> Vec> { - enum Line { - Fold(usize), - Source(usize), - }; - - let mut lines = vec![]; - let mut no_annotation_lines_counter = 0; - - for (idx, line) in body.iter().enumerate() { - match line { - DisplayLine::Source { - line: DisplaySourceLine::Annotation { .. }, - .. - } => { - if no_annotation_lines_counter > 2 { - let fold_start = idx - no_annotation_lines_counter; - let fold_end = idx; - let pre_len = if no_annotation_lines_counter > 8 { - 4 - } else { - 0 - }; - let post_len = if no_annotation_lines_counter > 8 { - 2 - } else { - 1 - }; - for (i, _) in body - .iter() - .enumerate() - .take(fold_start + pre_len) - .skip(fold_start) - { - lines.push(Line::Source(i)); - } - lines.push(Line::Fold(idx)); - for (i, _) in body - .iter() - .enumerate() - .take(fold_end) - .skip(fold_end - post_len) - { - lines.push(Line::Source(i)); - } - } else { - let start = idx - no_annotation_lines_counter; - for (i, _) in body.iter().enumerate().take(idx).skip(start) { - lines.push(Line::Source(i)); - } - } - no_annotation_lines_counter = 0; - } - DisplayLine::Source { .. } => { - no_annotation_lines_counter += 1; - continue; - } - _ => { - no_annotation_lines_counter += 1; - } - } - lines.push(Line::Source(idx)); - } - - let mut new_body = vec![]; - let mut removed = 0; - for line in lines { - match line { - Line::Source(i) => { - new_body.push(body.remove(i - removed)); - removed += 1; - } - Line::Fold(i) => { - if let DisplayLine::Source { - line: DisplaySourceLine::Annotation { .. }, - ref inline_marks, - .. - } = body.get(i - removed).unwrap() - { - new_body.push(DisplayLine::Fold { - inline_marks: inline_marks.clone(), - }) - } else { - unreachable!() - } - } - } - } - - new_body -} - -fn format_body(slice: snippet::Slice<'_>, has_footer: bool) -> Vec> { - let source_len = slice.source.chars().count(); - if let Some(bigger) = slice.annotations.iter().find_map(|x| { - if source_len < x.range.1 { - Some(x.range) - } else { - None - } - }) { - panic!( - "SourceAnnotation range `{:?}` is bigger than source length `{}`", - bigger, source_len - ) - } - - let mut body = vec![]; - let mut current_line = slice.line_start; - let mut current_index = 0; - let mut line_index_ranges = vec![]; - - for (line, end_line) in CursorLines::new(slice.source) { - let line_length = line.chars().count(); - let line_range = (current_index, current_index + line_length); - body.push(DisplayLine::Source { - lineno: Some(current_line), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: line, - range: line_range, - }, - }); - line_index_ranges.push(line_range); - current_line += 1; - current_index += line_length + end_line as usize; - } - - let mut annotation_line_count = 0; - let mut annotations = slice.annotations; - for (idx, (line_start, line_end)) in line_index_ranges.into_iter().enumerate() { - // It would be nice to use filter_drain here once it's stable. - annotations = annotations - .into_iter() - .filter(|annotation| { - let body_idx = idx + annotation_line_count; - let annotation_type = match annotation.annotation_type { - snippet::AnnotationType::Error => DisplayAnnotationType::None, - snippet::AnnotationType::Warning => DisplayAnnotationType::None, - _ => DisplayAnnotationType::from(annotation.annotation_type), - }; - match annotation.range { - (start, _) if start > line_end => true, - (start, end) - if start >= line_start && end <= line_end - || start == line_end && end - start <= 1 => - { - let range = (start - line_start, end - line_start); - body.insert( - body_idx + 1, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - annotation: Annotation { - annotation_type, - id: None, - label: format_label(Some(&annotation.label), None), - }, - range, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - ); - annotation_line_count += 1; - false - } - (start, end) if start >= line_start && start <= line_end && end > line_end => { - if start - line_start == 0 { - if let DisplayLine::Source { - ref mut inline_marks, - .. - } = body[body_idx] - { - inline_marks.push(DisplayMark { - mark_type: DisplayMarkType::AnnotationStart, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - }); - } - } else { - let range = (start - line_start, start - line_start + 1); - body.insert( - body_idx + 1, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::None, - id: None, - label: vec![], - }, - range, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - annotation_part: DisplayAnnotationPart::MultilineStart, - }, - }, - ); - annotation_line_count += 1; - } - true - } - (start, end) if start < line_start && end > line_end => { - if let DisplayLine::Source { - ref mut inline_marks, - .. - } = body[body_idx] - { - inline_marks.push(DisplayMark { - mark_type: DisplayMarkType::AnnotationThrough, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - }); - } - true - } - (start, end) if start < line_start && end >= line_start && end <= line_end => { - if let DisplayLine::Source { - ref mut inline_marks, - .. - } = body[body_idx] - { - inline_marks.push(DisplayMark { - mark_type: DisplayMarkType::AnnotationThrough, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - }); - } - - let range = (end - line_start, end - line_start + 1); - body.insert( - body_idx + 1, - DisplayLine::Source { - lineno: None, - inline_marks: vec![DisplayMark { - mark_type: DisplayMarkType::AnnotationThrough, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - }], - line: DisplaySourceLine::Annotation { - annotation: Annotation { - annotation_type, - id: None, - label: format_label(Some(&annotation.label), None), - }, - range, - annotation_type: DisplayAnnotationType::from( - annotation.annotation_type, - ), - annotation_part: DisplayAnnotationPart::MultilineEnd, - }, - }, - ); - annotation_line_count += 1; - false - } - _ => true, - } - }) - .collect(); - } - - if slice.fold { - body = fold_body(body); - } - - body.insert( - 0, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Empty, - }, - ); - if has_footer { - body.push(DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Empty, - }); - } else if let Some(DisplayLine::Source { .. }) = body.last() { - body.push(DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Empty, - }); - } - body -} - -impl<'a> From> for DisplayList<'a> { - fn from( - snippet::Snippet { - title, - footer, - slices, - opt, - }: snippet::Snippet<'a>, - ) -> DisplayList<'a> { - let mut body = vec![]; - if let Some(annotation) = title { - body.push(format_title(annotation)); - } - - for (idx, slice) in slices.into_iter().enumerate() { - body.append(&mut format_slice(slice, idx == 0, !footer.is_empty())); - } - - for annotation in footer { - body.append(&mut format_annotation(annotation)); - } - - let FormatOptions { - color, - anonymized_line_numbers, - } = opt; - - Self { - body, - stylesheet: get_term_style(color), - anonymized_line_numbers, - } - } -} - -impl From for DisplayAnnotationType { - fn from(at: snippet::AnnotationType) -> Self { - match at { - snippet::AnnotationType::Error => DisplayAnnotationType::Error, - snippet::AnnotationType::Warning => DisplayAnnotationType::Warning, - snippet::AnnotationType::Info => DisplayAnnotationType::Info, - snippet::AnnotationType::Note => DisplayAnnotationType::Note, - snippet::AnnotationType::Help => DisplayAnnotationType::Help, - } - } -} diff --git a/vendor/annotate-snippets-0.8.0/src/display_list/mod.rs b/vendor/annotate-snippets-0.8.0/src/display_list/mod.rs deleted file mode 100644 index 224a9f580..000000000 --- a/vendor/annotate-snippets-0.8.0/src/display_list/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! display_list module stores the output model for the snippet. -//! -//! `DisplayList` is a central structure in the crate, which contains -//! the structured list of lines to be displayed. -//! -//! It is made of two types of lines: `Source` and `Raw`. All `Source` lines -//! are structured using four columns: -//! -//! ```text -//! /------------ (1) Line number column. -//! | /--------- (2) Line number column delimiter. -//! | | /------- (3) Inline marks column. -//! | | | /--- (4) Content column with the source and annotations for slices. -//! | | | | -//! ============================================================================= -//! error[E0308]: mismatched types -//! --> src/format.rs:51:5 -//! | -//! 151 | / fn test() -> String { -//! 152 | | return "test"; -//! 153 | | } -//! | |___^ error: expected `String`, for `&str`. -//! | -//! ``` -//! -//! The first two lines of the example above are `Raw` lines, while the rest -//! are `Source` lines. -//! -//! `DisplayList` does not store column alignment information, and those are -//! only calculated by the implementation of `std::fmt::Display` using information such as -//! styling. -//! -//! The above snippet has been built out of the following structure: -mod from_snippet; -mod structs; - -pub use self::structs::*; diff --git a/vendor/annotate-snippets-0.8.0/src/display_list/structs.rs b/vendor/annotate-snippets-0.8.0/src/display_list/structs.rs deleted file mode 100644 index 8f6d8fcf1..000000000 --- a/vendor/annotate-snippets-0.8.0/src/display_list/structs.rs +++ /dev/null @@ -1,191 +0,0 @@ -use std::fmt; - -use crate::formatter::{get_term_style, style::Stylesheet}; - -/// List of lines to be displayed. -pub struct DisplayList<'a> { - pub body: Vec>, - pub stylesheet: Box, - pub anonymized_line_numbers: bool, -} - -impl<'a> From>> for DisplayList<'a> { - fn from(body: Vec>) -> DisplayList<'a> { - Self { - body, - anonymized_line_numbers: false, - stylesheet: get_term_style(false), - } - } -} - -impl<'a> PartialEq for DisplayList<'a> { - fn eq(&self, other: &Self) -> bool { - self.body == other.body && self.anonymized_line_numbers == other.anonymized_line_numbers - } -} - -impl<'a> fmt::Debug for DisplayList<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DisplayList") - .field("body", &self.body) - .field("anonymized_line_numbers", &self.anonymized_line_numbers) - .finish() - } -} - -#[derive(Debug, Default, Copy, Clone)] -pub struct FormatOptions { - pub color: bool, - pub anonymized_line_numbers: bool, -} - -/// Inline annotation which can be used in either Raw or Source line. -#[derive(Debug, PartialEq)] -pub struct Annotation<'a> { - pub annotation_type: DisplayAnnotationType, - pub id: Option<&'a str>, - pub label: Vec>, -} - -/// A single line used in `DisplayList`. -#[derive(Debug, PartialEq)] -pub enum DisplayLine<'a> { - /// A line with `lineno` portion of the slice. - Source { - lineno: Option, - inline_marks: Vec, - line: DisplaySourceLine<'a>, - }, - - /// A line indicating a folded part of the slice. - Fold { inline_marks: Vec }, - - /// A line which is displayed outside of slices. - Raw(DisplayRawLine<'a>), -} - -/// A source line. -#[derive(Debug, PartialEq)] -pub enum DisplaySourceLine<'a> { - /// A line with the content of the Slice. - Content { - text: &'a str, - range: (usize, usize), // meta information for annotation placement. - }, - - /// An annotation line which is displayed in context of the slice. - Annotation { - annotation: Annotation<'a>, - range: (usize, usize), - annotation_type: DisplayAnnotationType, - annotation_part: DisplayAnnotationPart, - }, - - /// An empty source line. - Empty, -} - -/// Raw line - a line which does not have the `lineno` part and is not considered -/// a part of the snippet. -#[derive(Debug, PartialEq)] -pub enum DisplayRawLine<'a> { - /// A line which provides information about the location of the given - /// slice in the project structure. - Origin { - path: &'a str, - pos: Option<(usize, usize)>, - header_type: DisplayHeaderType, - }, - - /// An annotation line which is not part of any snippet. - Annotation { - annotation: Annotation<'a>, - - /// If set to `true`, the annotation will be aligned to the - /// lineno delimiter of the snippet. - source_aligned: bool, - /// If set to `true`, only the label of the `Annotation` will be - /// displayed. It allows for a multiline annotation to be aligned - /// without displaing the meta information (`type` and `id`) to be - /// displayed on each line. - continuation: bool, - }, -} - -/// An inline text fragment which any label is composed of. -#[derive(Debug, PartialEq)] -pub struct DisplayTextFragment<'a> { - pub content: &'a str, - pub style: DisplayTextStyle, -} - -/// A style for the `DisplayTextFragment` which can be visually formatted. -/// -/// This information may be used to emphasis parts of the label. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum DisplayTextStyle { - Regular, - Emphasis, -} - -/// An indicator of what part of the annotation a given `Annotation` is. -#[derive(Debug, Clone, PartialEq)] -pub enum DisplayAnnotationPart { - /// A standalone, single-line annotation. - Standalone, - /// A continuation of a multi-line label of an annotation. - LabelContinuation, - /// A consequitive annotation in case multiple annotations annotate a single line. - Consequitive, - /// A line starting a multiline annotation. - MultilineStart, - /// A line ending a multiline annotation. - MultilineEnd, -} - -/// A visual mark used in `inline_marks` field of the `DisplaySourceLine`. -#[derive(Debug, Clone, PartialEq)] -pub struct DisplayMark { - pub mark_type: DisplayMarkType, - pub annotation_type: DisplayAnnotationType, -} - -/// A type of the `DisplayMark`. -#[derive(Debug, Clone, PartialEq)] -pub enum DisplayMarkType { - /// A mark indicating a multiline annotation going through the current line. - AnnotationThrough, - /// A mark indicating a multiline annotation starting on the given line. - AnnotationStart, -} - -/// A type of the `Annotation` which may impact the sigils, style or text displayed. -/// -/// There are several ways in which the `DisplayListFormatter` uses this information -/// when formatting the `DisplayList`: -/// -/// * An annotation may display the name of the type like `error` or `info`. -/// * An underline for `Error` may be `^^^` while for `Warning` it coule be `---`. -/// * `ColorStylesheet` may use different colors for different annotations. -#[derive(Debug, Clone, PartialEq)] -pub enum DisplayAnnotationType { - None, - Error, - Warning, - Info, - Note, - Help, -} - -/// Information whether the header is the initial one or a consequitive one -/// for multi-slice cases. -// TODO: private -#[derive(Debug, Clone, PartialEq)] -pub enum DisplayHeaderType { - /// Initial header is the first header in the snippet. - Initial, - - /// Continuation marks all headers of following slices in the snippet. - Continuation, -} diff --git a/vendor/annotate-snippets-0.8.0/src/formatter/mod.rs b/vendor/annotate-snippets-0.8.0/src/formatter/mod.rs deleted file mode 100644 index e93aeb329..000000000 --- a/vendor/annotate-snippets-0.8.0/src/formatter/mod.rs +++ /dev/null @@ -1,397 +0,0 @@ -use std::{ - cmp, - fmt::{self, Display, Write}, -}; - -pub mod style; - -use self::style::{Style, StyleClass, Stylesheet}; - -#[cfg(feature = "color")] -use crate::stylesheets::color::AnsiTermStylesheet; -use crate::{display_list::*, stylesheets::no_color::NoColorStylesheet}; - -fn format_repeat_char(c: char, n: usize, f: &mut fmt::Formatter<'_>) -> fmt::Result { - for _ in 0..n { - f.write_char(c)?; - } - Ok(()) -} - -#[inline] -fn is_annotation_empty(annotation: &Annotation<'_>) -> bool { - annotation - .label - .iter() - .all(|fragment| fragment.content.is_empty()) -} - -#[cfg(feature = "color")] -#[inline] -pub fn get_term_style(color: bool) -> Box { - if color { - Box::new(AnsiTermStylesheet) - } else { - Box::new(NoColorStylesheet) - } -} - -#[cfg(not(feature = "color"))] -#[inline] -pub fn get_term_style(_color: bool) -> Box { - Box::new(NoColorStylesheet) -} - -impl<'a> fmt::Display for DisplayList<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let lineno_width = self.body.iter().fold(0, |max, line| match line { - DisplayLine::Source { - lineno: Some(lineno), - .. - } => { - // The largest line is the largest width. - cmp::max(*lineno, max) - } - _ => max, - }); - let lineno_width = if lineno_width == 0 { - lineno_width - } else if self.anonymized_line_numbers { - Self::ANONYMIZED_LINE_NUM.len() - } else { - ((lineno_width as f64).log10().floor() as usize) + 1 - }; - let inline_marks_width = self.body.iter().fold(0, |max, line| match line { - DisplayLine::Source { inline_marks, .. } => cmp::max(inline_marks.len(), max), - _ => max, - }); - - for (i, line) in self.body.iter().enumerate() { - self.format_line(line, lineno_width, inline_marks_width, f)?; - if i + 1 < self.body.len() { - f.write_char('\n')?; - } - } - Ok(()) - } -} - -impl<'a> DisplayList<'a> { - const ANONYMIZED_LINE_NUM: &'static str = "LL"; - const ERROR_TXT: &'static str = "error"; - const HELP_TXT: &'static str = "help"; - const INFO_TXT: &'static str = "info"; - const NOTE_TXT: &'static str = "note"; - const WARNING_TXT: &'static str = "warning"; - - #[inline] - fn format_annotation_type( - annotation_type: &DisplayAnnotationType, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - match annotation_type { - DisplayAnnotationType::Error => f.write_str(Self::ERROR_TXT), - DisplayAnnotationType::Help => f.write_str(Self::HELP_TXT), - DisplayAnnotationType::Info => f.write_str(Self::INFO_TXT), - DisplayAnnotationType::Note => f.write_str(Self::NOTE_TXT), - DisplayAnnotationType::Warning => f.write_str(Self::WARNING_TXT), - DisplayAnnotationType::None => Ok(()), - } - } - - fn annotation_type_len(annotation_type: &DisplayAnnotationType) -> usize { - match annotation_type { - DisplayAnnotationType::Error => Self::ERROR_TXT.len(), - DisplayAnnotationType::Help => Self::HELP_TXT.len(), - DisplayAnnotationType::Info => Self::INFO_TXT.len(), - DisplayAnnotationType::Note => Self::NOTE_TXT.len(), - DisplayAnnotationType::Warning => Self::WARNING_TXT.len(), - DisplayAnnotationType::None => 0, - } - } - - fn get_annotation_style(&self, annotation_type: &DisplayAnnotationType) -> Box { - self.stylesheet.get_style(match annotation_type { - DisplayAnnotationType::Error => StyleClass::Error, - DisplayAnnotationType::Warning => StyleClass::Warning, - DisplayAnnotationType::Info => StyleClass::Info, - DisplayAnnotationType::Note => StyleClass::Note, - DisplayAnnotationType::Help => StyleClass::Help, - DisplayAnnotationType::None => StyleClass::None, - }) - } - - fn format_label( - &self, - label: &[DisplayTextFragment<'_>], - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - let emphasis_style = self.stylesheet.get_style(StyleClass::Emphasis); - - for fragment in label { - match fragment.style { - DisplayTextStyle::Regular => fragment.content.fmt(f)?, - DisplayTextStyle::Emphasis => emphasis_style.paint(&fragment.content, f)?, - } - } - Ok(()) - } - - fn format_annotation( - &self, - annotation: &Annotation<'_>, - continuation: bool, - in_source: bool, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - let color = self.get_annotation_style(&annotation.annotation_type); - let formatted_len = if let Some(id) = &annotation.id { - 2 + id.len() + Self::annotation_type_len(&annotation.annotation_type) - } else { - Self::annotation_type_len(&annotation.annotation_type) - }; - - if continuation { - format_repeat_char(' ', formatted_len + 2, f)?; - return self.format_label(&annotation.label, f); - } - if formatted_len == 0 { - self.format_label(&annotation.label, f) - } else { - color.paint_fn( - Box::new(|f| { - Self::format_annotation_type(&annotation.annotation_type, f)?; - if let Some(id) = &annotation.id { - f.write_char('[')?; - f.write_str(id)?; - f.write_char(']')?; - } - Ok(()) - }), - f, - )?; - if !is_annotation_empty(annotation) { - if in_source { - color.paint_fn( - Box::new(|f| { - f.write_str(": ")?; - self.format_label(&annotation.label, f) - }), - f, - )?; - } else { - f.write_str(": ")?; - self.format_label(&annotation.label, f)?; - } - } - Ok(()) - } - } - - #[inline] - fn format_source_line( - &self, - line: &DisplaySourceLine<'_>, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - match line { - DisplaySourceLine::Empty => Ok(()), - DisplaySourceLine::Content { text, .. } => { - f.write_char(' ')?; - text.fmt(f) - } - DisplaySourceLine::Annotation { - range, - annotation, - annotation_type, - annotation_part, - } => { - let indent_char = match annotation_part { - DisplayAnnotationPart::Standalone => ' ', - DisplayAnnotationPart::LabelContinuation => ' ', - DisplayAnnotationPart::Consequitive => ' ', - DisplayAnnotationPart::MultilineStart => '_', - DisplayAnnotationPart::MultilineEnd => '_', - }; - let mark = match annotation_type { - DisplayAnnotationType::Error => '^', - DisplayAnnotationType::Warning => '-', - DisplayAnnotationType::Info => '-', - DisplayAnnotationType::Note => '-', - DisplayAnnotationType::Help => '-', - DisplayAnnotationType::None => ' ', - }; - let color = self.get_annotation_style(annotation_type); - let indent_length = match annotation_part { - DisplayAnnotationPart::LabelContinuation => range.1, - DisplayAnnotationPart::Consequitive => range.1, - _ => range.0, - }; - - color.paint_fn( - Box::new(|f| { - format_repeat_char(indent_char, indent_length + 1, f)?; - format_repeat_char(mark, range.1 - indent_length, f) - }), - f, - )?; - - if !is_annotation_empty(&annotation) { - f.write_char(' ')?; - color.paint_fn( - Box::new(|f| { - self.format_annotation( - annotation, - annotation_part == &DisplayAnnotationPart::LabelContinuation, - true, - f, - ) - }), - f, - )?; - } - - Ok(()) - } - } - } - - #[inline] - fn format_raw_line( - &self, - line: &DisplayRawLine<'_>, - lineno_width: usize, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - match line { - DisplayRawLine::Origin { - path, - pos, - header_type, - } => { - let header_sigil = match header_type { - DisplayHeaderType::Initial => "-->", - DisplayHeaderType::Continuation => ":::", - }; - let lineno_color = self.stylesheet.get_style(StyleClass::LineNo); - - if let Some((col, row)) = pos { - format_repeat_char(' ', lineno_width, f)?; - lineno_color.paint(header_sigil, f)?; - f.write_char(' ')?; - path.fmt(f)?; - f.write_char(':')?; - col.fmt(f)?; - f.write_char(':')?; - row.fmt(f) - } else { - format_repeat_char(' ', lineno_width, f)?; - lineno_color.paint(header_sigil, f)?; - f.write_char(' ')?; - path.fmt(f) - } - } - DisplayRawLine::Annotation { - annotation, - source_aligned, - continuation, - } => { - if *source_aligned { - if *continuation { - format_repeat_char(' ', lineno_width + 3, f)?; - self.format_annotation(annotation, *continuation, false, f) - } else { - let lineno_color = self.stylesheet.get_style(StyleClass::LineNo); - format_repeat_char(' ', lineno_width, f)?; - f.write_char(' ')?; - lineno_color.paint("=", f)?; - f.write_char(' ')?; - self.format_annotation(annotation, *continuation, false, f) - } - } else { - self.format_annotation(annotation, *continuation, false, f) - } - } - } - } - - #[inline] - fn format_line( - &self, - dl: &DisplayLine<'_>, - lineno_width: usize, - inline_marks_width: usize, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - match dl { - DisplayLine::Source { - lineno, - inline_marks, - line, - } => { - let lineno_color = self.stylesheet.get_style(StyleClass::LineNo); - if self.anonymized_line_numbers && lineno.is_some() { - lineno_color.paint_fn( - Box::new(|f| { - f.write_str(Self::ANONYMIZED_LINE_NUM)?; - f.write_str(" |") - }), - f, - )?; - } else { - lineno_color.paint_fn( - Box::new(|f| { - match lineno { - Some(n) => write!(f, "{:>width$}", n, width = lineno_width), - None => format_repeat_char(' ', lineno_width, f), - }?; - f.write_str(" |") - }), - f, - )?; - } - if *line != DisplaySourceLine::Empty { - if !inline_marks.is_empty() || 0 < inline_marks_width { - f.write_char(' ')?; - self.format_inline_marks(inline_marks, inline_marks_width, f)?; - } - self.format_source_line(line, f)?; - } else if !inline_marks.is_empty() { - f.write_char(' ')?; - self.format_inline_marks(inline_marks, inline_marks_width, f)?; - } - Ok(()) - } - DisplayLine::Fold { inline_marks } => { - f.write_str("...")?; - if !inline_marks.is_empty() || 0 < inline_marks_width { - format_repeat_char(' ', lineno_width, f)?; - self.format_inline_marks(inline_marks, inline_marks_width, f)?; - } - Ok(()) - } - DisplayLine::Raw(line) => self.format_raw_line(line, lineno_width, f), - } - } - - fn format_inline_marks( - &self, - inline_marks: &[DisplayMark], - inline_marks_width: usize, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - format_repeat_char(' ', inline_marks_width - inline_marks.len(), f)?; - for mark in inline_marks { - self.get_annotation_style(&mark.annotation_type).paint_fn( - Box::new(|f| { - f.write_char(match mark.mark_type { - DisplayMarkType::AnnotationThrough => '|', - DisplayMarkType::AnnotationStart => '/', - }) - }), - f, - )?; - } - Ok(()) - } -} diff --git a/vendor/annotate-snippets-0.8.0/src/formatter/style.rs b/vendor/annotate-snippets-0.8.0/src/formatter/style.rs deleted file mode 100644 index f76e6b0ab..000000000 --- a/vendor/annotate-snippets-0.8.0/src/formatter/style.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! Set of structures required to implement a stylesheet -//! -//! In order to provide additional styling information for the -//! formatter, a structs can implement `Stylesheet` and `Style` -//! traits. -//! -use std::fmt; - -/// StyleClass is a collection of named variants of style classes -pub enum StyleClass { - /// Message indicating an error. - Error, - /// Message indicating a warning. - Warning, - /// Message indicating an information. - Info, - /// Message indicating a note. - Note, - /// Message indicating a help. - Help, - - /// Style for line numbers. - LineNo, - - /// Parts of the text that are to be emphasised. - Emphasis, - - /// Parts of the text that are regular. Usually a no-op. - None, -} - -/// This trait implements a return value for the `Stylesheet::get_style`. -pub trait Style { - /// The method used to write text with formatter - fn paint(&self, text: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result; - /// The method used to write display function with formatter - fn paint_fn<'a>( - &self, - c: Box) -> fmt::Result + 'a>, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result; - /// The method used by the DisplayListFormatter to display the message - /// in bold font. - fn bold(&self) -> Box; -} - -/// Trait to annotate structs that can provide `Style` implementations for -/// every `StyleClass` variant. -pub trait Stylesheet { - /// Returns a `Style` implementer based on the requested `StyleClass` variant. - fn get_style(&self, class: StyleClass) -> Box; -} diff --git a/vendor/annotate-snippets-0.8.0/src/lib.rs b/vendor/annotate-snippets-0.8.0/src/lib.rs deleted file mode 100644 index 46b25e156..000000000 --- a/vendor/annotate-snippets-0.8.0/src/lib.rs +++ /dev/null @@ -1,54 +0,0 @@ -#![deny(rust_2018_idioms)] - -//! A library for formatting of text or programming code snippets. -//! -//! It's primary purpose is to build an ASCII-graphical representation of the snippet -//! with annotations. -//! -//! # Example -//! -//! ```text -//! error[E0308]: mismatched types -//! --> src/format.rs:52:1 -//! | -//! 51 | ) -> Option { -//! | -------------- expected `Option` because of return type -//! 52 | / for ann in annotations { -//! 53 | | match (ann.range.0, ann.range.1) { -//! 54 | | (None, None) => continue, -//! 55 | | (Some(start), Some(end)) if start > end_index => continue, -//! ... | -//! 71 | | } -//! 72 | | } -//! | |_____^ expected enum `std::option::Option`, found () -//! ``` -//! -//! The crate uses a three stage process with two conversions between states: -//! -//! ```text -//! Snippet --> DisplayList --> String -//! ``` -//! -//! The input type - [Snippet](self::snippet) is a structure designed -//! to align with likely output from any parser whose code snippet is to be -//! annotated. -//! -//! The middle structure - [DisplayList](self::display_list) is a -//! structure designed to store the snippet data converted into a vector -//! of lines containing semantic information about each line. -//! This structure is the easiest to manipulate and organize. -//! -//! Finally, [DisplayListFormatter](self::formatter::DisplayListFormatter) is -//! used to format the `DisplayList` using a `Stylesheet` into a final `String` output. -//! -//! A user of the crate may choose to provide their own equivalent of the input -//! structure with an `Into` trait. -//! -//! A user of the crate may also choose to provide their own formatter logic, -//! to convert a `DisplayList` into a `String`, or just a `Stylesheet` to -//! use the crate's formatting logic, but with a custom stylesheet. - -pub mod display_list; -pub mod formatter; -pub mod snippet; -pub mod stylesheets; diff --git a/vendor/annotate-snippets-0.8.0/src/snippet.rs b/vendor/annotate-snippets-0.8.0/src/snippet.rs deleted file mode 100644 index bc7ba0099..000000000 --- a/vendor/annotate-snippets-0.8.0/src/snippet.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! Structures used as an input for the library. -//! -//! Example: -//! -//! ``` -//! use annotate_snippets::snippet::*; -//! -//! Snippet { -//! title: Some(Annotation { -//! label: Some("mismatched types"), -//! id: None, -//! annotation_type: AnnotationType::Error, -//! }), -//! footer: vec![], -//! slices: vec![ -//! Slice { -//! source: "Foo", -//! line_start: 51, -//! origin: Some("src/format.rs"), -//! fold: false, -//! annotations: vec![], -//! }, -//! Slice { -//! source: "Faa", -//! line_start: 129, -//! origin: Some("src/display.rs"), -//! fold: false, -//! annotations: vec![], -//! }, -//! ], -//! opt: Default::default(), -//! }; -//! ``` -use crate::display_list::FormatOptions; - -/// Primary structure provided for formatting -#[derive(Debug, Default)] -pub struct Snippet<'a> { - pub title: Option>, - pub footer: Vec>, - pub slices: Vec>, - pub opt: FormatOptions, -} - -/// Structure containing the slice of text to be annotated and -/// basic information about the location of the slice. -/// -/// One `Slice` is meant to represent a single, continuous, -/// slice of source code that you want to annotate. -#[derive(Debug)] -pub struct Slice<'a> { - pub source: &'a str, - pub line_start: usize, - pub origin: Option<&'a str>, - pub annotations: Vec>, - /// If set explicitly to `true`, the snippet will fold - /// parts of the slice that don't contain any annotations. - pub fold: bool, -} - -/// Types of annotations. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum AnnotationType { - /// Error annotations are displayed using red color and "^" character. - Error, - /// Warning annotations are displayed using blue color and "-" character. - Warning, - Info, - Note, - Help, -} - -/// An annotation for a `Slice`. -#[derive(Debug)] -pub struct SourceAnnotation<'a> { - pub range: (usize, usize), - pub label: &'a str, - pub annotation_type: AnnotationType, -} - -/// An annotation for a `Snippet`. -#[derive(Debug)] -pub struct Annotation<'a> { - /// Identifier of the annotation. Usually error code like "E0308". - pub id: Option<&'a str>, - pub label: Option<&'a str>, - pub annotation_type: AnnotationType, -} diff --git a/vendor/annotate-snippets-0.8.0/src/stylesheets/color.rs b/vendor/annotate-snippets-0.8.0/src/stylesheets/color.rs deleted file mode 100644 index 024dd06f6..000000000 --- a/vendor/annotate-snippets-0.8.0/src/stylesheets/color.rs +++ /dev/null @@ -1,50 +0,0 @@ -use std::fmt::{self, Display}; - -use yansi_term::{Color::Fixed, Style as AnsiTermStyle}; - -use crate::formatter::style::{Style, StyleClass, Stylesheet}; - -struct AnsiTermStyleWrapper { - style: AnsiTermStyle, -} - -impl Style for AnsiTermStyleWrapper { - fn paint(&self, text: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.style.paint(text).fmt(f) - } - - fn paint_fn<'a>( - &self, - c: Box) -> fmt::Result + 'a>, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - self.style.paint_fn(c).fmt(f) - } - - fn bold(&self) -> Box { - Box::new(AnsiTermStyleWrapper { style: self.style }) - } -} - -pub struct AnsiTermStylesheet; - -impl Stylesheet for AnsiTermStylesheet { - fn get_style(&self, class: StyleClass) -> Box { - let ansi_term_style = match class { - StyleClass::Error => Fixed(9).bold(), - StyleClass::Warning => Fixed(11).bold(), - StyleClass::Info => Fixed(12).bold(), - StyleClass::Note => AnsiTermStyle::new().bold(), - StyleClass::Help => Fixed(14).bold(), - - StyleClass::LineNo => Fixed(12).bold(), - - StyleClass::Emphasis => AnsiTermStyle::new().bold(), - - StyleClass::None => AnsiTermStyle::new(), - }; - Box::new(AnsiTermStyleWrapper { - style: ansi_term_style, - }) - } -} diff --git a/vendor/annotate-snippets-0.8.0/src/stylesheets/mod.rs b/vendor/annotate-snippets-0.8.0/src/stylesheets/mod.rs deleted file mode 100644 index 49f6ea04b..000000000 --- a/vendor/annotate-snippets-0.8.0/src/stylesheets/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! List of stylesheets that can be used by the `DisplayListFormatter`. -//! -//! The list depends on what optional dependencies the crate has been -//! compiled with. -//! -//! By default the `no_color` is available. If the crate gets compiled -//! with `ansi_term`, the `color` stylesheet is added. - -#[cfg(feature = "color")] -pub mod color; -pub mod no_color; diff --git a/vendor/annotate-snippets-0.8.0/src/stylesheets/no_color.rs b/vendor/annotate-snippets-0.8.0/src/stylesheets/no_color.rs deleted file mode 100644 index 21cb26955..000000000 --- a/vendor/annotate-snippets-0.8.0/src/stylesheets/no_color.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::fmt; - -use crate::formatter::style::{Style, StyleClass, Stylesheet}; - -pub struct NoOpStyle {} - -impl Style for NoOpStyle { - fn paint(&self, text: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(text) - } - - fn paint_fn<'a>( - &self, - c: Box) -> fmt::Result + 'a>, - f: &mut fmt::Formatter<'_>, - ) -> fmt::Result { - c(f) - } - - fn bold(&self) -> Box { - Box::new(NoOpStyle {}) - } -} - -pub struct NoColorStylesheet; - -impl Stylesheet for NoColorStylesheet { - fn get_style(&self, _class: StyleClass) -> Box { - Box::new(NoOpStyle {}) - } -} diff --git a/vendor/annotate-snippets-0.8.0/tests/diff/mod.rs b/vendor/annotate-snippets-0.8.0/tests/diff/mod.rs deleted file mode 100644 index 576c6c4d6..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/diff/mod.rs +++ /dev/null @@ -1,43 +0,0 @@ -use difference::{Changeset, Difference}; -use yansi_term::Color::{Black, Green, Red}; - -pub fn get_diff(left: &str, right: &str) -> String { - let mut output = String::new(); - - let Changeset { diffs, .. } = Changeset::new(left, right, "\n"); - - for i in 0..diffs.len() { - match diffs[i] { - Difference::Same(ref x) => { - output += &format!(" {}\n", x); - } - Difference::Add(ref x) => { - match diffs[i - 1] { - Difference::Rem(ref y) => { - output += &format!("{}", Green.paint("+")); - let Changeset { diffs, .. } = Changeset::new(y, x, " "); - for c in diffs { - match c { - Difference::Same(ref z) => { - output += &format!("{} ", Green.paint(z.as_str())); - } - Difference::Add(ref z) => { - output += &format!("{} ", Black.on(Green).paint(z.as_str())); - } - _ => (), - } - } - output += "\n"; - } - _ => { - output += &format!("+{}\n", Green.paint(x.as_str())); - } - }; - } - Difference::Rem(ref x) => { - output += &format!("-{}\n", Red.paint(x.as_str())); - } - } - } - output -} diff --git a/vendor/annotate-snippets-0.8.0/tests/dl_from_snippet.rs b/vendor/annotate-snippets-0.8.0/tests/dl_from_snippet.rs deleted file mode 100644 index 2ed990261..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/dl_from_snippet.rs +++ /dev/null @@ -1,401 +0,0 @@ -use annotate_snippets::display_list::DisplayList; -use annotate_snippets::{display_list as dl, formatter::get_term_style, snippet}; - -#[test] -fn test_format_title() { - let input = snippet::Snippet { - title: Some(snippet::Annotation { - id: Some("E0001"), - label: Some("This is a title"), - annotation_type: snippet::AnnotationType::Error, - }), - footer: vec![], - slices: vec![], - opt: Default::default(), - }; - let output = dl::DisplayList { - body: vec![dl::DisplayLine::Raw(dl::DisplayRawLine::Annotation { - annotation: dl::Annotation { - annotation_type: dl::DisplayAnnotationType::Error, - id: Some("E0001"), - label: vec![dl::DisplayTextFragment { - content: "This is a title", - style: dl::DisplayTextStyle::Emphasis, - }], - }, - source_aligned: false, - continuation: false, - })], - stylesheet: get_term_style(input.opt.color), - anonymized_line_numbers: input.opt.anonymized_line_numbers, - }; - assert_eq!(dl::DisplayList::from(input), output); -} - -#[test] -fn test_format_slice() { - let line_1 = "This is line 1"; - let line_2 = "This is line 2"; - let source = vec![line_1, line_2].join("\n"); - let input = snippet::Snippet { - title: None, - footer: vec![], - slices: vec![snippet::Slice { - source: &source, - line_start: 5402, - origin: None, - annotations: vec![], - fold: false, - }], - opt: Default::default(), - }; - let output = dl::DisplayList { - body: vec![ - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Source { - lineno: Some(5402), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - text: line_1, - range: (0, line_1.len()), - }, - }, - dl::DisplayLine::Source { - lineno: Some(5403), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - range: (line_1.len() + 1, source.len()), - text: line_2, - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - ], - stylesheet: get_term_style(input.opt.color), - anonymized_line_numbers: input.opt.anonymized_line_numbers, - }; - assert_eq!(dl::DisplayList::from(input), output); -} - -#[test] -fn test_format_slices_continuation() { - let src_0 = "This is slice 1"; - let src_0_len = src_0.len(); - let src_1 = "This is slice 2"; - let src_1_len = src_1.len(); - let input = snippet::Snippet { - title: None, - footer: vec![], - slices: vec![ - snippet::Slice { - source: src_0, - line_start: 5402, - origin: Some("file1.rs"), - annotations: vec![], - fold: false, - }, - snippet::Slice { - source: src_1, - line_start: 2, - origin: Some("file2.rs"), - annotations: vec![], - fold: false, - }, - ], - opt: Default::default(), - }; - let output = dl::DisplayList { - body: vec![ - dl::DisplayLine::Raw(dl::DisplayRawLine::Origin { - path: "file1.rs", - pos: None, - header_type: dl::DisplayHeaderType::Initial, - }), - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Source { - lineno: Some(5402), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - text: src_0, - range: (0, src_0_len), - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Raw(dl::DisplayRawLine::Origin { - path: "file2.rs", - pos: None, - header_type: dl::DisplayHeaderType::Continuation, - }), - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Source { - lineno: Some(2), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - text: src_1, - range: (0, src_1_len), - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - ], - stylesheet: get_term_style(input.opt.color), - anonymized_line_numbers: input.opt.anonymized_line_numbers, - }; - assert_eq!(dl::DisplayList::from(input), output); -} - -#[test] -fn test_format_slice_annotation_standalone() { - let line_1 = "This is line 1"; - let line_2 = "This is line 2"; - let source = vec![line_1, line_2].join("\n"); - // In line 2 - let range = (22, 24); - let input = snippet::Snippet { - title: None, - footer: vec![], - slices: vec![snippet::Slice { - source: &source, - line_start: 5402, - origin: None, - annotations: vec![snippet::SourceAnnotation { - range, - label: "Test annotation", - annotation_type: snippet::AnnotationType::Info, - }], - fold: false, - }], - opt: Default::default(), - }; - let output = dl::DisplayList { - body: vec![ - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Source { - lineno: Some(5402), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - range: (0, line_1.len()), - text: line_1, - }, - }, - dl::DisplayLine::Source { - lineno: Some(5403), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - range: (line_1.len() + 1, source.len()), - text: line_2, - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Annotation { - annotation: dl::Annotation { - annotation_type: dl::DisplayAnnotationType::Info, - id: None, - label: vec![dl::DisplayTextFragment { - content: "Test annotation", - style: dl::DisplayTextStyle::Regular, - }], - }, - range: (range.0 - (line_1.len() + 1), range.1 - (line_1.len() + 1)), - annotation_type: dl::DisplayAnnotationType::Info, - annotation_part: dl::DisplayAnnotationPart::Standalone, - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - ], - stylesheet: get_term_style(input.opt.color), - anonymized_line_numbers: input.opt.anonymized_line_numbers, - }; - assert_eq!(dl::DisplayList::from(input), output); -} - -#[test] -fn test_format_label() { - let input = snippet::Snippet { - title: None, - footer: vec![snippet::Annotation { - id: None, - label: Some("This __is__ a title"), - annotation_type: snippet::AnnotationType::Error, - }], - slices: vec![], - opt: Default::default(), - }; - let output = dl::DisplayList { - body: vec![dl::DisplayLine::Raw(dl::DisplayRawLine::Annotation { - annotation: dl::Annotation { - annotation_type: dl::DisplayAnnotationType::Error, - id: None, - label: vec![ - dl::DisplayTextFragment { - content: "This ", - style: dl::DisplayTextStyle::Regular, - }, - dl::DisplayTextFragment { - content: "is", - style: dl::DisplayTextStyle::Emphasis, - }, - dl::DisplayTextFragment { - content: " a title", - style: dl::DisplayTextStyle::Regular, - }, - ], - }, - source_aligned: true, - continuation: false, - })], - stylesheet: get_term_style(input.opt.color), - anonymized_line_numbers: input.opt.anonymized_line_numbers, - }; - assert_eq!(dl::DisplayList::from(input), output); -} - -#[test] -#[should_panic] -fn test_i26() { - let source = "short"; - let label = "label"; - let input = snippet::Snippet { - title: None, - footer: vec![], - slices: vec![snippet::Slice { - annotations: vec![snippet::SourceAnnotation { - range: (0, source.len() + 1), - label, - annotation_type: snippet::AnnotationType::Error, - }], - source, - line_start: 0, - origin: None, - fold: false, - }], - opt: Default::default(), - }; - - let _ = dl::DisplayList::from(input); -} - -#[test] -fn test_i_29() { - let snippets = snippet::Snippet { - title: Some(snippet::Annotation { - id: None, - label: Some("oops"), - annotation_type: snippet::AnnotationType::Error, - }), - footer: vec![], - slices: vec![snippet::Slice { - source: "First line\r\nSecond oops line", - line_start: 1, - origin: Some(""), - annotations: vec![snippet::SourceAnnotation { - range: (19, 23), - label: "oops", - annotation_type: snippet::AnnotationType::Error, - }], - fold: true, - }], - opt: Default::default(), - }; - - let expected = DisplayList { - body: vec![ - dl::DisplayLine::Raw(dl::DisplayRawLine::Annotation { - annotation: dl::Annotation { - annotation_type: dl::DisplayAnnotationType::Error, - id: None, - label: vec![dl::DisplayTextFragment { - content: "oops", - style: dl::DisplayTextStyle::Emphasis, - }], - }, - source_aligned: false, - continuation: false, - }), - dl::DisplayLine::Raw(dl::DisplayRawLine::Origin { - path: "", - pos: Some((2, 8)), - header_type: dl::DisplayHeaderType::Initial, - }), - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - dl::DisplayLine::Source { - lineno: Some(1), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - text: "First line", - range: (0, 10), - }, - }, - dl::DisplayLine::Source { - lineno: Some(2), - inline_marks: vec![], - line: dl::DisplaySourceLine::Content { - text: "Second oops line", - range: (12, 28), - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Annotation { - annotation: dl::Annotation { - annotation_type: dl::DisplayAnnotationType::None, - id: None, - label: vec![dl::DisplayTextFragment { - content: "oops", - style: dl::DisplayTextStyle::Regular, - }], - }, - range: (7, 11), - annotation_type: dl::DisplayAnnotationType::Error, - annotation_part: dl::DisplayAnnotationPart::Standalone, - }, - }, - dl::DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: dl::DisplaySourceLine::Empty, - }, - ], - stylesheet: get_term_style(false), - anonymized_line_numbers: false, - }; - - assert_eq!(DisplayList::from(snippets), expected); -} diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.toml b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.toml deleted file mode 100644 index bdb577f46..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.toml +++ /dev/null @@ -1,40 +0,0 @@ -[[slices]] -source = """ -) -> Option { - for ann in annotations { - match (ann.range.0, ann.range.1) { - (None, None) => continue, - (Some(start), Some(end)) if start > end_index || end < start_index => continue, - (Some(start), Some(end)) if start >= start_index && end <= end_index => { - let label = if let Some(ref label) = ann.label { - format!(" {}", label) - } else { - String::from("") - }; - - return Some(format!( - "{}{}{}", - " ".repeat(start - start_index), - "^".repeat(end - start), - label - )); - } - _ => continue, - } - } -""" -line_start = 51 -origin = "src/format.rs" -fold = true -[[slices.annotations]] -label = "expected `std::option::Option` because of return type" -annotation_type = "Warning" -range = [5, 19] -[[slices.annotations]] -label = "expected enum `std::option::Option`, found ()" -annotation_type = "Error" -range = [22, 765] -[title] -label = "mismatched types" -id = "E0308" -annotation_type = "Error" diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.txt b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.txt deleted file mode 100644 index bacdec10d..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation.txt +++ /dev/null @@ -1,14 +0,0 @@ -error[E0308]: mismatched types - --> src/format.rs:51:6 - | -51 | ) -> Option { - | -------------- expected `std::option::Option` because of return type -52 | / for ann in annotations { -53 | | match (ann.range.0, ann.range.1) { -54 | | (None, None) => continue, -55 | | (Some(start), Some(end)) if start > end_index || end < start_index => continue, -... | -71 | | } -72 | | } - | |_____^ expected enum `std::option::Option`, found () - | diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.toml b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.toml deleted file mode 100644 index 6ec0b1fe8..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.toml +++ /dev/null @@ -1,18 +0,0 @@ -[[slices]] -source = """ - if let DisplayLine::Source { - ref mut inline_marks, - } = body[body_idx] -""" -line_start = 139 -origin = "src/display_list.rs" -fold = false -[[slices.annotations]] -label = "missing fields `lineno`, `content`" -annotation_type = "Error" -range = [31, 127] - -[title] -label = "pattern does not mention fields `lineno`, `content`" -id = "E0027" -annotation_type = "Error" diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.txt b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.txt deleted file mode 100644 index 8a00bfa20..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation2.txt +++ /dev/null @@ -1,9 +0,0 @@ -error[E0027]: pattern does not mention fields `lineno`, `content` - --> src/display_list.rs:139:32 - | -139 | if let DisplayLine::Source { - | ________________________________^ -140 | | ref mut inline_marks, -141 | | } = body[body_idx] - | |_________________________^ missing fields `lineno`, `content` - | diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.toml b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.toml deleted file mode 100644 index 21bbcd857..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.toml +++ /dev/null @@ -1,18 +0,0 @@ -[[slices]] -source = """ -This is an exampl -e of an edge case of an annotation overflowing -to exactly one character on next line. -""" -line_start = 26 -origin = "foo.txt" -fold = false -[[slices.annotations]] -label = "this should not be on separate lines" -annotation_type = "Error" -range = [11, 18] - -[title] -label = "spacing error found" -id = "E####" -annotation_type = "Error" diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.txt b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.txt deleted file mode 100644 index 12e174c56..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiline_annotation3.txt +++ /dev/null @@ -1,9 +0,0 @@ -error[E####]: spacing error found - --> foo.txt:26:12 - | -26 | This is an exampl - | ____________^ -27 | | e of an edge case of an annotation overflowing - | |_^ this should not be on separate lines -28 | to exactly one character on next line. - | \ No newline at end of file diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.toml b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.toml deleted file mode 100644 index 84efc5f17..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.toml +++ /dev/null @@ -1,25 +0,0 @@ -[[slices]] -source = """ -fn add_title_line(result: &mut Vec, main_annotation: Option<&Annotation>) { - if let Some(annotation) = main_annotation { - result.push(format_title_line( - &annotation.annotation_type, - None, - &annotation.label, - )); - } -} -""" -line_start = 96 -[[slices.annotations]] -label = "Variable defined here" -annotation_type = "Error" -range = [100, 110] -[[slices.annotations]] -label = "Referenced here" -annotation_type = "Error" -range = [184, 194] -[[slices.annotations]] -label = "Referenced again here" -annotation_type = "Error" -range = [243, 253] diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.txt b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.txt deleted file mode 100644 index 26c677f7e..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/multiple_annotations.txt +++ /dev/null @@ -1,14 +0,0 @@ - | - 96 | fn add_title_line(result: &mut Vec, main_annotation: Option<&Annotation>) { - 97 | if let Some(annotation) = main_annotation { - | ^^^^^^^^^^ Variable defined here - 98 | result.push(format_title_line( - 99 | &annotation.annotation_type, - | ^^^^^^^^^^ Referenced here -100 | None, -101 | &annotation.label, - | ^^^^^^^^^^ Referenced again here -102 | )); -103 | } -104 | } - | diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.toml b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.toml deleted file mode 100644 index 6c38674ac..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.toml +++ /dev/null @@ -1,18 +0,0 @@ -[[slices]] -source = """ - }) - - for line in &self.body {""" -line_start = 169 -origin = "src/format_color.rs" -[[slices.annotations]] -label = "unexpected token" -annotation_type = "Error" -range = [20, 23] -[[slices.annotations]] -label = "expected one of `.`, `;`, `?`, or an operator here" -annotation_type = "Warning" -range = [10, 11] -[title] -label = "expected one of `.`, `;`, `?`, or an operator, found `for`" -annotation_type = "Error" diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.txt b/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.txt deleted file mode 100644 index 752cc890f..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures/no-color/simple.txt +++ /dev/null @@ -1,9 +0,0 @@ -error: expected one of `.`, `;`, `?`, or an operator, found `for` - --> src/format_color.rs:171:9 - | -169 | }) - | - expected one of `.`, `;`, `?`, or an operator here -170 | -171 | for line in &self.body { - | ^^^ unexpected token - | diff --git a/vendor/annotate-snippets-0.8.0/tests/fixtures_test.rs b/vendor/annotate-snippets-0.8.0/tests/fixtures_test.rs deleted file mode 100644 index e471521f2..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/fixtures_test.rs +++ /dev/null @@ -1,45 +0,0 @@ -mod diff; -mod snippet; - -use crate::snippet::SnippetDef; -use annotate_snippets::{display_list::DisplayList, snippet::Snippet}; -use glob::glob; -use std::{error::Error, fs::File, io, io::prelude::*}; - -fn read_file(path: &str) -> Result { - let mut f = File::open(path)?; - let mut s = String::new(); - (f.read_to_string(&mut s))?; - Ok(s.trim_end().to_string()) -} - -fn read_fixture<'de>(src: &'de str) -> Result, Box> { - Ok(toml::from_str(src).map(|a: SnippetDef| a.into())?) -} - -#[test] -fn test_fixtures() { - for entry in glob("./tests/fixtures/no-color/**/*.toml").expect("Failed to read glob pattern") { - let p = entry.expect("Error while getting an entry"); - - let path_in = p.to_str().expect("Can't print path"); - let path_out = path_in.replace(".toml", ".txt"); - - let src = read_file(&path_in).expect("Failed to read file"); - let snippet = read_fixture(&src).expect("Failed to read file"); - let expected_out = read_file(&path_out).expect("Failed to read file"); - - let dl = DisplayList::from(snippet); - let actual_out = dl.to_string(); - println!("{}", expected_out); - println!("{}", actual_out.trim_end()); - - assert_eq!( - expected_out, - actual_out.trim_end(), - "\n\n\nWhile parsing: {}\nThe diff is:\n\n\n{}\n\n\n", - path_in, - diff::get_diff(expected_out.as_str(), actual_out.as_str()) - ); - } -} diff --git a/vendor/annotate-snippets-0.8.0/tests/formatter.rs b/vendor/annotate-snippets-0.8.0/tests/formatter.rs deleted file mode 100644 index 5c7211d1e..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/formatter.rs +++ /dev/null @@ -1,552 +0,0 @@ -use annotate_snippets::display_list::*; -use annotate_snippets::snippet::{self, Snippet}; - -#[test] -fn test_source_empty() { - let dl = DisplayList::from(vec![DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Empty, - }]); - - assert_eq!(dl.to_string(), " |"); -} - -#[test] -fn test_source_content() { - let dl = DisplayList::from(vec![ - DisplayLine::Source { - lineno: Some(56), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "This is an example", - range: (0, 19), - }, - }, - DisplayLine::Source { - lineno: Some(57), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "of content lines", - range: (0, 19), - }, - }, - ]); - - assert_eq!( - dl.to_string(), - "56 | This is an example\n57 | of content lines" - ); -} - -#[test] -fn test_source_annotation_standalone_singleline() { - let dl = DisplayList::from(vec![DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::None, - id: None, - label: vec![DisplayTextFragment { - content: "Example string", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Error, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }]); - - assert_eq!(dl.to_string(), " | ^^^^^ Example string"); -} - -#[test] -fn test_source_annotation_standalone_multiline() { - let dl = DisplayList::from(vec![ - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Help, - id: None, - label: vec![DisplayTextFragment { - content: "Example string", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Warning, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Help, - id: None, - label: vec![DisplayTextFragment { - content: "Second line", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Warning, - annotation_part: DisplayAnnotationPart::LabelContinuation, - }, - }, - ]); - - assert_eq!( - dl.to_string(), - " | ----- help: Example string\n | Second line" - ); -} - -#[test] -fn test_source_annotation_standalone_multi_annotation() { - let dl = DisplayList::from(vec![ - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Info, - id: None, - label: vec![DisplayTextFragment { - content: "Example string", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Note, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Info, - id: None, - label: vec![DisplayTextFragment { - content: "Second line", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Note, - annotation_part: DisplayAnnotationPart::LabelContinuation, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: None, - label: vec![DisplayTextFragment { - content: "This is a note", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Note, - annotation_part: DisplayAnnotationPart::Consequitive, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: None, - label: vec![DisplayTextFragment { - content: "Second line of the warning", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Note, - annotation_part: DisplayAnnotationPart::LabelContinuation, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Info, - id: None, - label: vec![DisplayTextFragment { - content: "This is an info", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Info, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 5), - annotation: Annotation { - annotation_type: DisplayAnnotationType::Help, - id: None, - label: vec![DisplayTextFragment { - content: "This is help", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::Help, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Annotation { - range: (0, 0), - annotation: Annotation { - annotation_type: DisplayAnnotationType::None, - id: None, - label: vec![DisplayTextFragment { - content: "This is an annotation of type none", - style: DisplayTextStyle::Regular, - }], - }, - annotation_type: DisplayAnnotationType::None, - annotation_part: DisplayAnnotationPart::Standalone, - }, - }, - ]); - - assert_eq!(dl.to_string(), " | ----- info: Example string\n | Second line\n | warning: This is a note\n | Second line of the warning\n | ----- info: This is an info\n | ----- help: This is help\n | This is an annotation of type none"); -} - -#[test] -fn test_fold_line() { - let dl = DisplayList::from(vec![ - DisplayLine::Source { - lineno: Some(5), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "This is line 5", - range: (0, 19), - }, - }, - DisplayLine::Fold { - inline_marks: vec![], - }, - DisplayLine::Source { - lineno: Some(10021), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "... and now we're at line 10021", - range: (0, 19), - }, - }, - ]); - - assert_eq!( - dl.to_string(), - " 5 | This is line 5\n...\n10021 | ... and now we're at line 10021" - ); -} - -#[test] -fn test_raw_origin_initial_nopos() { - let dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Origin { - path: "src/test.rs", - pos: None, - header_type: DisplayHeaderType::Initial, - })]); - - assert_eq!(dl.to_string(), "--> src/test.rs"); -} - -#[test] -fn test_raw_origin_initial_pos() { - let dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Origin { - path: "src/test.rs", - pos: Some((23, 15)), - header_type: DisplayHeaderType::Initial, - })]); - - assert_eq!(dl.to_string(), "--> src/test.rs:23:15"); -} - -#[test] -fn test_raw_origin_continuation() { - let dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Origin { - path: "src/test.rs", - pos: Some((23, 15)), - header_type: DisplayHeaderType::Continuation, - })]); - - assert_eq!(dl.to_string(), "::: src/test.rs:23:15"); -} - -#[test] -fn test_raw_annotation_unaligned() { - let dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Error, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "This is an error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: false, - })]); - - assert_eq!(dl.to_string(), "error[E0001]: This is an error"); -} - -#[test] -fn test_raw_annotation_unaligned_multiline() { - let dl = DisplayList::from(vec![ - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "This is an error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: false, - }), - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "Second line of the error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: true, - }), - ]); - - assert_eq!( - dl.to_string(), - "warning[E0001]: This is an error\n Second line of the error" - ); -} - -#[test] -fn test_raw_annotation_aligned() { - let dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Error, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "This is an error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: true, - continuation: false, - })]); - - assert_eq!(dl.to_string(), " = error[E0001]: This is an error"); -} - -#[test] -fn test_raw_annotation_aligned_multiline() { - let dl = DisplayList::from(vec![ - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "This is an error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: true, - continuation: false, - }), - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Warning, - id: Some("E0001"), - label: vec![DisplayTextFragment { - content: "Second line of the error", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: true, - continuation: true, - }), - ]); - - assert_eq!( - dl.to_string(), - " = warning[E0001]: This is an error\n Second line of the error" - ); -} - -#[test] -fn test_different_annotation_types() { - let dl = DisplayList::from(vec![ - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::Note, - id: None, - label: vec![DisplayTextFragment { - content: "This is a note", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: false, - }), - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::None, - id: None, - label: vec![DisplayTextFragment { - content: "This is just a string", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: false, - }), - DisplayLine::Raw(DisplayRawLine::Annotation { - annotation: Annotation { - annotation_type: DisplayAnnotationType::None, - id: None, - label: vec![DisplayTextFragment { - content: "Second line of none type annotation", - style: DisplayTextStyle::Regular, - }], - }, - source_aligned: false, - continuation: true, - }), - ]); - - assert_eq!( - dl.to_string(), - "note: This is a note\nThis is just a string\n Second line of none type annotation", - ); -} - -#[test] -fn test_inline_marks_empty_line() { - let dl = DisplayList::from(vec![DisplayLine::Source { - lineno: None, - inline_marks: vec![DisplayMark { - mark_type: DisplayMarkType::AnnotationThrough, - annotation_type: DisplayAnnotationType::Error, - }], - line: DisplaySourceLine::Empty, - }]); - - assert_eq!(dl.to_string(), " | |",); -} - -#[test] -fn test_anon_lines() { - let mut dl = DisplayList::from(vec![ - DisplayLine::Source { - lineno: Some(56), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "This is an example", - range: (0, 19), - }, - }, - DisplayLine::Source { - lineno: Some(57), - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "of content lines", - range: (0, 19), - }, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Empty, - }, - DisplayLine::Source { - lineno: None, - inline_marks: vec![], - line: DisplaySourceLine::Content { - text: "abc", - range: (0, 19), - }, - }, - ]); - - dl.anonymized_line_numbers = true; - assert_eq!( - dl.to_string(), - "LL | This is an example\nLL | of content lines\n |\n | abc" - ); -} - -#[test] -fn test_raw_origin_initial_pos_anon_lines() { - let mut dl = DisplayList::from(vec![DisplayLine::Raw(DisplayRawLine::Origin { - path: "src/test.rs", - pos: Some((23, 15)), - header_type: DisplayHeaderType::Initial, - })]); - - // Using anonymized_line_numbers should not affect the inital position - dl.anonymized_line_numbers = true; - assert_eq!(dl.to_string(), "--> src/test.rs:23:15"); -} - -#[test] -fn test_i_29() { - let snippets = Snippet { - title: Some(snippet::Annotation { - id: None, - label: Some("oops"), - annotation_type: snippet::AnnotationType::Error, - }), - footer: vec![], - slices: vec![snippet::Slice { - source: "First line\r\nSecond oops line", - line_start: 1, - origin: Some(""), - annotations: vec![snippet::SourceAnnotation { - range: (19, 23), - label: "oops", - annotation_type: snippet::AnnotationType::Error, - }], - fold: true, - }], - opt: Default::default(), - }; - let expected = r#"error: oops - --> :2:8 - | -1 | First line -2 | Second oops line - | ^^^^ oops - |"#; - - assert_eq!(DisplayList::from(snippets).to_string(), expected); -} diff --git a/vendor/annotate-snippets-0.8.0/tests/snippet/mod.rs b/vendor/annotate-snippets-0.8.0/tests/snippet/mod.rs deleted file mode 100644 index c3348741a..000000000 --- a/vendor/annotate-snippets-0.8.0/tests/snippet/mod.rs +++ /dev/null @@ -1,167 +0,0 @@ -use serde::{Deserialize, Deserializer, Serialize}; - -use annotate_snippets::{ - display_list::FormatOptions, - snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}, -}; - -#[derive(Deserialize)] -pub struct SnippetDef<'a> { - #[serde(deserialize_with = "deserialize_annotation")] - #[serde(default)] - #[serde(borrow)] - pub title: Option>, - #[serde(deserialize_with = "deserialize_annotations")] - #[serde(default)] - #[serde(borrow)] - pub footer: Vec>, - #[serde(deserialize_with = "deserialize_opt")] - #[serde(default)] - pub opt: FormatOptions, - #[serde(deserialize_with = "deserialize_slices")] - #[serde(borrow)] - pub slices: Vec>, -} - -impl<'a> Into> for SnippetDef<'a> { - fn into(self) -> Snippet<'a> { - let SnippetDef { - title, - footer, - opt, - slices, - } = self; - Snippet { - title, - footer, - slices, - opt, - } - } -} - -fn deserialize_opt<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - struct Wrapper(#[serde(with = "FormatOptionsDef")] FormatOptions); - - Wrapper::deserialize(deserializer).map(|w| w.0) -} - -#[derive(Deserialize)] -#[serde(remote = "FormatOptions")] -pub struct FormatOptionsDef { - pub color: bool, - pub anonymized_line_numbers: bool, -} - -fn deserialize_slices<'de, D>(deserializer: D) -> Result>, D::Error> -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - struct Wrapper<'a>( - #[serde(with = "SliceDef")] - #[serde(borrow)] - Slice<'a>, - ); - - let v = Vec::deserialize(deserializer)?; - Ok(v.into_iter().map(|Wrapper(a)| a).collect()) -} - -fn deserialize_annotation<'de, D>(deserializer: D) -> Result>, D::Error> -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - struct Wrapper<'a>( - #[serde(with = "AnnotationDef")] - #[serde(borrow)] - Annotation<'a>, - ); - - Option::::deserialize(deserializer) - .map(|opt_wrapped: Option| opt_wrapped.map(|wrapped: Wrapper| wrapped.0)) -} - -fn deserialize_annotations<'de, D>(deserializer: D) -> Result>, D::Error> -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - struct Wrapper<'a>( - #[serde(with = "AnnotationDef")] - #[serde(borrow)] - Annotation<'a>, - ); - - let v = Vec::deserialize(deserializer)?; - Ok(v.into_iter().map(|Wrapper(a)| a).collect()) -} - -#[derive(Deserialize)] -#[serde(remote = "Slice")] -pub struct SliceDef<'a> { - #[serde(borrow)] - pub source: &'a str, - pub line_start: usize, - #[serde(borrow)] - pub origin: Option<&'a str>, - #[serde(deserialize_with = "deserialize_source_annotations")] - #[serde(borrow)] - pub annotations: Vec>, - #[serde(default)] - pub fold: bool, -} - -fn deserialize_source_annotations<'de, D>( - deserializer: D, -) -> Result>, D::Error> -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - struct Wrapper<'a>( - #[serde(with = "SourceAnnotationDef")] - #[serde(borrow)] - SourceAnnotation<'a>, - ); - - let v = Vec::deserialize(deserializer)?; - Ok(v.into_iter().map(|Wrapper(a)| a).collect()) -} - -#[derive(Serialize, Deserialize)] -#[serde(remote = "SourceAnnotation")] -pub struct SourceAnnotationDef<'a> { - pub range: (usize, usize), - #[serde(borrow)] - pub label: &'a str, - #[serde(with = "AnnotationTypeDef")] - pub annotation_type: AnnotationType, -} - -#[derive(Serialize, Deserialize)] -#[serde(remote = "Annotation")] -pub struct AnnotationDef<'a> { - #[serde(borrow)] - pub id: Option<&'a str>, - #[serde(borrow)] - pub label: Option<&'a str>, - #[serde(with = "AnnotationTypeDef")] - pub annotation_type: AnnotationType, -} - -#[allow(dead_code)] -#[derive(Serialize, Deserialize)] -#[serde(remote = "AnnotationType")] -enum AnnotationTypeDef { - Error, - Warning, - Info, - Note, - Help, -} diff --git a/vendor/anyhow/.cargo-checksum.json b/vendor/anyhow/.cargo-checksum.json index 7b37c5570..5bbee7b7b 100644 --- a/vendor/anyhow/.cargo-checksum.json +++ b/vendor/anyhow/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"b83515ea98aa6ba603307c3629b86b0ad85e3017df8fe9f444c4bc8e0fc18c03","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"4bd4d352368ac0f5447031d82454490f6ac0c80d2fa4cb64ba0c23c614670d49","build.rs":"f82a81a4c16e3b68140e10c3d3a9ee54af48c53133a1d894fbb92190f09f0550","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/backtrace.rs":"5a60bd1fe1717c044c7ab34c062ce6651c0cb08596a5878e391c2755ecac07f9","src/chain.rs":"6edefc5f3c7d69683095862e54e3bb56faba5b3387bf2eeaed429da090007a0a","src/context.rs":"559478ae785ce913523aa21358cc1561ef4b0b95c5c87675a77890364c0162fe","src/ensure.rs":"ba404f1708d41a267f8678858aebefadc8fae717bd5533e5ebb47e219aa44f7e","src/error.rs":"6c5b1357eedd6f2be1fdaee1be645a33e68c945c481d6ff20b98c8fdedea687a","src/fmt.rs":"c2d4aad6ce20625a70a7c091e3087b6a2c19a4a87c7a12edb4c98978307245ea","src/kind.rs":"b21b15dbee77d50abe88684a9571b39659076465dd4b1956f366af8fdd26e95a","src/lib.rs":"b340e18f5666d53289ce3428054e9789009cf60ea3e9ff717b3a4028fbaba6c2","src/macros.rs":"4ff9a40d7ff06cc02b387f40d6ae296990493cd7f9755880c621c47e7e845f07","src/ptr.rs":"f4e28bc9feba1e84160ca9d185008a51b5d72e168e6546f3e942f4258c361e19","src/wrapper.rs":"1229beca67dbd95ca77c9ecce282272acc55276c267c58cb73a75388b4693dda","tests/common/mod.rs":"f9088c2d7afafa64ff730b629272045b776bfafc2f5957508242da630635f2e1","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/drop/mod.rs":"08c3e553c1cc0d2dbd936fc45f4b5b1105057186affd6865e8d261e05f0f0646","tests/test_autotrait.rs":"981e792db353be2f14c7a1cabe43b5f1329c168cb7679077cc2be786a0920d48","tests/test_backtrace.rs":"0e50edbb33b6bd07ba89ff3db72fb7c688ba2a4371fccdbbb20309ab02948b6a","tests/test_boxed.rs":"6b26db0e2eb72afe9af7352ea820837aab90f8d486294616dd5dc34c1b94038c","tests/test_chain.rs":"d5e90e3eba58abc60d241d3aade39e0b8d4006d9a14f3cf015d3d925160b5812","tests/test_context.rs":"8409c53b328562c11e822bd6c3cd17e0d4d50b9bbb8fc3617333fd77303a6a33","tests/test_convert.rs":"7e7a8b4772a427a911014ac4d1083f9519000e786177f898808980dd9bdfde61","tests/test_downcast.rs":"797e69a72d125758c4c4897e5dc776d549d52cc9a6a633e0a33193f588a62b88","tests/test_ensure.rs":"bd793da08a4d01b8211646d82bec73468e54f6caf5f520617519a12cbb6659b9","tests/test_ffi.rs":"d0cb4c1d6d9154090982dee72ae3ebe05a5981f976058c3250f1c9da5a45edef","tests/test_fmt.rs":"17572596f257aac9aa2ec4620e292ca6a954128b94772bb948399fab53832e70","tests/test_macros.rs":"11f05010bc9b16319884c1286444100e30cddc2ecd1ffe5e0fd3fee5ffb32683","tests/test_repr.rs":"dbb9b04ddbe1ab31eb5331ea69f05bb3a147299da2275a3d4dcc92947b5591b9","tests/test_source.rs":"b80723cf635a4f8c4df21891b34bfab9ed2b2aa407e7a2f826d24e334cd5f88e","tests/ui/chained-comparison.rs":"6504b03d95b5acc232a7f4defc9f343b2be6733bf475fa0992e8e6545b912bd4","tests/ui/chained-comparison.stderr":"7f1d0a8c251b0ede2d30b3087ec157fc660945c97a642c4a5acf5a14ec58de34","tests/ui/empty-ensure.rs":"ab5bf37c846a0d689f26ce9257a27228411ed64154f9c950f1602d88a355d94b","tests/ui/empty-ensure.stderr":"345102cbef47310f2f4066a669199873a627ca4f1fcb885505c6e17d1fc95e88","tests/ui/must-use.rs":"fb59860b43f673bf4a430a6036ba463e95028844d8dd4243cfe5ebc7f2be582f","tests/ui/must-use.stderr":"4dc15f52c3a186251c948b6a2955b777ed3c88e5da94b887f8ff945b3ecd8cee","tests/ui/no-impl.rs":"fab6cbf2f6ea510b86f567dfb3b7c31250a9fd71ae5d110dbb9188be569ec593","tests/ui/no-impl.stderr":"39d3234c0cbb6213a422485cd1bf64b0877d2b2ea3e168b099bc8a6c1e0d33df","tests/ui/temporary-value.rs":"4dcc96271b2403e6372cf4cfc813445e5ce4365fc6e156b6bc38274098499a70","tests/ui/temporary-value.stderr":"64e448b6759cf51d41b1360307a638452bbe53ffa706f93e4a503b712d7b89a8","tests/ui/wrong-interpolation.rs":"9c44d4674c2dccd27b9dedd03341346ec02d993b41793ee89b5755202e7e367e","tests/ui/wrong-interpolation.stderr":"301e60e2eb9401782c7dc0b3580613a4cb2aafd4cc8065734a630a62e1161aa5"},"package":"c794e162a5eff65c72ef524dfe393eb923c354e350bb78b9c7383df13f3bc142"} \ No newline at end of file +{"files":{"Cargo.toml":"5779c6bea2555cdabd4560de187ac5e3c88ff2df8172077397643edc51c6fcc3","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"4bd4d352368ac0f5447031d82454490f6ac0c80d2fa4cb64ba0c23c614670d49","build.rs":"88bf7100143c79c0af683da7f28deaac031c9b9b213a6426560dc089b0ba45aa","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/backtrace.rs":"5b4103a7d24d6f438a64b8cc0fafe28d55fc0ca090368174ce44d64e3940badd","src/chain.rs":"6edefc5f3c7d69683095862e54e3bb56faba5b3387bf2eeaed429da090007a0a","src/context.rs":"0bb1566aae147d393796dd6ede6ba329916e0a373b7cbc38335c3eeeb3d48b57","src/ensure.rs":"498bc9c7fb8b93168ed12f532cb97df6ccdda9ce25371586d7f5b1b1c98a14bf","src/error.rs":"e45d4dcfe64b1823b42fbf9bb260e6437987e8c2d51f92434db9d808b36e700a","src/fmt.rs":"c2d4aad6ce20625a70a7c091e3087b6a2c19a4a87c7a12edb4c98978307245ea","src/kind.rs":"332854c5eb07d44447c356a2e7dc585634b0da1ffbbfa81269c369deaefbc247","src/lib.rs":"82011e86fb9b41fe10ab2fde2b797b4858e697e7ead3a5f0d30b018357f1721d","src/macros.rs":"dd35f2ec2a0a25e4504fb04bcd42f6d0963bc0035aaaefc412f5ee1d78945fe1","src/ptr.rs":"f4e28bc9feba1e84160ca9d185008a51b5d72e168e6546f3e942f4258c361e19","src/wrapper.rs":"ff3ad72065a30cc32e9acb0614a30703c49c57b941a335c348b6439af684316b","tests/common/mod.rs":"f9088c2d7afafa64ff730b629272045b776bfafc2f5957508242da630635f2e1","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/drop/mod.rs":"08c3e553c1cc0d2dbd936fc45f4b5b1105057186affd6865e8d261e05f0f0646","tests/test_autotrait.rs":"981e792db353be2f14c7a1cabe43b5f1329c168cb7679077cc2be786a0920d48","tests/test_backtrace.rs":"0e50edbb33b6bd07ba89ff3db72fb7c688ba2a4371fccdbbb20309ab02948b6a","tests/test_boxed.rs":"6b26db0e2eb72afe9af7352ea820837aab90f8d486294616dd5dc34c1b94038c","tests/test_chain.rs":"d5e90e3eba58abc60d241d3aade39e0b8d4006d9a14f3cf015d3d925160b5812","tests/test_context.rs":"8409c53b328562c11e822bd6c3cd17e0d4d50b9bbb8fc3617333fd77303a6a33","tests/test_convert.rs":"7e7a8b4772a427a911014ac4d1083f9519000e786177f898808980dd9bdfde61","tests/test_downcast.rs":"797e69a72d125758c4c4897e5dc776d549d52cc9a6a633e0a33193f588a62b88","tests/test_ensure.rs":"c8137a9565685aedf02b365008b27c707f4c3d81cd2b986b3b7105b426c723b1","tests/test_ffi.rs":"d0cb4c1d6d9154090982dee72ae3ebe05a5981f976058c3250f1c9da5a45edef","tests/test_fmt.rs":"17572596f257aac9aa2ec4620e292ca6a954128b94772bb948399fab53832e70","tests/test_macros.rs":"11f05010bc9b16319884c1286444100e30cddc2ecd1ffe5e0fd3fee5ffb32683","tests/test_repr.rs":"dbb9b04ddbe1ab31eb5331ea69f05bb3a147299da2275a3d4dcc92947b5591b9","tests/test_source.rs":"b80723cf635a4f8c4df21891b34bfab9ed2b2aa407e7a2f826d24e334cd5f88e","tests/ui/chained-comparison.rs":"6504b03d95b5acc232a7f4defc9f343b2be6733bf475fa0992e8e6545b912bd4","tests/ui/chained-comparison.stderr":"7f1d0a8c251b0ede2d30b3087ec157fc660945c97a642c4a5acf5a14ec58de34","tests/ui/empty-ensure.rs":"ab5bf37c846a0d689f26ce9257a27228411ed64154f9c950f1602d88a355d94b","tests/ui/empty-ensure.stderr":"345102cbef47310f2f4066a669199873a627ca4f1fcb885505c6e17d1fc95e88","tests/ui/must-use.rs":"fb59860b43f673bf4a430a6036ba463e95028844d8dd4243cfe5ebc7f2be582f","tests/ui/must-use.stderr":"c2848c5f254b4c061eea6714d9baf709924aba06619eaf2a8b3aee1266b75f9e","tests/ui/no-impl.rs":"fab6cbf2f6ea510b86f567dfb3b7c31250a9fd71ae5d110dbb9188be569ec593","tests/ui/no-impl.stderr":"9d36a96220f0b5a81db027bcba411a61a72cc2e370c38058ab556442e8bb8a8b","tests/ui/temporary-value.rs":"4dcc96271b2403e6372cf4cfc813445e5ce4365fc6e156b6bc38274098499a70","tests/ui/temporary-value.stderr":"64e448b6759cf51d41b1360307a638452bbe53ffa706f93e4a503b712d7b89a8","tests/ui/wrong-interpolation.rs":"9c44d4674c2dccd27b9dedd03341346ec02d993b41793ee89b5755202e7e367e","tests/ui/wrong-interpolation.stderr":"301e60e2eb9401782c7dc0b3580613a4cb2aafd4cc8065734a630a62e1161aa5"},"package":"98161a4e3e2184da77bb14f02184cdd111e83bbbcc9979dfee3c44b9a85f5602"} \ No newline at end of file diff --git a/vendor/anyhow/Cargo.toml b/vendor/anyhow/Cargo.toml index 6537f7b5f..844c2bd3a 100644 --- a/vendor/anyhow/Cargo.toml +++ b/vendor/anyhow/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.38" name = "anyhow" -version = "1.0.60" +version = "1.0.65" authors = ["David Tolnay "] description = "Flexible concrete Error type built on std::error::Error" documentation = "https://docs.rs/anyhow" diff --git a/vendor/anyhow/build.rs b/vendor/anyhow/build.rs index c470ba11b..38006832e 100644 --- a/vendor/anyhow/build.rs +++ b/vendor/anyhow/build.rs @@ -15,15 +15,17 @@ compile_error! { // type. If the current toolchain is able to compile it, we go ahead and use // backtrace in anyhow. const PROBE: &str = r#" - #![feature(backtrace)] - #![allow(dead_code)] + #![feature(error_generic_member_access, provide_any)] + use std::any::{Demand, Provider}; use std::backtrace::{Backtrace, BacktraceStatus}; use std::error::Error; use std::fmt::{self, Display}; #[derive(Debug)] - struct E; + struct E { + backtrace: Backtrace, + } impl Display for E { fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result { @@ -32,14 +34,26 @@ const PROBE: &str = r#" } impl Error for E { - fn backtrace(&self) -> Option<&Backtrace> { - let backtrace = Backtrace::capture(); - match backtrace.status() { - BacktraceStatus::Captured | BacktraceStatus::Disabled | _ => {} - } - unimplemented!() + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + demand.provide_ref(&self.backtrace); } } + + struct P; + + impl Provider for P { + fn provide<'a>(&'a self, _demand: &mut Demand<'a>) {} + } + + const _: fn() = || { + let backtrace: Backtrace = Backtrace::capture(); + let status: BacktraceStatus = backtrace.status(); + match status { + BacktraceStatus::Captured | BacktraceStatus::Disabled | _ => {} + } + }; + + const _: fn(&dyn Error) -> Option<&Backtrace> = |err| err.request_ref::(); "#; fn main() { diff --git a/vendor/anyhow/src/backtrace.rs b/vendor/anyhow/src/backtrace.rs index e4c907641..23c0c85ce 100644 --- a/vendor/anyhow/src/backtrace.rs +++ b/vendor/anyhow/src/backtrace.rs @@ -38,7 +38,7 @@ macro_rules! backtrace { #[cfg(backtrace)] macro_rules! backtrace_if_absent { ($err:expr) => { - match $err.backtrace() { + match ($err as &dyn std::error::Error).request_ref::() { Some(_) => None, None => backtrace!(), } diff --git a/vendor/anyhow/src/context.rs b/vendor/anyhow/src/context.rs index c2284130f..1b7dd31ac 100644 --- a/vendor/anyhow/src/context.rs +++ b/vendor/anyhow/src/context.rs @@ -4,7 +4,7 @@ use core::convert::Infallible; use core::fmt::{self, Debug, Display, Write}; #[cfg(backtrace)] -use std::backtrace::Backtrace; +use std::any::Demand; mod ext { use super::*; @@ -24,7 +24,7 @@ mod ext { where C: Display + Send + Sync + 'static, { - let backtrace = backtrace_if_absent!(self); + let backtrace = backtrace_if_absent!(&self); Error::from_context(context, self, backtrace) } } @@ -123,28 +123,29 @@ where C: Display, E: StdError + 'static, { - #[cfg(backtrace)] - fn backtrace(&self) -> Option<&Backtrace> { - self.error.backtrace() - } - fn source(&self) -> Option<&(dyn StdError + 'static)> { Some(&self.error) } + + #[cfg(backtrace)] + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + self.error.provide(demand); + } } impl StdError for ContextError where C: Display, { - #[cfg(backtrace)] - fn backtrace(&self) -> Option<&Backtrace> { - Some(self.error.backtrace()) - } - fn source(&self) -> Option<&(dyn StdError + 'static)> { Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) }) } + + #[cfg(backtrace)] + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + demand.provide_ref(self.error.backtrace()); + self.error.provide(demand); + } } struct Quoted(C); diff --git a/vendor/anyhow/src/ensure.rs b/vendor/anyhow/src/ensure.rs index 80bdab704..0ab447123 100644 --- a/vendor/anyhow/src/ensure.rs +++ b/vendor/anyhow/src/ensure.rs @@ -788,15 +788,15 @@ macro_rules! __fancy_ensure { (lhs, rhs) => { if !(lhs $op rhs) { #[allow(unused_imports)] - use $crate::private::{BothDebug, NotBothDebug}; + use $crate::__private::{BothDebug, NotBothDebug}; return Err((lhs, rhs).__dispatch_ensure( - $crate::private::concat!( + $crate::__private::concat!( "Condition failed: `", - $crate::private::stringify!($lhs), + $crate::__private::stringify!($lhs), " ", - $crate::private::stringify!($op), + $crate::__private::stringify!($op), " ", - $crate::private::stringify!($rhs), + $crate::__private::stringify!($rhs), "`", ), )); @@ -811,24 +811,24 @@ macro_rules! __fancy_ensure { macro_rules! __fallback_ensure { ($cond:expr $(,)?) => { if !$cond { - return $crate::private::Err($crate::Error::msg( - $crate::private::concat!("Condition failed: `", $crate::private::stringify!($cond), "`") + return $crate::__private::Err($crate::Error::msg( + $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`") )); } }; ($cond:expr, $msg:literal $(,)?) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($msg)); + return $crate::__private::Err($crate::__anyhow!($msg)); } }; ($cond:expr, $err:expr $(,)?) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($err)); + return $crate::__private::Err($crate::__anyhow!($err)); } }; ($cond:expr, $fmt:expr, $($arg:tt)*) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($fmt, $($arg)*)); + return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*)); } }; } diff --git a/vendor/anyhow/src/error.rs b/vendor/anyhow/src/error.rs index 0971146c9..9f6ce8c10 100644 --- a/vendor/anyhow/src/error.rs +++ b/vendor/anyhow/src/error.rs @@ -5,6 +5,8 @@ use crate::ptr::Mut; use crate::ptr::{Own, Ref}; use crate::{Error, StdError}; use alloc::boxed::Box; +#[cfg(backtrace)] +use core::any::Demand; use core::any::TypeId; use core::fmt::{self, Debug, Display}; use core::mem::ManuallyDrop; @@ -31,7 +33,7 @@ impl Error { where E: StdError + Send + Sync + 'static, { - let backtrace = backtrace_if_absent!(error); + let backtrace = backtrace_if_absent!(&error); Error::from_std(error, backtrace) } @@ -522,6 +524,18 @@ impl Error { } } +#[cfg(backtrace)] +impl std::any::Provider for Error { + // Called by thiserror when you have `#[source] anyhow::Error`. This provide + // implementation includes the anyhow::Error's Backtrace if any, unlike + // deref'ing to dyn Error where the provide implementation would include + // only the original error's Backtrace from before it got wrapped into an + // anyhow::Error. + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + unsafe { ErrorImpl::provide(self.inner.by_ref(), demand) } + } +} + #[cfg(feature = "std")] #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))] impl From for Error @@ -530,7 +544,7 @@ where { #[cold] fn from(error: E) -> Self { - let backtrace = backtrace_if_absent!(error); + let backtrace = backtrace_if_absent!(&error); Error::from_std(error, backtrace) } } @@ -886,13 +900,21 @@ impl ErrorImpl { .as_ref() .or_else(|| { #[cfg(backtrace)] - return Self::error(this).backtrace(); - #[cfg(all(not(backtrace), feature = "backtrace"))] + return Self::error(this).request_ref::(); + #[cfg(not(backtrace))] return (vtable(this.ptr).object_backtrace)(this); }) .expect("backtrace capture failed") } + #[cfg(backtrace)] + unsafe fn provide<'a>(this: Ref<'a, Self>, demand: &mut Demand<'a>) { + if let Some(backtrace) = &this.deref().backtrace { + demand.provide_ref(backtrace); + } + Self::error(this).provide(demand); + } + #[cold] pub(crate) unsafe fn chain(this: Ref) -> Chain { Chain::new(Self::error(this)) @@ -903,14 +925,14 @@ impl StdError for ErrorImpl where E: StdError, { - #[cfg(backtrace)] - fn backtrace(&self) -> Option<&Backtrace> { - Some(unsafe { ErrorImpl::backtrace(self.erase()) }) - } - fn source(&self) -> Option<&(dyn StdError + 'static)> { unsafe { ErrorImpl::error(self.erase()).source() } } + + #[cfg(backtrace)] + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + unsafe { ErrorImpl::provide(self.erase(), demand) } + } } impl Debug for ErrorImpl diff --git a/vendor/anyhow/src/kind.rs b/vendor/anyhow/src/kind.rs index 59857057d..f47fe44ba 100644 --- a/vendor/anyhow/src/kind.rs +++ b/vendor/anyhow/src/kind.rs @@ -40,7 +40,7 @@ // The anyhow! macro will set up the call in this form: // // #[allow(unused_imports)] -// use $crate::private::{AdhocKind, TraitKind}; +// use $crate::__private::{AdhocKind, TraitKind}; // let error = $msg; // (&error).anyhow_kind().new(error) @@ -110,7 +110,7 @@ impl BoxedKind for Box {} impl Boxed { #[cold] pub fn new(self, error: Box) -> Error { - let backtrace = backtrace_if_absent!(error); + let backtrace = backtrace_if_absent!(&*error); Error::from_boxed(error, backtrace) } } diff --git a/vendor/anyhow/src/lib.rs b/vendor/anyhow/src/lib.rs index 976668aab..792a4d007 100644 --- a/vendor/anyhow/src/lib.rs +++ b/vendor/anyhow/src/lib.rs @@ -210,8 +210,8 @@ //! will require an explicit `.map_err(Error::msg)` when working with a //! non-Anyhow error type inside a function that returns Anyhow's error type. -#![doc(html_root_url = "https://docs.rs/anyhow/1.0.60")] -#![cfg_attr(backtrace, feature(backtrace))] +#![doc(html_root_url = "https://docs.rs/anyhow/1.0.65")] +#![cfg_attr(backtrace, feature(error_generic_member_access, provide_any))] #![cfg_attr(doc_cfg, feature(doc_cfg))] #![cfg_attr(not(feature = "std"), no_std)] #![deny(dead_code, unused_imports, unused_mut)] @@ -634,7 +634,7 @@ pub fn Ok(t: T) -> Result { // Not public API. Referenced by macro-generated code. #[doc(hidden)] -pub mod private { +pub mod __private { use crate::Error; use alloc::fmt; use core::fmt::Arguments; diff --git a/vendor/anyhow/src/macros.rs b/vendor/anyhow/src/macros.rs index 5dc138386..6dd22743b 100644 --- a/vendor/anyhow/src/macros.rs +++ b/vendor/anyhow/src/macros.rs @@ -55,13 +55,13 @@ #[macro_export] macro_rules! bail { ($msg:literal $(,)?) => { - return $crate::private::Err($crate::__anyhow!($msg)) + return $crate::__private::Err($crate::__anyhow!($msg)) }; ($err:expr $(,)?) => { - return $crate::private::Err($crate::__anyhow!($err)) + return $crate::__private::Err($crate::__anyhow!($err)) }; ($fmt:expr, $($arg:tt)*) => { - return $crate::private::Err($crate::__anyhow!($fmt, $($arg)*)) + return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*)) }; } @@ -120,24 +120,24 @@ macro_rules! bail { macro_rules! ensure { ($cond:expr $(,)?) => { if !$cond { - return $crate::private::Err($crate::Error::msg( - $crate::private::concat!("Condition failed: `", $crate::private::stringify!($cond), "`") + return $crate::__private::Err($crate::Error::msg( + $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`") )); } }; ($cond:expr, $msg:literal $(,)?) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($msg)); + return $crate::__private::Err($crate::__anyhow!($msg)); } }; ($cond:expr, $err:expr $(,)?) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($err)); + return $crate::__private::Err($crate::__anyhow!($err)); } }; ($cond:expr, $fmt:expr, $($arg:tt)*) => { if !$cond { - return $crate::private::Err($crate::__anyhow!($fmt, $($arg)*)); + return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*)); } }; } @@ -189,14 +189,14 @@ macro_rules! ensure { #[macro_export] macro_rules! anyhow { ($msg:literal $(,)?) => { - $crate::private::must_use({ - let error = $crate::private::format_err($crate::private::format_args!($msg)); + $crate::__private::must_use({ + let error = $crate::__private::format_err($crate::__private::format_args!($msg)); error }) }; ($err:expr $(,)?) => { - $crate::private::must_use({ - use $crate::private::kind::*; + $crate::__private::must_use({ + use $crate::__private::kind::*; let error = match $err { error => (&error).anyhow_kind().new(error), }; @@ -204,7 +204,7 @@ macro_rules! anyhow { }) }; ($fmt:expr, $($arg:tt)*) => { - $crate::Error::msg($crate::private::format!($fmt, $($arg)*)) + $crate::Error::msg($crate::__private::format!($fmt, $($arg)*)) }; } @@ -215,17 +215,17 @@ macro_rules! anyhow { #[macro_export] macro_rules! __anyhow { ($msg:literal $(,)?) => ({ - let error = $crate::private::format_err($crate::private::format_args!($msg)); + let error = $crate::__private::format_err($crate::__private::format_args!($msg)); error }); ($err:expr $(,)?) => ({ - use $crate::private::kind::*; + use $crate::__private::kind::*; let error = match $err { error => (&error).anyhow_kind().new(error), }; error }); ($fmt:expr, $($arg:tt)*) => { - $crate::Error::msg($crate::private::format!($fmt, $($arg)*)) + $crate::Error::msg($crate::__private::format!($fmt, $($arg)*)) }; } diff --git a/vendor/anyhow/src/wrapper.rs b/vendor/anyhow/src/wrapper.rs index 3ebe51a88..5f18a5031 100644 --- a/vendor/anyhow/src/wrapper.rs +++ b/vendor/anyhow/src/wrapper.rs @@ -1,6 +1,9 @@ use crate::StdError; use core::fmt::{self, Debug, Display}; +#[cfg(backtrace)] +use std::any::Demand; + #[repr(transparent)] pub struct MessageError(pub M); @@ -67,12 +70,12 @@ impl Display for BoxedError { #[cfg(feature = "std")] impl StdError for BoxedError { - #[cfg(backtrace)] - fn backtrace(&self) -> Option<&crate::backtrace::Backtrace> { - self.0.backtrace() - } - fn source(&self) -> Option<&(dyn StdError + 'static)> { self.0.source() } + + #[cfg(backtrace)] + fn provide<'a>(&'a self, demand: &mut Demand<'a>) { + self.0.provide(demand); + } } diff --git a/vendor/anyhow/tests/test_ensure.rs b/vendor/anyhow/tests/test_ensure.rs index 4bb12f9fa..cbcba5798 100644 --- a/vendor/anyhow/tests/test_ensure.rs +++ b/vendor/anyhow/tests/test_ensure.rs @@ -5,9 +5,9 @@ clippy::items_after_statements, clippy::let_and_return, clippy::let_underscore_drop, - clippy::logic_bug, clippy::match_bool, clippy::never_loop, + clippy::overly_complex_bool_expr, clippy::redundant_closure_call, clippy::redundant_pattern_matching, clippy::too_many_lines, diff --git a/vendor/anyhow/tests/ui/must-use.stderr b/vendor/anyhow/tests/ui/must-use.stderr index e9ee24b09..e10bde40f 100644 --- a/vendor/anyhow/tests/ui/must-use.stderr +++ b/vendor/anyhow/tests/ui/must-use.stderr @@ -1,4 +1,4 @@ -error: unused return value of `anyhow::private::must_use` that must be used +error: unused return value of `anyhow::__private::must_use` that must be used --> tests/ui/must-use.rs:8:9 | 8 | anyhow!("it failed"); diff --git a/vendor/anyhow/tests/ui/no-impl.stderr b/vendor/anyhow/tests/ui/no-impl.stderr index 7c5ec503f..074dafe62 100644 --- a/vendor/anyhow/tests/ui/no-impl.stderr +++ b/vendor/anyhow/tests/ui/no-impl.stderr @@ -19,13 +19,13 @@ error[E0599]: the method `anyhow_kind` exists for reference `&Error`, but its tr `&Error: Into` which is required by `&Error: anyhow::kind::TraitKind` note: the following traits must be implemented - --> $RUST/core/src/convert/mod.rs - | - | pub trait Into: Sized { - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - ::: $RUST/core/src/fmt/mod.rs + --> $RUST/core/src/fmt/mod.rs | | pub trait Display { | ^^^^^^^^^^^^^^^^^ + | + ::: $RUST/core/src/convert/mod.rs + | + | pub trait Into: Sized { + | ^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in the macro `anyhow` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/vendor/block-buffer-0.7.3/.cargo-checksum.json b/vendor/block-buffer-0.7.3/.cargo-checksum.json deleted file mode 100644 index 779d602b1..000000000 --- a/vendor/block-buffer-0.7.3/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"e4e9e182794c2185438af0c505714df9e051d1d1b17aec7a42265be672b1d027","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"d5c22aa3118d240e877ad41c5d9fa232f9c77d757d4aac0c2f943afc0a95e0ef","src/lib.rs":"59dd4084e456153bee968153ee45e34c8e853abfb756a53571c5844ccaf18c23"},"package":"c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b"} \ No newline at end of file diff --git a/vendor/block-buffer-0.7.3/Cargo.toml b/vendor/block-buffer-0.7.3/Cargo.toml deleted file mode 100644 index 6b10954cb..000000000 --- a/vendor/block-buffer-0.7.3/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "block-buffer" -version = "0.7.3" -authors = ["RustCrypto Developers"] -description = "Fixed size buffer for block processing of data" -documentation = "https://docs.rs/block-buffer" -keywords = ["block", "buffer"] -categories = ["cryptography", "no-std"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/RustCrypto/utils" -[dependencies.block-padding] -version = "0.1" - -[dependencies.byte-tools] -version = "0.3" - -[dependencies.byteorder] -version = "1.1" -default-features = false - -[dependencies.generic-array] -version = "0.12" -[badges.travis-ci] -repository = "RustCrypto/utils" diff --git a/vendor/block-buffer-0.7.3/LICENSE-APACHE b/vendor/block-buffer-0.7.3/LICENSE-APACHE deleted file mode 100644 index 78173fa2e..000000000 --- a/vendor/block-buffer-0.7.3/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/block-buffer-0.7.3/LICENSE-MIT b/vendor/block-buffer-0.7.3/LICENSE-MIT deleted file mode 100644 index 502cee6e8..000000000 --- a/vendor/block-buffer-0.7.3/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018-2019 The RustCrypto Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/block-buffer-0.7.3/src/lib.rs b/vendor/block-buffer-0.7.3/src/lib.rs deleted file mode 100644 index d3b691655..000000000 --- a/vendor/block-buffer-0.7.3/src/lib.rs +++ /dev/null @@ -1,210 +0,0 @@ -#![no_std] -pub extern crate byteorder; -pub extern crate block_padding; -pub extern crate generic_array; -extern crate byte_tools; - -use byteorder::{ByteOrder, BE}; -use byte_tools::zero; -use block_padding::{Padding, PadError}; -use generic_array::{GenericArray, ArrayLength}; -use core::slice; - -/// Buffer for block processing of data -#[derive(Clone, Default)] -pub struct BlockBuffer> { - buffer: GenericArray, - pos: usize, -} - -#[inline(always)] -unsafe fn cast>(block: &[u8]) -> &GenericArray { - debug_assert_eq!(block.len(), N::to_usize()); - &*(block.as_ptr() as *const GenericArray) -} - - - -impl> BlockBuffer { - /// Process data in `input` in blocks of size `BlockSize` using function `f`. - #[inline] - pub fn input(&mut self, mut input: &[u8], mut f: F) - where F: FnMut(&GenericArray) - { - // If there is already data in the buffer, process it if we have - // enough to complete the chunk. - let rem = self.remaining(); - if self.pos != 0 && input.len() >= rem { - let (l, r) = input.split_at(rem); - input = r; - self.buffer[self.pos..].copy_from_slice(l); - self.pos = 0; - f(&self.buffer); - } - - // While we have at least a full buffer size chunks's worth of data, - // process that data without copying it into the buffer - while input.len() >= self.size() { - let (block, r) = input.split_at(self.size()); - input = r; - f(unsafe { cast(block) }); - } - - // Copy any remaining data into the buffer. - self.buffer[self.pos..self.pos+input.len()].copy_from_slice(input); - self.pos += input.len(); - } - - /* - /// Process data in `input` in blocks of size `BlockSize` using function `f`, which accepts - /// slice of blocks. - #[inline] - pub fn input2(&mut self, mut input: &[u8], mut f: F) - where F: FnMut(&[GenericArray]) - { - // If there is already data in the buffer, process it if we have - // enough to complete the chunk. - let rem = self.remaining(); - if self.pos != 0 && input.len() >= rem { - let (l, r) = input.split_at(rem); - input = r; - self.buffer[self.pos..].copy_from_slice(l); - self.pos = 0; - f(slice::from_ref(&self.buffer)); - } - - // While we have at least a full buffer size chunks's worth of data, - // process it data without copying into the buffer - let n_blocks = input.len()/self.size(); - let (left, right) = input.split_at(n_blocks*self.size()); - // safe because we guarantee that `blocks` does not point outside of `input` - let blocks = unsafe { - slice::from_raw_parts( - left.as_ptr() as *const GenericArray, - n_blocks, - ) - }; - f(blocks); - - // Copy remaining data into the buffer. - self.buffer[self.pos..self.pos+right.len()].copy_from_slice(right); - self.pos += right.len(); - } - */ - - /// Variant that doesn't flush the buffer until there's additional - /// data to be processed. Suitable for tweakable block ciphers - /// like Threefish that need to know whether a block is the *last* - /// data block before processing it. - #[inline] - pub fn input_lazy(&mut self, mut input: &[u8], mut f: F) - where F: FnMut(&GenericArray) - { - let rem = self.remaining(); - if self.pos != 0 && input.len() > rem { - let (l, r) = input.split_at(rem); - input = r; - self.buffer[self.pos..].copy_from_slice(l); - self.pos = 0; - f(&self.buffer); - } - - while input.len() > self.size() { - let (block, r) = input.split_at(self.size()); - input = r; - f(unsafe { cast(block) }); - } - - self.buffer[self.pos..self.pos+input.len()].copy_from_slice(input); - self.pos += input.len(); - } - - /// Pad buffer with `prefix` and make sure that internall buffer - /// has at least `up_to` free bytes. All remaining bytes get - /// zeroed-out. - #[inline] - fn digest_pad(&mut self, up_to: usize, f: &mut F) - where F: FnMut(&GenericArray) - { - if self.pos == self.size() { - f(&self.buffer); - self.pos = 0; - } - self.buffer[self.pos] = 0x80; - self.pos += 1; - - zero(&mut self.buffer[self.pos..]); - - if self.remaining() < up_to { - f(&self.buffer); - zero(&mut self.buffer[..self.pos]); - } - } - - /// Pad message with 0x80, zeros and 64-bit message length - /// in a byte order specified by `B` - #[inline] - pub fn len64_padding(&mut self, data_len: u64, mut f: F) - where B: ByteOrder, F: FnMut(&GenericArray) - { - // TODO: replace `F` with `impl Trait` on MSRV bump - self.digest_pad(8, &mut f); - let s = self.size(); - B::write_u64(&mut self.buffer[s-8..], data_len); - f(&self.buffer); - self.pos = 0; - } - - - /// Pad message with 0x80, zeros and 128-bit message length - /// in the big-endian byte order - #[inline] - pub fn len128_padding_be(&mut self, hi: u64, lo: u64, mut f: F) - where F: FnMut(&GenericArray) - { - // TODO: on MSRV bump replace `F` with `impl Trait`, use `u128`, add `B` - self.digest_pad(16, &mut f); - let s = self.size(); - BE::write_u64(&mut self.buffer[s-16..s-8], hi); - BE::write_u64(&mut self.buffer[s-8..], lo); - f(&self.buffer); - self.pos = 0; - } - - /// Pad message with a given padding `P` - /// - /// Returns `PadError` if internall buffer is full, which can only happen if - /// `input_lazy` was used. - #[inline] - pub fn pad_with(&mut self) - -> Result<&mut GenericArray, PadError> - { - P::pad_block(&mut self.buffer[..], self.pos)?; - self.pos = 0; - Ok(&mut self.buffer) - } - - /// Return size of the internall buffer in bytes - #[inline] - pub fn size(&self) -> usize { - BlockSize::to_usize() - } - - /// Return current cursor position - #[inline] - pub fn position(&self) -> usize { - self.pos - } - - /// Return number of remaining bytes in the internall buffer - #[inline] - pub fn remaining(&self) -> usize { - self.size() - self.pos - } - - /// Reset buffer by setting cursor position to zero - #[inline] - pub fn reset(&mut self) { - self.pos = 0 - } -} diff --git a/vendor/block-padding/.cargo-checksum.json b/vendor/block-padding/.cargo-checksum.json deleted file mode 100644 index e80396463..000000000 --- a/vendor/block-padding/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"f895c4794f1c00f5f01376dae2b66870d939a01b9a366ee4d177b6b7ad99bd4a","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"d5c22aa3118d240e877ad41c5d9fa232f9c77d757d4aac0c2f943afc0a95e0ef","src/lib.rs":"962c90d43c7c2761b3c96fab2713ae357a7a8d2d048e37ce4f3354941ad41b97"},"package":"fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5"} \ No newline at end of file diff --git a/vendor/block-padding/Cargo.toml b/vendor/block-padding/Cargo.toml deleted file mode 100644 index 1b1c849a8..000000000 --- a/vendor/block-padding/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "block-padding" -version = "0.1.5" -authors = ["RustCrypto Developers"] -description = "Padding and unpadding of messages divided into blocks." -documentation = "https://docs.rs/block-padding" -keywords = ["padding", "pkcs7", "ansix923", "iso7816"] -categories = ["cryptography", "no-std"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/RustCrypto/utils" -[dependencies.byte-tools] -version = "0.3" -[badges.travis-ci] -repository = "RustCrypto/utils" diff --git a/vendor/block-padding/LICENSE-APACHE b/vendor/block-padding/LICENSE-APACHE deleted file mode 100644 index 78173fa2e..000000000 --- a/vendor/block-padding/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/block-padding/LICENSE-MIT b/vendor/block-padding/LICENSE-MIT deleted file mode 100644 index 502cee6e8..000000000 --- a/vendor/block-padding/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018-2019 The RustCrypto Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/block-padding/src/lib.rs b/vendor/block-padding/src/lib.rs deleted file mode 100644 index 5c4c8c3b6..000000000 --- a/vendor/block-padding/src/lib.rs +++ /dev/null @@ -1,323 +0,0 @@ -//! Padding and unpadding of messages divided into blocks. -//! -//! This crate provides `Padding` trait which provides padding and unpadding -//! operations. Additionally several common padding schemes are available out -//! of the box. -#![no_std] -#![doc(html_logo_url = - "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")] -extern crate byte_tools; - -use byte_tools::{zero, set}; - -/// Error for indicating failed padding operation -#[derive(Clone, Copy, Debug)] -pub struct PadError; - -/// Error for indicating failed unpadding operation -#[derive(Clone, Copy, Debug)] -pub struct UnpadError; - -/// Trait for padding messages divided into blocks -pub trait Padding { - /// Pads `block` filled with data up to `pos`. - /// - /// `pos` should be inside of the block and block must not be full, i.e. - /// `pos < block.len()` must be true. Otherwise method will return - /// `PadError`. Some potentially irreversible padding schemes can allow - /// padding of the full block, in this case aforementioned condition is - /// relaxed to `pos <= block.len()`. - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError>; - - /// Pads message with length `pos` in the provided buffer. - /// - /// `&buf[..pos]` is perceived as the message, the buffer must contain - /// enough leftover space for padding: `block_size - (pos % block_size)` - /// extra bytes must be available. Otherwise method will return - /// `PadError`. - fn pad(buf: &mut [u8], pos: usize, block_size: usize) - -> Result<&mut [u8], PadError> - { - let bs = block_size * (pos / block_size); - if buf.len() < bs || buf.len() - bs < block_size { Err(PadError)? } - Self::pad_block(&mut buf[bs..bs+block_size], pos - bs)?; - Ok(&mut buf[..bs+block_size]) - } - - /// Unpad given `data` by truncating it according to the used padding. - /// In case of the malformed padding will return `UnpadError` - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError>; -} - -/// Pad block with zeros. -/// -/// ``` -/// use block_padding::{ZeroPadding, Padding}; -/// -/// let msg = b"test"; -/// let n = msg.len(); -/// let mut buffer = [0xff; 16]; -/// buffer[..n].copy_from_slice(msg); -/// let padded_msg = ZeroPadding::pad(&mut buffer, n, 8).unwrap(); -/// assert_eq!(padded_msg, b"test\x00\x00\x00\x00"); -/// assert_eq!(ZeroPadding::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{ZeroPadding, Padding}; -/// # let msg = b"test"; -/// # let n = msg.len(); -/// # let mut buffer = [0xff; 16]; -/// # buffer[..n].copy_from_slice(msg); -/// let padded_msg = ZeroPadding::pad(&mut buffer, n, 2).unwrap(); -/// assert_eq!(padded_msg, b"test"); -/// assert_eq!(ZeroPadding::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// -/// Note that zero padding may not be reversible if the original message ends -/// with one or more zero bytes. -pub enum ZeroPadding{} - -impl Padding for ZeroPadding { - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError> { - if pos > block.len() { Err(PadError)? } - zero(&mut block[pos..]); - Ok(()) - } - - fn pad(buf: &mut [u8], pos: usize, block_size: usize) - -> Result<&mut [u8], PadError> - { - if pos % block_size == 0 { - Ok(&mut buf[..pos]) - } else { - let bs = block_size * (pos / block_size); - let be = bs + block_size; - if buf.len() < be { Err(PadError)? } - Self::pad_block(&mut buf[bs..be], pos - bs)?; - Ok(&mut buf[..be]) - } - } - - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError> { - let mut n = data.len() - 1; - while n != 0 { - if data[n] != 0 { - break; - } - n -= 1; - } - Ok(&data[..n+1]) - } -} - -/// Pad block with bytes with value equal to the number of bytes added. -/// -/// PKCS#7 described in the [RFC 5652](https://tools.ietf.org/html/rfc5652#section-6.3). -/// -/// ``` -/// use block_padding::{Pkcs7, Padding}; -/// -/// let msg = b"test"; -/// let n = msg.len(); -/// let mut buffer = [0xff; 8]; -/// buffer[..n].copy_from_slice(msg); -/// let padded_msg = Pkcs7::pad(&mut buffer, n, 8).unwrap(); -/// assert_eq!(padded_msg, b"test\x04\x04\x04\x04"); -/// assert_eq!(Pkcs7::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{Pkcs7, Padding}; -/// # let msg = b"test"; -/// # let n = msg.len(); -/// # let mut buffer = [0xff; 8]; -/// # buffer[..n].copy_from_slice(msg); -/// let padded_msg = Pkcs7::pad(&mut buffer, n, 2).unwrap(); -/// assert_eq!(padded_msg, b"test\x02\x02"); -/// assert_eq!(Pkcs7::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{Pkcs7, Padding}; -/// let mut buffer = [0xff; 5]; -/// assert!(Pkcs7::pad(&mut buffer, 4, 2).is_err()); -/// ``` -/// ``` -/// # use block_padding::{Pkcs7, Padding}; -/// # let buffer = [0xff; 16]; -/// assert!(Pkcs7::unpad(&buffer).is_err()); -/// ``` -/// -/// In addition to conditions stated in the `Padding` trait documentation, -/// `pad_block` will return `PadError` if `block.len() > 255`, and in case of -/// `pad` if `block_size > 255`. -pub enum Pkcs7{} - -impl Padding for Pkcs7 { - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError> { - if block.len() > 255 { Err(PadError)? } - if pos >= block.len() { Err(PadError)? } - let n = block.len() - pos; - set(&mut block[pos..], n as u8); - Ok(()) - } - - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError> { - if data.is_empty() { Err(UnpadError)? } - let l = data.len(); - let n = data[l-1]; - if n == 0 || n as usize > l { Err(UnpadError)? } - for v in &data[l-n as usize..l-1] { - if *v != n { Err(UnpadError)? } - } - Ok(&data[..l - n as usize]) - } -} - -/// Pad block with zeros except the last byte which will be set to the number -/// bytes. -/// -/// ``` -/// use block_padding::{AnsiX923, Padding}; -/// -/// let msg = b"test"; -/// let n = msg.len(); -/// let mut buffer = [0xff; 16]; -/// buffer[..n].copy_from_slice(msg); -/// let padded_msg = AnsiX923::pad(&mut buffer, n, 8).unwrap(); -/// assert_eq!(padded_msg, b"test\x00\x00\x00\x04"); -/// assert_eq!(AnsiX923::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{AnsiX923, Padding}; -/// # let msg = b"test"; -/// # let n = msg.len(); -/// # let mut buffer = [0xff; 16]; -/// # buffer[..n].copy_from_slice(msg); -/// let padded_msg = AnsiX923::pad(&mut buffer, n, 2).unwrap(); -/// assert_eq!(padded_msg, b"test\x00\x02"); -/// assert_eq!(AnsiX923::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{AnsiX923, Padding}; -/// # let buffer = [0xff; 16]; -/// assert!(AnsiX923::unpad(&buffer).is_err()); -/// ``` -/// -/// In addition to conditions stated in the `Padding` trait documentation, -/// `pad_block` will return `PadError` if `block.len() > 255`, and in case of -/// `pad` if `block_size > 255`. -pub enum AnsiX923{} - -impl Padding for AnsiX923 { - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError>{ - if block.len() > 255 { Err(PadError)? } - if pos >= block.len() { Err(PadError)? } - let bs = block.len(); - zero(&mut block[pos..bs-1]); - block[bs-1] = (bs - pos) as u8; - Ok(()) - } - - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError> { - if data.is_empty() { Err(UnpadError)? } - let l = data.len(); - let n = data[l-1] as usize; - if n == 0 || n > l { - return Err(UnpadError) - } - for v in &data[l-n..l-1] { - if *v != 0 { Err(UnpadError)? } - } - Ok(&data[..l-n]) - } -} - -/// Pad block with byte sequence `\x80 00...00 00`. -/// -/// ``` -/// use block_padding::{Iso7816, Padding}; -/// -/// let msg = b"test"; -/// let n = msg.len(); -/// let mut buffer = [0xff; 16]; -/// buffer[..n].copy_from_slice(msg); -/// let padded_msg = Iso7816::pad(&mut buffer, n, 8).unwrap(); -/// assert_eq!(padded_msg, b"test\x80\x00\x00\x00"); -/// assert_eq!(Iso7816::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{Iso7816, Padding}; -/// # let msg = b"test"; -/// # let n = msg.len(); -/// # let mut buffer = [0xff; 16]; -/// # buffer[..n].copy_from_slice(msg); -/// let padded_msg = Iso7816::pad(&mut buffer, n, 2).unwrap(); -/// assert_eq!(padded_msg, b"test\x80\x00"); -/// assert_eq!(Iso7816::unpad(&padded_msg).unwrap(), msg); -/// ``` -pub enum Iso7816{} - -impl Padding for Iso7816 { - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError> { - if pos >= block.len() { Err(PadError)? } - block[pos] = 0x80; - zero(&mut block[pos+1..]); - Ok(()) - } - - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError> { - if data.is_empty() { Err(UnpadError)? } - let mut n = data.len() - 1; - while n != 0 { - if data[n] != 0 { break; } - n -= 1; - } - if data[n] != 0x80 { Err(UnpadError)? } - Ok(&data[..n]) - } -} - -/// Don't pad the data. Useful for key wrapping. Padding will fail if the data cannot be -/// fitted into blocks without padding. -/// -/// ``` -/// use block_padding::{NoPadding, Padding}; -/// -/// let msg = b"test"; -/// let n = msg.len(); -/// let mut buffer = [0xff; 16]; -/// buffer[..n].copy_from_slice(msg); -/// let padded_msg = NoPadding::pad(&mut buffer, n, 4).unwrap(); -/// assert_eq!(padded_msg, b"test"); -/// assert_eq!(NoPadding::unpad(&padded_msg).unwrap(), msg); -/// ``` -/// ``` -/// # use block_padding::{NoPadding, Padding}; -/// # let msg = b"test"; -/// # let n = msg.len(); -/// # let mut buffer = [0xff; 16]; -/// # buffer[..n].copy_from_slice(msg); -/// let padded_msg = NoPadding::pad(&mut buffer, n, 2).unwrap(); -/// assert_eq!(padded_msg, b"test"); -/// assert_eq!(NoPadding::unpad(&padded_msg).unwrap(), msg); -/// ``` -pub enum NoPadding {} - -impl Padding for NoPadding { - fn pad_block(block: &mut [u8], pos: usize) -> Result<(), PadError> { - if pos % block.len() != 0 { - Err(PadError)? - } - Ok(()) - } - - fn pad(buf: &mut [u8], pos: usize, block_size: usize) -> Result<&mut [u8], PadError> { - if pos % block_size != 0 { - Err(PadError)? - } - Ok(&mut buf[..pos]) - } - - fn unpad(data: &[u8]) -> Result<&[u8], UnpadError> { - Ok(data) - } -} diff --git a/vendor/byte-tools/.cargo-checksum.json b/vendor/byte-tools/.cargo-checksum.json deleted file mode 100644 index 36f28b52e..000000000 --- a/vendor/byte-tools/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"0542f7bd3605206297b6708b28bfff87a2ef7fa65ccab1474ddb53072600d7e1","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"d5c22aa3118d240e877ad41c5d9fa232f9c77d757d4aac0c2f943afc0a95e0ef","src/lib.rs":"c8fb45d44cae0b1094bf8cef5059827b28b490eb14a3865fa536b61241c2c8c4"},"package":"e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"} \ No newline at end of file diff --git a/vendor/byte-tools/Cargo.toml b/vendor/byte-tools/Cargo.toml deleted file mode 100644 index 74c6b9a0e..000000000 --- a/vendor/byte-tools/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "byte-tools" -version = "0.3.1" -authors = ["RustCrypto Developers"] -description = "Bytes related utility functions" -documentation = "https://docs.rs/byte-tools" -keywords = ["bytes"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/RustCrypto/utils" diff --git a/vendor/byte-tools/LICENSE-APACHE b/vendor/byte-tools/LICENSE-APACHE deleted file mode 100644 index 78173fa2e..000000000 --- a/vendor/byte-tools/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/byte-tools/LICENSE-MIT b/vendor/byte-tools/LICENSE-MIT deleted file mode 100644 index 502cee6e8..000000000 --- a/vendor/byte-tools/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018-2019 The RustCrypto Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/byte-tools/src/lib.rs b/vendor/byte-tools/src/lib.rs deleted file mode 100644 index b4a450f9f..000000000 --- a/vendor/byte-tools/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -#![no_std] -use core::ptr; - -/// Copy bytes from `src` to `dst` -/// -/// Panics if `src.len() < dst.len()` -#[inline(always)] -pub fn copy(src: &[u8], dst: &mut [u8]) { - assert!(dst.len() >= src.len()); - unsafe { - ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); - } -} - -/// Zero all bytes in `dst` -#[inline(always)] -pub fn zero(dst: &mut [u8]) { - unsafe { - ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len()); - } -} - -/// Sets all bytes in `dst` equal to `value` -#[inline(always)] -pub fn set(dst: &mut [u8], value: u8) { - unsafe { - ptr::write_bytes(dst.as_mut_ptr(), value, dst.len()); - } -} diff --git a/vendor/byteorder/.cargo-checksum.json b/vendor/byteorder/.cargo-checksum.json deleted file mode 100644 index 434cc1a16..000000000 --- a/vendor/byteorder/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"3a745d94ee9dce0d9dc638c02078cd5001d3d9d12d58b4f220c0101e32cfc16a","COPYING":"01c266bced4a434da0051174d6bee16a4c82cf634e2679b6155d40d75012390f","Cargo.toml":"8585455e5a0e638cf5d489a21e286e93680f835cb8a13595918b5eb7c8c7f212","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"9d57556868344534de2489317e3c6bb611348ecd44438dcb982bd8d2a55a5a1b","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","benches/bench.rs":"a80bf3cd446c9b6c0cca3865c4de047bdf4644b74cdf696822f8ff87adfa1fca","rustfmt.toml":"1ca600239a27401c4a43f363cf3f38183a212affc1f31bff3ae93234bbaec228","src/io.rs":"9612530634d0e7ce9887a23836b58c0d972c1f45b05d9ada8355961567075627","src/lib.rs":"813ce6a8beafee3fd4e63325d783108aa02e8c57e412bc97580191d84082fbc9"},"package":"14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"} \ No newline at end of file diff --git a/vendor/byteorder/CHANGELOG.md b/vendor/byteorder/CHANGELOG.md deleted file mode 100644 index 6b51eb076..000000000 --- a/vendor/byteorder/CHANGELOG.md +++ /dev/null @@ -1,139 +0,0 @@ -1.3.4 -===== -This patch release squashes deprecation warnings for the `try!` macro, in -accordance with byteorder's minimum supported Rust version (currently at Rust -1.12.0). - - -1.3.3 -===== -This patch release adds `ByteOrder::write_i8_into()` as a simple, safe interface -for ordinarily unsafe or tedious code. - - -1.3.2 -===== -This patch release adds `ReadBytesExt::read_i8_into()` as a simple, safe interface -for ordinarily unsafe or tedious code. - - -1.3.1 -===== -This minor release performs mostly small internal changes. Going forward, these -are not going to be incorporated into the changelog. - - -1.3.0 -===== -This new minor release now enables `i128` support automatically on Rust -compilers that support 128-bit integers. The `i128` feature is now a no-op, but -continues to exist for backward compatibility purposes. The crate continues to -maintain compatibility with Rust 1.12.0. - -This release also deprecates the `ByteOrder` trait methods -`read_f32_into_unchecked` and `read_f64_into_unchecked` in favor of -`read_f32_into` and `read_f64_into`. This was an oversight from the 1.2 release -where the corresponding methods on `ReadBytesExt` were deprecated. - -`quickcheck` and `rand` were bumped to `0.8` and `0.6`, respectively. - -A few small documentation related bugs have been fixed. - - -1.2.7 -===== -This patch release excludes some CI files from the crate release and updates -the license field to use `OR` instead of `/`. - - -1.2.6 -===== -This patch release fixes some test compilation errors introduced by an -over-eager release of 1.2.5. - - -1.2.5 -===== -This patch release fixes some typos in the docs, adds doc tests to methods on -`WriteByteExt` and bumps the quickcheck dependency to `0.7`. - - -1.2.4 -===== -This patch release adds support for 48-bit integers by adding the following -methods to the `ByteOrder` trait: `read_u48`, `read_i48`, `write_u48` and -`write_i48`. Corresponding methods have been added to the `ReadBytesExt` and -`WriteBytesExt` traits as well. - - -1.2.3 -===== -This patch release removes the use of `feature(i128_type)` from byteorder, -since it has been stabilized. We leave byteorder's `i128` feature in place -in order to continue supporting compilation on older versions of Rust. - - -1.2.2 -===== -This patch release only consists of internal improvements and refactorings. -Notably, this removes all uses of `transmute` and instead uses pointer casts. - - -1.2.1 -===== -This patch release removes more unnecessary uses of `unsafe` that -were overlooked in the prior `1.2.0` release. In particular, the -`ReadBytesExt::read_{f32,f64}_into_checked` methods have been deprecated and -replaced by more appropriately named `read_{f32,f64}_into` methods. - - -1.2.0 -===== -The most prominent change in this release of `byteorder` is the removal of -unnecessary signaling NaN masking, and in turn, the `unsafe` annotations -associated with methods that didn't do masking. See -[#103](https://github.com/BurntSushi/byteorder/issues/103) -for more details. - -* [BUG #102](https://github.com/BurntSushi/byteorder/issues/102): - Fix big endian tests. -* [BUG #103](https://github.com/BurntSushi/byteorder/issues/103): - Remove sNaN masking. - - -1.1.0 -===== -This release of `byteorder` features a number of fixes and improvements, mostly -as a result of the -[Litz Blitz evaluation](https://public.etherpad-mozilla.org/p/rust-crate-eval-byteorder). - -Feature enhancements: - -* [FEATURE #63](https://github.com/BurntSushi/byteorder/issues/63): - Add methods for reading/writing slices of numbers for a specific - endianness. -* [FEATURE #65](https://github.com/BurntSushi/byteorder/issues/65): - Add support for `u128`/`i128` types. (Behind the nightly only `i128` - feature.) -* [FEATURE #72](https://github.com/BurntSushi/byteorder/issues/72): - Add "panics" and "errors" sections for each relevant public API item. -* [FEATURE #74](https://github.com/BurntSushi/byteorder/issues/74): - Add CI badges to Cargo.toml. -* [FEATURE #75](https://github.com/BurntSushi/byteorder/issues/75): - Add more examples to public API items. -* Add 24-bit read/write methods. -* Add `BE` and `LE` type aliases for `BigEndian` and `LittleEndian`, - respectively. - -Bug fixes: - -* [BUG #68](https://github.com/BurntSushi/byteorder/issues/68): - Panic in {BigEndian,LittleEndian}::default. -* [BUG #69](https://github.com/BurntSushi/byteorder/issues/69): - Seal the `ByteOrder` trait to prevent out-of-crate implementations. -* [BUG #71](https://github.com/BurntSushi/byteorder/issues/71): - Guarantee that the results of `read_f32`/`read_f64` are always defined. -* [BUG #73](https://github.com/BurntSushi/byteorder/issues/73): - Add crates.io categories. -* [BUG #77](https://github.com/BurntSushi/byteorder/issues/77): - Add `html_root` doc attribute. diff --git a/vendor/byteorder/COPYING b/vendor/byteorder/COPYING deleted file mode 100644 index bb9c20a09..000000000 --- a/vendor/byteorder/COPYING +++ /dev/null @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff --git a/vendor/byteorder/Cargo.toml b/vendor/byteorder/Cargo.toml deleted file mode 100644 index c71f90ba9..000000000 --- a/vendor/byteorder/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -edition = "2018" -name = "byteorder" -version = "1.4.3" -authors = ["Andrew Gallant "] -exclude = ["/ci/*"] -description = "Library for reading/writing numbers in big-endian and little-endian." -homepage = "https://github.com/BurntSushi/byteorder" -documentation = "https://docs.rs/byteorder" -readme = "README.md" -keywords = ["byte", "endian", "big-endian", "little-endian", "binary"] -categories = ["encoding", "parsing", "no-std"] -license = "Unlicense OR MIT" -repository = "https://github.com/BurntSushi/byteorder" -[profile.bench] -opt-level = 3 - -[lib] -name = "byteorder" -bench = false -[dev-dependencies.quickcheck] -version = "0.9.2" -default-features = false - -[dev-dependencies.rand] -version = "0.7" - -[features] -default = ["std"] -i128 = [] -std = [] diff --git a/vendor/byteorder/LICENSE-MIT b/vendor/byteorder/LICENSE-MIT deleted file mode 100644 index 3b0a5dc09..000000000 --- a/vendor/byteorder/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/byteorder/README.md b/vendor/byteorder/README.md deleted file mode 100644 index d8461c58f..000000000 --- a/vendor/byteorder/README.md +++ /dev/null @@ -1,63 +0,0 @@ -byteorder -========= -This crate provides convenience methods for encoding and decoding -numbers in either big-endian or little-endian order. - -[![Build status](https://github.com/BurntSushi/byteorder/workflows/ci/badge.svg)](https://github.com/BurntSushi/byteorder/actions) -[![](https://meritbadge.herokuapp.com/byteorder)](https://crates.io/crates/byteorder) - -Dual-licensed under MIT or the [UNLICENSE](https://unlicense.org/). - - -### Documentation - -https://docs.rs/byteorder - - -### Installation - -This crate works with Cargo and is on -[crates.io](https://crates.io/crates/byteorder). Add it to your `Cargo.toml` -like so: - -```toml -[dependencies] -byteorder = "1" -``` - -If you want to augment existing `Read` and `Write` traits, then import the -extension methods like so: - -```rust -use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian}; -``` - -For example: - -```rust -use std::io::Cursor; -use byteorder::{BigEndian, ReadBytesExt}; - -let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -// Note that we use type parameters to indicate which kind of byte order -// we want! -assert_eq!(517, rdr.read_u16::().unwrap()); -assert_eq!(768, rdr.read_u16::().unwrap()); -``` - -### `no_std` crates - -This crate has a feature, `std`, that is enabled by default. To use this crate -in a `no_std` context, add the following to your `Cargo.toml`: - -```toml -[dependencies] -byteorder = { version = "1", default-features = false } -``` - - -### Alternatives - -Note that as of Rust 1.32, the standard numeric types provide built-in methods -like `to_le_bytes` and `from_le_bytes`, which support some of the same use -cases. diff --git a/vendor/byteorder/UNLICENSE b/vendor/byteorder/UNLICENSE deleted file mode 100644 index 68a49daad..000000000 --- a/vendor/byteorder/UNLICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to diff --git a/vendor/byteorder/benches/bench.rs b/vendor/byteorder/benches/bench.rs deleted file mode 100644 index bb00422f7..000000000 --- a/vendor/byteorder/benches/bench.rs +++ /dev/null @@ -1,324 +0,0 @@ -#![feature(test)] - -extern crate test; - -macro_rules! bench_num { - ($name:ident, $read:ident, $bytes:expr, $data:expr) => { - mod $name { - use byteorder::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use test::black_box as bb; - use test::Bencher; - - const NITER: usize = 100_000; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$read(&buf, $bytes)); - } - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$read(&buf, $bytes)); - } - }); - } - - #[bench] - fn read_native_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$read(&buf, $bytes)); - } - }); - } - } - }; - ($ty:ident, $max:ident, - $read:ident, $write:ident, $size:expr, $data:expr) => { - mod $ty { - use byteorder::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use std::$ty; - use test::black_box as bb; - use test::Bencher; - - const NITER: usize = 100_000; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$read(&buf)); - } - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$read(&buf)); - } - }); - } - - #[bench] - fn read_native_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$read(&buf)); - } - }); - } - - #[bench] - fn write_big_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$write(&mut buf, n)); - } - }); - } - - #[bench] - fn write_little_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$write(&mut buf, n)); - } - }); - } - - #[bench] - fn write_native_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$write(&mut buf, n)); - } - }); - } - } - }; -} - -bench_num!(u16, MAX, read_u16, write_u16, 2, [1, 2]); -bench_num!(i16, MAX, read_i16, write_i16, 2, [1, 2]); -bench_num!(u32, MAX, read_u32, write_u32, 4, [1, 2, 3, 4]); -bench_num!(i32, MAX, read_i32, write_i32, 4, [1, 2, 3, 4]); -bench_num!(u64, MAX, read_u64, write_u64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(i64, MAX, read_i64, write_i64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(f32, MAX, read_f32, write_f32, 4, [1, 2, 3, 4]); -bench_num!(f64, MAX, read_f64, write_f64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!(uint_1, read_uint, 1, [1]); -bench_num!(uint_2, read_uint, 2, [1, 2]); -bench_num!(uint_3, read_uint, 3, [1, 2, 3]); -bench_num!(uint_4, read_uint, 4, [1, 2, 3, 4]); -bench_num!(uint_5, read_uint, 5, [1, 2, 3, 4, 5]); -bench_num!(uint_6, read_uint, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(uint_7, read_uint, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(uint_8, read_uint, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!(int_1, read_int, 1, [1]); -bench_num!(int_2, read_int, 2, [1, 2]); -bench_num!(int_3, read_int, 3, [1, 2, 3]); -bench_num!(int_4, read_int, 4, [1, 2, 3, 4]); -bench_num!(int_5, read_int, 5, [1, 2, 3, 4, 5]); -bench_num!(int_6, read_int, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(int_7, read_int, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(int_8, read_int, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!( - u128, - MAX, - read_u128, - write_u128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); -bench_num!( - i128, - MAX, - read_i128, - write_i128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -bench_num!(uint128_1, read_uint128, 1, [1]); -bench_num!(uint128_2, read_uint128, 2, [1, 2]); -bench_num!(uint128_3, read_uint128, 3, [1, 2, 3]); -bench_num!(uint128_4, read_uint128, 4, [1, 2, 3, 4]); -bench_num!(uint128_5, read_uint128, 5, [1, 2, 3, 4, 5]); -bench_num!(uint128_6, read_uint128, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(uint128_7, read_uint128, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(uint128_8, read_uint128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(uint128_9, read_uint128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); -bench_num!(uint128_10, read_uint128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); -bench_num!(uint128_11, read_uint128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); -bench_num!( - uint128_12, - read_uint128, - 12, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -); -bench_num!( - uint128_13, - read_uint128, - 13, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -); -bench_num!( - uint128_14, - read_uint128, - 14, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -); -bench_num!( - uint128_15, - read_uint128, - 15, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -); -bench_num!( - uint128_16, - read_uint128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -bench_num!(int128_1, read_int128, 1, [1]); -bench_num!(int128_2, read_int128, 2, [1, 2]); -bench_num!(int128_3, read_int128, 3, [1, 2, 3]); -bench_num!(int128_4, read_int128, 4, [1, 2, 3, 4]); -bench_num!(int128_5, read_int128, 5, [1, 2, 3, 4, 5]); -bench_num!(int128_6, read_int128, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(int128_7, read_int128, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(int128_8, read_int128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(int128_9, read_int128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); -bench_num!(int128_10, read_int128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); -bench_num!(int128_11, read_int128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); -bench_num!( - int128_12, - read_int128, - 12, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -); -bench_num!( - int128_13, - read_int128, - 13, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -); -bench_num!( - int128_14, - read_int128, - 14, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -); -bench_num!( - int128_15, - read_int128, - 15, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -); -bench_num!( - int128_16, - read_int128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -macro_rules! bench_slice { - ($name:ident, $numty:ty, $read:ident, $write:ident) => { - mod $name { - use std::mem::size_of; - - use byteorder::{BigEndian, ByteOrder, LittleEndian}; - use rand::distributions; - use rand::{self, Rng}; - use test::Bencher; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let mut numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - BigEndian::$write(&numbers, &mut bytes); - - b.bytes = bytes.len() as u64; - b.iter(|| { - BigEndian::$read(&bytes, &mut numbers); - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let mut numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - LittleEndian::$write(&numbers, &mut bytes); - - b.bytes = bytes.len() as u64; - b.iter(|| { - LittleEndian::$read(&bytes, &mut numbers); - }); - } - - #[bench] - fn write_big_endian(b: &mut Bencher) { - let numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - - b.bytes = bytes.len() as u64; - b.iter(|| { - BigEndian::$write(&numbers, &mut bytes); - }); - } - - #[bench] - fn write_little_endian(b: &mut Bencher) { - let numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - - b.bytes = bytes.len() as u64; - b.iter(|| { - LittleEndian::$write(&numbers, &mut bytes); - }); - } - } - }; -} - -bench_slice!(slice_u64, u64, read_u64_into, write_u64_into); diff --git a/vendor/byteorder/rustfmt.toml b/vendor/byteorder/rustfmt.toml deleted file mode 100644 index aa37a218b..000000000 --- a/vendor/byteorder/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -max_width = 79 -use_small_heuristics = "max" diff --git a/vendor/byteorder/src/io.rs b/vendor/byteorder/src/io.rs deleted file mode 100644 index dfad2ca39..000000000 --- a/vendor/byteorder/src/io.rs +++ /dev/null @@ -1,1592 +0,0 @@ -use std::{ - io::{self, Result}, - slice, -}; - -use crate::ByteOrder; - -/// Extends [`Read`] with methods for reading numbers. (For `std::io`.) -/// -/// Most of the methods defined here have an unconstrained type parameter that -/// must be explicitly instantiated. Typically, it is instantiated with either -/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. -/// -/// # Examples -/// -/// Read unsigned 16 bit big-endian integers from a [`Read`]: -/// -/// ```rust -/// use std::io::Cursor; -/// use byteorder::{BigEndian, ReadBytesExt}; -/// -/// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -/// assert_eq!(517, rdr.read_u16::().unwrap()); -/// assert_eq!(768, rdr.read_u16::().unwrap()); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html -pub trait ReadBytesExt: io::Read { - /// Reads an unsigned 8 bit integer from the underlying reader. - /// - /// Note that since this reads a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::ReadBytesExt; - /// - /// let mut rdr = Cursor::new(vec![2, 5]); - /// assert_eq!(2, rdr.read_u8().unwrap()); - /// assert_eq!(5, rdr.read_u8().unwrap()); - /// ``` - #[inline] - fn read_u8(&mut self) -> Result { - let mut buf = [0; 1]; - self.read_exact(&mut buf)?; - Ok(buf[0]) - } - - /// Reads a signed 8 bit integer from the underlying reader. - /// - /// Note that since this reads a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::ReadBytesExt; - /// - /// let mut rdr = Cursor::new(vec![0x02, 0xfb]); - /// assert_eq!(2, rdr.read_i8().unwrap()); - /// assert_eq!(-5, rdr.read_i8().unwrap()); - /// ``` - #[inline] - fn read_i8(&mut self) -> Result { - let mut buf = [0; 1]; - self.read_exact(&mut buf)?; - Ok(buf[0] as i8) - } - - /// Reads an unsigned 16 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// assert_eq!(517, rdr.read_u16::().unwrap()); - /// assert_eq!(768, rdr.read_u16::().unwrap()); - /// ``` - #[inline] - fn read_u16(&mut self) -> Result { - let mut buf = [0; 2]; - self.read_exact(&mut buf)?; - Ok(T::read_u16(&buf)) - } - - /// Reads a signed 16 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); - /// assert_eq!(193, rdr.read_i16::().unwrap()); - /// assert_eq!(-132, rdr.read_i16::().unwrap()); - /// ``` - #[inline] - fn read_i16(&mut self) -> Result { - let mut buf = [0; 2]; - self.read_exact(&mut buf)?; - Ok(T::read_i16(&buf)) - } - - /// Reads an unsigned 24 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 24 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x01, 0x0b]); - /// assert_eq!(267, rdr.read_u24::().unwrap()); - /// ``` - #[inline] - fn read_u24(&mut self) -> Result { - let mut buf = [0; 3]; - self.read_exact(&mut buf)?; - Ok(T::read_u24(&buf)) - } - - /// Reads a signed 24 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 24 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xff, 0x7a, 0x33]); - /// assert_eq!(-34253, rdr.read_i24::().unwrap()); - /// ``` - #[inline] - fn read_i24(&mut self) -> Result { - let mut buf = [0; 3]; - self.read_exact(&mut buf)?; - Ok(T::read_i24(&buf)) - } - - /// Reads an unsigned 32 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); - /// assert_eq!(267, rdr.read_u32::().unwrap()); - /// ``` - #[inline] - fn read_u32(&mut self) -> Result { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_u32(&buf)) - } - - /// Reads a signed 32 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); - /// assert_eq!(-34253, rdr.read_i32::().unwrap()); - /// ``` - #[inline] - fn read_i32(&mut self) -> Result { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_i32(&buf)) - } - - /// Reads an unsigned 48 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 48 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xb6, 0x71, 0x6b, 0xdc, 0x2b, 0x31]); - /// assert_eq!(200598257150769, rdr.read_u48::().unwrap()); - /// ``` - #[inline] - fn read_u48(&mut self) -> Result { - let mut buf = [0; 6]; - self.read_exact(&mut buf)?; - Ok(T::read_u48(&buf)) - } - - /// Reads a signed 48 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 48 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x9d, 0x71, 0xab, 0xe7, 0x97, 0x8f]); - /// assert_eq!(-108363435763825, rdr.read_i48::().unwrap()); - /// ``` - #[inline] - fn read_i48(&mut self) -> Result { - let mut buf = [0; 6]; - self.read_exact(&mut buf)?; - Ok(T::read_i48(&buf)) - } - - /// Reads an unsigned 64 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned 64 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83]); - /// assert_eq!(918733457491587, rdr.read_u64::().unwrap()); - /// ``` - #[inline] - fn read_u64(&mut self) -> Result { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_u64(&buf)) - } - - /// Reads a signed 64 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a signed 64 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); - /// assert_eq!(i64::min_value(), rdr.read_i64::().unwrap()); - /// ``` - #[inline] - fn read_i64(&mut self) -> Result { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_i64(&buf)) - } - - /// Reads an unsigned 128 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned 128 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); - /// assert_eq!(16947640962301618749969007319746179, rdr.read_u128::().unwrap()); - /// ``` - #[inline] - fn read_u128(&mut self) -> Result { - let mut buf = [0; 16]; - self.read_exact(&mut buf)?; - Ok(T::read_u128(&buf)) - } - - /// Reads a signed 128 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a signed 128 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - /// assert_eq!(i128::min_value(), rdr.read_i128::().unwrap()); - /// ``` - #[inline] - fn read_i128(&mut self) -> Result { - let mut buf = [0; 16]; - self.read_exact(&mut buf)?; - Ok(T::read_i128(&buf)) - } - - /// Reads an unsigned n-bytes integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned n-byte big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0x74, 0xfa]); - /// assert_eq!(8418554, rdr.read_uint::(3).unwrap()); - #[inline] - fn read_uint(&mut self, nbytes: usize) -> Result { - let mut buf = [0; 8]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_uint(&buf[..nbytes], nbytes)) - } - - /// Reads a signed n-bytes integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned n-byte big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xc1, 0xff, 0x7c]); - /// assert_eq!(-4063364, rdr.read_int::(3).unwrap()); - #[inline] - fn read_int(&mut self, nbytes: usize) -> Result { - let mut buf = [0; 8]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_int(&buf[..nbytes], nbytes)) - } - - /// Reads an unsigned n-bytes integer from the underlying reader. - #[inline] - fn read_uint128(&mut self, nbytes: usize) -> Result { - let mut buf = [0; 16]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_uint128(&buf[..nbytes], nbytes)) - } - - /// Reads a signed n-bytes integer from the underlying reader. - #[inline] - fn read_int128(&mut self, nbytes: usize) -> Result { - let mut buf = [0; 16]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_int128(&buf[..nbytes], nbytes)) - } - - /// Reads a IEEE754 single-precision (4 bytes) floating point number from - /// the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a big-endian single-precision floating point number from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// ]); - /// assert_eq!(f32::consts::PI, rdr.read_f32::().unwrap()); - /// ``` - #[inline] - fn read_f32(&mut self) -> Result { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_f32(&buf)) - } - - /// Reads a IEEE754 double-precision (8 bytes) floating point number from - /// the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a big-endian double-precision floating point number from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// ]); - /// assert_eq!(f64::consts::PI, rdr.read_f64::().unwrap()); - /// ``` - #[inline] - fn read_f64(&mut self) -> Result { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_f64(&buf)) - } - - /// Reads a sequence of unsigned 16 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_u16_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u16_into(&mut self, dst: &mut [u16]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u16(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 32 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_u32_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u32_into(&mut self, dst: &mut [u32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u32(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 64 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 64 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_u64_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u64_into(&mut self, dst: &mut [u64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u64(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 128 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 128 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_u128_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u128_into( - &mut self, - dst: &mut [u128], - ) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u128(dst); - Ok(()) - } - - /// Reads a sequence of signed 8 bit integers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// Note that since each `i8` is a single byte, no byte order conversions - /// are used. This method is included because it provides a safe, simple - /// way for the caller to read into a `&mut [i8]` buffer. (Without this - /// method, the caller would have to either use `unsafe` code or convert - /// each byte to `i8` individually.) - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 251, 3]); - /// let mut dst = [0; 3]; - /// rdr.read_i8_into(&mut dst).unwrap(); - /// assert_eq!([2, -5, 3], dst); - /// ``` - #[inline] - fn read_i8_into(&mut self, dst: &mut [i8]) -> Result<()> { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf) - } - - /// Reads a sequence of signed 16 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_i16_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i16_into(&mut self, dst: &mut [i16]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i16(dst); - Ok(()) - } - - /// Reads a sequence of signed 32 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_i32_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i32_into(&mut self, dst: &mut [i32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i32(dst); - Ok(()) - } - - /// Reads a sequence of signed 64 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 64 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_i64_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i64_into(&mut self, dst: &mut [i64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i64(dst); - Ok(()) - } - - /// Reads a sequence of signed 128 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 128 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_i128_into::(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i128_into( - &mut self, - dst: &mut [i128], - ) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i128(dst); - Ok(()) - } - - /// Reads a sequence of IEEE754 single-precision (4 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// 0x3f, 0x80, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f32_into::(&mut dst).unwrap(); - /// assert_eq!([f32::consts::PI, 1.0], dst); - /// ``` - #[inline] - fn read_f32_into(&mut self, dst: &mut [f32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_f32(dst); - Ok(()) - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f32_into` instead. - /// - /// Reads a sequence of IEEE754 single-precision (4 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// 0x3f, 0x80, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f32_into_unchecked::(&mut dst).unwrap(); - /// assert_eq!([f32::consts::PI, 1.0], dst); - /// ``` - #[inline] - #[deprecated(since = "1.2.0", note = "please use `read_f32_into` instead")] - fn read_f32_into_unchecked( - &mut self, - dst: &mut [f32], - ) -> Result<()> { - self.read_f32_into::(dst) - } - - /// Reads a sequence of IEEE754 double-precision (8 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f64_into::(&mut dst).unwrap(); - /// assert_eq!([f64::consts::PI, 1.0], dst); - /// ``` - #[inline] - fn read_f64_into(&mut self, dst: &mut [f64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_f64(dst); - Ok(()) - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f64_into` instead. - /// - /// Reads a sequence of IEEE754 double-precision (8 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Safety - /// - /// This method is unsafe because there are no guarantees made about the - /// floating point values. In particular, this method does not check for - /// signaling NaNs, which may result in undefined behavior. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f64_into_unchecked::(&mut dst).unwrap(); - /// assert_eq!([f64::consts::PI, 1.0], dst); - /// ``` - #[inline] - #[deprecated(since = "1.2.0", note = "please use `read_f64_into` instead")] - fn read_f64_into_unchecked( - &mut self, - dst: &mut [f64], - ) -> Result<()> { - self.read_f64_into::(dst) - } -} - -/// All types that implement `Read` get methods defined in `ReadBytesExt` -/// for free. -impl ReadBytesExt for R {} - -/// Extends [`Write`] with methods for writing numbers. (For `std::io`.) -/// -/// Most of the methods defined here have an unconstrained type parameter that -/// must be explicitly instantiated. Typically, it is instantiated with either -/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. -/// -/// # Examples -/// -/// Write unsigned 16 bit big-endian integers to a [`Write`]: -/// -/// ```rust -/// use byteorder::{BigEndian, WriteBytesExt}; -/// -/// let mut wtr = vec![]; -/// wtr.write_u16::(517).unwrap(); -/// wtr.write_u16::(768).unwrap(); -/// assert_eq!(wtr, vec![2, 5, 3, 0]); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html -pub trait WriteBytesExt: io::Write { - /// Writes an unsigned 8 bit integer to the underlying writer. - /// - /// Note that since this writes a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 8 bit integers to a `Write`: - /// - /// ```rust - /// use byteorder::WriteBytesExt; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u8(2).unwrap(); - /// wtr.write_u8(5).unwrap(); - /// assert_eq!(wtr, b"\x02\x05"); - /// ``` - #[inline] - fn write_u8(&mut self, n: u8) -> Result<()> { - self.write_all(&[n]) - } - - /// Writes a signed 8 bit integer to the underlying writer. - /// - /// Note that since this writes a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 8 bit integers to a `Write`: - /// - /// ```rust - /// use byteorder::WriteBytesExt; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i8(2).unwrap(); - /// wtr.write_i8(-5).unwrap(); - /// assert_eq!(wtr, b"\x02\xfb"); - /// ``` - #[inline] - fn write_i8(&mut self, n: i8) -> Result<()> { - self.write_all(&[n as u8]) - } - - /// Writes an unsigned 16 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 16 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u16::(517).unwrap(); - /// wtr.write_u16::(768).unwrap(); - /// assert_eq!(wtr, b"\x02\x05\x03\x00"); - /// ``` - #[inline] - fn write_u16(&mut self, n: u16) -> Result<()> { - let mut buf = [0; 2]; - T::write_u16(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 16 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 16 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i16::(193).unwrap(); - /// wtr.write_i16::(-132).unwrap(); - /// assert_eq!(wtr, b"\x00\xc1\xff\x7c"); - /// ``` - #[inline] - fn write_i16(&mut self, n: i16) -> Result<()> { - let mut buf = [0; 2]; - T::write_i16(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 24 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 24 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u24::(267).unwrap(); - /// wtr.write_u24::(120111).unwrap(); - /// assert_eq!(wtr, b"\x00\x01\x0b\x01\xd5\x2f"); - /// ``` - #[inline] - fn write_u24(&mut self, n: u32) -> Result<()> { - let mut buf = [0; 3]; - T::write_u24(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 24 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 24 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i24::(-34253).unwrap(); - /// wtr.write_i24::(120111).unwrap(); - /// assert_eq!(wtr, b"\xff\x7a\x33\x01\xd5\x2f"); - /// ``` - #[inline] - fn write_i24(&mut self, n: i32) -> Result<()> { - let mut buf = [0; 3]; - T::write_i24(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 32 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 32 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u32::(267).unwrap(); - /// wtr.write_u32::(1205419366).unwrap(); - /// assert_eq!(wtr, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); - /// ``` - #[inline] - fn write_u32(&mut self, n: u32) -> Result<()> { - let mut buf = [0; 4]; - T::write_u32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 32 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 32 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i32::(-34253).unwrap(); - /// wtr.write_i32::(1205419366).unwrap(); - /// assert_eq!(wtr, b"\xff\xff\x7a\x33\x47\xd9\x3d\x66"); - /// ``` - #[inline] - fn write_i32(&mut self, n: i32) -> Result<()> { - let mut buf = [0; 4]; - T::write_i32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 48 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 48 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u48::(52360336390828).unwrap(); - /// wtr.write_u48::(541).unwrap(); - /// assert_eq!(wtr, b"\x2f\x9f\x17\x40\x3a\xac\x00\x00\x00\x00\x02\x1d"); - /// ``` - #[inline] - fn write_u48(&mut self, n: u64) -> Result<()> { - let mut buf = [0; 6]; - T::write_u48(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 48 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 48 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i48::(-108363435763825).unwrap(); - /// wtr.write_i48::(77).unwrap(); - /// assert_eq!(wtr, b"\x9d\x71\xab\xe7\x97\x8f\x00\x00\x00\x00\x00\x4d"); - /// ``` - #[inline] - fn write_i48(&mut self, n: i64) -> Result<()> { - let mut buf = [0; 6]; - T::write_i48(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 64 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 64 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u64::(918733457491587).unwrap(); - /// wtr.write_u64::(143).unwrap(); - /// assert_eq!(wtr, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f"); - /// ``` - #[inline] - fn write_u64(&mut self, n: u64) -> Result<()> { - let mut buf = [0; 8]; - T::write_u64(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 64 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 64 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i64::(i64::min_value()).unwrap(); - /// wtr.write_i64::(i64::max_value()).unwrap(); - /// assert_eq!(wtr, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff"); - /// ``` - #[inline] - fn write_i64(&mut self, n: i64) -> Result<()> { - let mut buf = [0; 8]; - T::write_i64(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 128 bit integer to the underlying writer. - #[inline] - fn write_u128(&mut self, n: u128) -> Result<()> { - let mut buf = [0; 16]; - T::write_u128(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 128 bit integer to the underlying writer. - #[inline] - fn write_i128(&mut self, n: i128) -> Result<()> { - let mut buf = [0; 16]; - T::write_i128(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned n-bytes integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Panics - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 8`, this method panics. - /// - /// # Examples - /// - /// Write unsigned 40 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_uint::(312550384361, 5).unwrap(); - /// wtr.write_uint::(43, 5).unwrap(); - /// assert_eq!(wtr, b"\x48\xc5\x74\x62\xe9\x00\x00\x00\x00\x2b"); - /// ``` - #[inline] - fn write_uint( - &mut self, - n: u64, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 8]; - T::write_uint(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a signed n-bytes integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Panics - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 8`, this method panics. - /// - /// # Examples - /// - /// Write signed 56 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_int::(-3548172039376767, 7).unwrap(); - /// wtr.write_int::(43, 7).unwrap(); - /// assert_eq!(wtr, b"\xf3\x64\xf4\xd1\xfd\xb0\x81\x00\x00\x00\x00\x00\x00\x2b"); - /// ``` - #[inline] - fn write_int( - &mut self, - n: i64, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 8]; - T::write_int(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes an unsigned n-bytes integer to the underlying writer. - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 16`, this method panics. - #[inline] - fn write_uint128( - &mut self, - n: u128, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 16]; - T::write_uint128(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a signed n-bytes integer to the underlying writer. - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 16`, this method panics. - #[inline] - fn write_int128( - &mut self, - n: i128, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 16]; - T::write_int128(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a IEEE754 single-precision (4 bytes) floating point number to - /// the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write a big-endian single-precision floating point number to a `Write`: - /// - /// ```rust - /// use std::f32; - /// - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_f32::(f32::consts::PI).unwrap(); - /// assert_eq!(wtr, b"\x40\x49\x0f\xdb"); - /// ``` - #[inline] - fn write_f32(&mut self, n: f32) -> Result<()> { - let mut buf = [0; 4]; - T::write_f32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a IEEE754 double-precision (8 bytes) floating point number to - /// the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write a big-endian double-precision floating point number to a `Write`: - /// - /// ```rust - /// use std::f64; - /// - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_f64::(f64::consts::PI).unwrap(); - /// assert_eq!(wtr, b"\x40\x09\x21\xfb\x54\x44\x2d\x18"); - /// ``` - #[inline] - fn write_f64(&mut self, n: f64) -> Result<()> { - let mut buf = [0; 8]; - T::write_f64(&mut buf, n); - self.write_all(&buf) - } -} - -/// All types that implement `Write` get methods defined in `WriteBytesExt` -/// for free. -impl WriteBytesExt for W {} - -/// Convert a slice of T (where T is plain old data) to its mutable binary -/// representation. -/// -/// This function is wildly unsafe because it permits arbitrary modification of -/// the binary representation of any `Copy` type. Use with care. It's intended -/// to be called only where `T` is a numeric type. -unsafe fn slice_to_u8_mut(slice: &mut [T]) -> &mut [u8] { - use std::mem::size_of; - - let len = size_of::() * slice.len(); - slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut u8, len) -} diff --git a/vendor/byteorder/src/lib.rs b/vendor/byteorder/src/lib.rs deleted file mode 100644 index cc37cca6a..000000000 --- a/vendor/byteorder/src/lib.rs +++ /dev/null @@ -1,4052 +0,0 @@ -/*! -This crate provides convenience methods for encoding and decoding numbers in -either [big-endian or little-endian order]. - -The organization of the crate is pretty simple. A trait, [`ByteOrder`], specifies -byte conversion methods for each type of number in Rust (sans numbers that have -a platform dependent size like `usize` and `isize`). Two types, [`BigEndian`] -and [`LittleEndian`] implement these methods. Finally, [`ReadBytesExt`] and -[`WriteBytesExt`] provide convenience methods available to all types that -implement [`Read`] and [`Write`]. - -An alias, [`NetworkEndian`], for [`BigEndian`] is provided to help improve -code clarity. - -An additional alias, [`NativeEndian`], is provided for the endianness of the -local platform. This is convenient when serializing data for use and -conversions are not desired. - -# Examples - -Read unsigned 16 bit big-endian integers from a [`Read`] type: - -```rust -use std::io::Cursor; -use byteorder::{BigEndian, ReadBytesExt}; - -let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -// Note that we use type parameters to indicate which kind of byte order -// we want! -assert_eq!(517, rdr.read_u16::().unwrap()); -assert_eq!(768, rdr.read_u16::().unwrap()); -``` - -Write unsigned 16 bit little-endian integers to a [`Write`] type: - -```rust -use byteorder::{LittleEndian, WriteBytesExt}; - -let mut wtr = vec![]; -wtr.write_u16::(517).unwrap(); -wtr.write_u16::(768).unwrap(); -assert_eq!(wtr, vec![5, 2, 0, 3]); -``` - -# Optional Features - -This crate optionally provides support for 128 bit values (`i128` and `u128`) -when built with the `i128` feature enabled. - -This crate can also be used without the standard library. - -# Alternatives - -Note that as of Rust 1.32, the standard numeric types provide built-in methods -like `to_le_bytes` and `from_le_bytes`, which support some of the same use -cases. - -[big-endian or little-endian order]: https://en.wikipedia.org/wiki/Endianness -[`ByteOrder`]: trait.ByteOrder.html -[`BigEndian`]: enum.BigEndian.html -[`LittleEndian`]: enum.LittleEndian.html -[`ReadBytesExt`]: trait.ReadBytesExt.html -[`WriteBytesExt`]: trait.WriteBytesExt.html -[`NetworkEndian`]: type.NetworkEndian.html -[`NativeEndian`]: type.NativeEndian.html -[`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html -[`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html -*/ - -#![deny(missing_docs)] -#![cfg_attr(not(feature = "std"), no_std)] - -use core::{ - convert::TryInto, fmt::Debug, hash::Hash, ptr::copy_nonoverlapping, slice, -}; - -#[cfg(feature = "std")] -pub use crate::io::{ReadBytesExt, WriteBytesExt}; - -#[cfg(feature = "std")] -mod io; - -#[inline] -fn extend_sign(val: u64, nbytes: usize) -> i64 { - let shift = (8 - nbytes) * 8; - (val << shift) as i64 >> shift -} - -#[inline] -fn extend_sign128(val: u128, nbytes: usize) -> i128 { - let shift = (16 - nbytes) * 8; - (val << shift) as i128 >> shift -} - -#[inline] -fn unextend_sign(val: i64, nbytes: usize) -> u64 { - let shift = (8 - nbytes) * 8; - (val << shift) as u64 >> shift -} - -#[inline] -fn unextend_sign128(val: i128, nbytes: usize) -> u128 { - let shift = (16 - nbytes) * 8; - (val << shift) as u128 >> shift -} - -#[inline] -fn pack_size(n: u64) -> usize { - if n < 1 << 8 { - 1 - } else if n < 1 << 16 { - 2 - } else if n < 1 << 24 { - 3 - } else if n < 1 << 32 { - 4 - } else if n < 1 << 40 { - 5 - } else if n < 1 << 48 { - 6 - } else if n < 1 << 56 { - 7 - } else { - 8 - } -} - -#[inline] -fn pack_size128(n: u128) -> usize { - if n < 1 << 8 { - 1 - } else if n < 1 << 16 { - 2 - } else if n < 1 << 24 { - 3 - } else if n < 1 << 32 { - 4 - } else if n < 1 << 40 { - 5 - } else if n < 1 << 48 { - 6 - } else if n < 1 << 56 { - 7 - } else if n < 1 << 64 { - 8 - } else if n < 1 << 72 { - 9 - } else if n < 1 << 80 { - 10 - } else if n < 1 << 88 { - 11 - } else if n < 1 << 96 { - 12 - } else if n < 1 << 104 { - 13 - } else if n < 1 << 112 { - 14 - } else if n < 1 << 120 { - 15 - } else { - 16 - } -} - -mod private { - /// Sealed stops crates other than byteorder from implementing any traits - /// that use it. - pub trait Sealed {} - impl Sealed for super::LittleEndian {} - impl Sealed for super::BigEndian {} -} - -/// `ByteOrder` describes types that can serialize integers as bytes. -/// -/// Note that `Self` does not appear anywhere in this trait's definition! -/// Therefore, in order to use it, you'll need to use syntax like -/// `T::read_u16(&[0, 1])` where `T` implements `ByteOrder`. -/// -/// This crate provides two types that implement `ByteOrder`: [`BigEndian`] -/// and [`LittleEndian`]. -/// This trait is sealed and cannot be implemented for callers to avoid -/// breaking backwards compatibility when adding new derived traits. -/// -/// # Examples -/// -/// Write and read `u32` numbers in little endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, LittleEndian}; -/// -/// let mut buf = [0; 4]; -/// LittleEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); -/// ``` -/// -/// Write and read `i16` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, BigEndian}; -/// -/// let mut buf = [0; 2]; -/// BigEndian::write_i16(&mut buf, -5_000); -/// assert_eq!(-5_000, BigEndian::read_i16(&buf)); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -pub trait ByteOrder: - Clone - + Copy - + Debug - + Default - + Eq - + Hash - + Ord - + PartialEq - + PartialOrd - + private::Sealed -{ - /// Reads an unsigned 16 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - fn read_u16(buf: &[u8]) -> u16; - - /// Reads an unsigned 24 bit integer from `buf`, stored in u32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_u24(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); - /// ``` - fn read_u24(buf: &[u8]) -> u32 { - Self::read_uint(buf, 3) as u32 - } - - /// Reads an unsigned 32 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_u32(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); - /// ``` - fn read_u32(buf: &[u8]) -> u32; - - /// Reads an unsigned 48 bit integer from `buf`, stored in u64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); - /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); - /// ``` - fn read_u48(buf: &[u8]) -> u64 { - Self::read_uint(buf, 6) as u64 - } - - /// Reads an unsigned 64 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_u64(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); - /// ``` - fn read_u64(buf: &[u8]) -> u64; - - /// Reads an unsigned 128 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_u128(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); - /// ``` - fn read_u128(buf: &[u8]) -> u128; - - /// Reads an unsigned n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 8` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); - /// ``` - fn read_uint(buf: &[u8], nbytes: usize) -> u64; - - /// Reads an unsigned n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 16` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); - /// ``` - fn read_uint128(buf: &[u8], nbytes: usize) -> u128; - - /// Writes an unsigned 16 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_u16(&mut buf, 1_000); - /// assert_eq!(1_000, LittleEndian::read_u16(&buf)); - /// ``` - fn write_u16(buf: &mut [u8], n: u16); - - /// Writes an unsigned 24 bit integer `n` to `buf`, stored in u32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_u24(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); - /// ``` - fn write_u24(buf: &mut [u8], n: u32) { - Self::write_uint(buf, n as u64, 3) - } - - /// Writes an unsigned 32 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_u32(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); - /// ``` - fn write_u32(buf: &mut [u8], n: u32); - - /// Writes an unsigned 48 bit integer `n` to `buf`, stored in u64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); - /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); - /// ``` - fn write_u48(buf: &mut [u8], n: u64) { - Self::write_uint(buf, n as u64, 6) - } - - /// Writes an unsigned 64 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_u64(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); - /// ``` - fn write_u64(buf: &mut [u8], n: u64); - - /// Writes an unsigned 128 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_u128(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); - /// ``` - fn write_u128(buf: &mut [u8], n: u128); - - /// Writes an unsigned integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); - /// ``` - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize); - - /// Writes an unsigned integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); - /// ``` - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize); - - /// Reads a signed 16 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_i16(&mut buf, -1_000); - /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); - /// ``` - #[inline] - fn read_i16(buf: &[u8]) -> i16 { - Self::read_u16(buf) as i16 - } - - /// Reads a signed 24 bit integer from `buf`, stored in i32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_i24(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); - /// ``` - #[inline] - fn read_i24(buf: &[u8]) -> i32 { - Self::read_int(buf, 3) as i32 - } - - /// Reads a signed 32 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_i32(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); - /// ``` - #[inline] - fn read_i32(buf: &[u8]) -> i32 { - Self::read_u32(buf) as i32 - } - - /// Reads a signed 48 bit integer from `buf`, stored in i64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); - /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); - /// ``` - #[inline] - fn read_i48(buf: &[u8]) -> i64 { - Self::read_int(buf, 6) as i64 - } - - /// Reads a signed 64 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_i64(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); - /// ``` - #[inline] - fn read_i64(buf: &[u8]) -> i64 { - Self::read_u64(buf) as i64 - } - - /// Reads a signed 128 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_i128(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); - /// ``` - #[inline] - fn read_i128(buf: &[u8]) -> i128 { - Self::read_u128(buf) as i128 - } - - /// Reads a signed n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 8` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); - /// ``` - #[inline] - fn read_int(buf: &[u8], nbytes: usize) -> i64 { - extend_sign(Self::read_uint(buf, nbytes), nbytes) - } - - /// Reads a signed n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 16` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int128(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); - /// ``` - #[inline] - fn read_int128(buf: &[u8], nbytes: usize) -> i128 { - extend_sign128(Self::read_uint128(buf, nbytes), nbytes) - } - - /// Reads a IEEE754 single-precision (4 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let e = 2.71828; - /// let mut buf = [0; 4]; - /// LittleEndian::write_f32(&mut buf, e); - /// assert_eq!(e, LittleEndian::read_f32(&buf)); - /// ``` - #[inline] - fn read_f32(buf: &[u8]) -> f32 { - f32::from_bits(Self::read_u32(buf)) - } - - /// Reads a IEEE754 double-precision (8 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let phi = 1.6180339887; - /// let mut buf = [0; 8]; - /// LittleEndian::write_f64(&mut buf, phi); - /// assert_eq!(phi, LittleEndian::read_f64(&buf)); - /// ``` - #[inline] - fn read_f64(buf: &[u8]) -> f64 { - f64::from_bits(Self::read_u64(buf)) - } - - /// Writes a signed 16 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_i16(&mut buf, -1_000); - /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); - /// ``` - #[inline] - fn write_i16(buf: &mut [u8], n: i16) { - Self::write_u16(buf, n as u16) - } - - /// Writes a signed 24 bit integer `n` to `buf`, stored in i32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_i24(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); - /// ``` - #[inline] - fn write_i24(buf: &mut [u8], n: i32) { - Self::write_int(buf, n as i64, 3) - } - - /// Writes a signed 32 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_i32(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); - /// ``` - #[inline] - fn write_i32(buf: &mut [u8], n: i32) { - Self::write_u32(buf, n as u32) - } - - /// Writes a signed 48 bit integer `n` to `buf`, stored in i64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); - /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); - /// ``` - #[inline] - fn write_i48(buf: &mut [u8], n: i64) { - Self::write_int(buf, n as i64, 6) - } - - /// Writes a signed 64 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_i64(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); - /// ``` - #[inline] - fn write_i64(buf: &mut [u8], n: i64) { - Self::write_u64(buf, n as u64) - } - - /// Writes a signed 128 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read n-byte `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_i128(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); - /// ``` - #[inline] - fn write_i128(buf: &mut [u8], n: i128) { - Self::write_u128(buf, n as u128) - } - - /// Writes a signed integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); - /// ``` - #[inline] - fn write_int(buf: &mut [u8], n: i64, nbytes: usize) { - Self::write_uint(buf, unextend_sign(n, nbytes), nbytes) - } - - /// Writes a signed integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int128(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); - /// ``` - #[inline] - fn write_int128(buf: &mut [u8], n: i128, nbytes: usize) { - Self::write_uint128(buf, unextend_sign128(n, nbytes), nbytes) - } - - /// Writes a IEEE754 single-precision (4 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let e = 2.71828; - /// let mut buf = [0; 4]; - /// LittleEndian::write_f32(&mut buf, e); - /// assert_eq!(e, LittleEndian::read_f32(&buf)); - /// ``` - #[inline] - fn write_f32(buf: &mut [u8], n: f32) { - Self::write_u32(buf, n.to_bits()) - } - - /// Writes a IEEE754 double-precision (8 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let phi = 1.6180339887; - /// let mut buf = [0; 8]; - /// LittleEndian::write_f64(&mut buf, phi); - /// assert_eq!(phi, LittleEndian::read_f64(&buf)); - /// ``` - #[inline] - fn write_f64(buf: &mut [u8], n: f64) { - Self::write_u64(buf, n.to_bits()) - } - - /// Reads unsigned 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 2*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u16_into(src: &[u8], dst: &mut [u16]); - - /// Reads unsigned 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u32_into(src: &[u8], dst: &mut [u32]); - - /// Reads unsigned 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u64_into(src: &[u8], dst: &mut [u64]); - - /// Reads unsigned 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 16*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u128_into(src: &[u8], dst: &mut [u128]); - - /// Reads signed 16 bit integers from `src` to `dst`. - /// - /// # Panics - /// - /// Panics when `buf.len() != 2*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0x0f, 0xee]; - /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i16_into(src: &[u8], dst: &mut [i16]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u16, dst.len()) - }; - Self::read_u16_into(src, dst) - } - - /// Reads signed 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i32_into(src: &[u8], dst: &mut [i32]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) - }; - Self::read_u32_into(src, dst); - } - - /// Reads signed 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i64_into(src: &[u8], dst: &mut [i64]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) - }; - Self::read_u64_into(src, dst); - } - - /// Reads signed 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 16*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i128_into(src: &[u8], dst: &mut [i128]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u128, dst.len()) - }; - Self::read_u128_into(src, dst); - } - - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_f32_into(src: &[u8], dst: &mut [f32]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) - }; - Self::read_u32_into(src, dst); - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f32_into` instead. - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into_unchecked(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - #[deprecated(since = "1.3.0", note = "please use `read_f32_into` instead")] - fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32]) { - Self::read_f32_into(src, dst); - } - - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_f64_into(src: &[u8], dst: &mut [f64]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) - }; - Self::read_u64_into(src, dst); - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f64_into` instead. - /// - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into_unchecked(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - #[deprecated(since = "1.3.0", note = "please use `read_f64_into` instead")] - fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64]) { - Self::read_f64_into(src, dst); - } - - /// Writes unsigned 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 2*src.len()`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u16_into(src: &[u16], dst: &mut [u8]); - - /// Writes unsigned 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 4*src.len()`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u32_into(src: &[u32], dst: &mut [u8]); - - /// Writes unsigned 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 8*src.len()`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u64_into(src: &[u64], dst: &mut [u8]); - - /// Writes unsigned 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 16*src.len()`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u128_into(src: &[u128], dst: &mut [u8]); - - /// Writes signed 8 bit integers from `src` into `dst`. - /// - /// Note that since each `i8` is a single byte, no byte order conversions - /// are used. This method is included because it provides a safe, simple - /// way for the caller to write from a `&[i8]` buffer. (Without this - /// method, the caller would have to either use `unsafe` code or convert - /// each byte to `u8` individually.) - /// - /// # Panics - /// - /// Panics when `buf.len() != src.len()`. - /// - /// # Examples - /// - /// Write and read `i8` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; - /// - /// let mut bytes = [0; 4]; - /// let numbers_given = [1, 2, 0xf, 0xe]; - /// LittleEndian::write_i8_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// bytes.as_ref().read_i8_into(&mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i8_into(src: &[i8], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u8, src.len()) - }; - dst.copy_from_slice(src); - } - - /// Writes signed 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `buf.len() != 2*src.len()`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0x0f, 0xee]; - /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i16_into(src: &[i16], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u16, src.len()) - }; - Self::write_u16_into(src, dst); - } - - /// Writes signed 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 4*src.len()`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i32_into(src: &[i32], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) - }; - Self::write_u32_into(src, dst); - } - - /// Writes signed 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 8*src.len()`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i64_into(src: &[i64], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) - }; - Self::write_u64_into(src, dst); - } - - /// Writes signed 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 16*src.len()`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i128_into(src: &[i128], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u128, src.len()) - }; - Self::write_u128_into(src, dst); - } - - /// Writes IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_f32_into(src: &[f32], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) - }; - Self::write_u32_into(src, dst); - } - - /// Writes IEEE754 double-precision (8 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_f64_into(src: &[f64], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) - }; - Self::write_u64_into(src, dst); - } - - /// Converts the given slice of unsigned 16 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u16(&mut numbers); - /// assert_eq!(numbers, [5u16.to_be(), 65000u16.to_be()]); - /// ``` - fn from_slice_u16(numbers: &mut [u16]); - - /// Converts the given slice of unsigned 32 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u32(&mut numbers); - /// assert_eq!(numbers, [5u32.to_be(), 65000u32.to_be()]); - /// ``` - fn from_slice_u32(numbers: &mut [u32]); - - /// Converts the given slice of unsigned 64 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u64(&mut numbers); - /// assert_eq!(numbers, [5u64.to_be(), 65000u64.to_be()]); - /// ``` - fn from_slice_u64(numbers: &mut [u64]); - - /// Converts the given slice of unsigned 128 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u128(&mut numbers); - /// assert_eq!(numbers, [5u128.to_be(), 65000u128.to_be()]); - /// ``` - fn from_slice_u128(numbers: &mut [u128]); - - /// Converts the given slice of signed 16 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 6500]; - /// BigEndian::from_slice_i16(&mut numbers); - /// assert_eq!(numbers, [5i16.to_be(), 6500i16.to_be()]); - /// ``` - #[inline] - fn from_slice_i16(src: &mut [i16]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u16, src.len()) - }; - Self::from_slice_u16(src); - } - - /// Converts the given slice of signed 32 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i32(&mut numbers); - /// assert_eq!(numbers, [5i32.to_be(), 65000i32.to_be()]); - /// ``` - #[inline] - fn from_slice_i32(src: &mut [i32]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u32, src.len()) - }; - Self::from_slice_u32(src); - } - - /// Converts the given slice of signed 64 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i64(&mut numbers); - /// assert_eq!(numbers, [5i64.to_be(), 65000i64.to_be()]); - /// ``` - #[inline] - fn from_slice_i64(src: &mut [i64]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u64, src.len()) - }; - Self::from_slice_u64(src); - } - - /// Converts the given slice of signed 128 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i128(&mut numbers); - /// assert_eq!(numbers, [5i128.to_be(), 65000i128.to_be()]); - /// ``` - #[inline] - fn from_slice_i128(src: &mut [i128]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u128, src.len()) - }; - Self::from_slice_u128(src); - } - - /// Converts the given slice of IEEE754 single-precision (4 bytes) floating - /// point numbers to a particular endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - fn from_slice_f32(numbers: &mut [f32]); - - /// Converts the given slice of IEEE754 double-precision (8 bytes) floating - /// point numbers to a particular endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - fn from_slice_f64(numbers: &mut [f64]); -} - -/// Defines big-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `u32` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, BigEndian}; -/// -/// let mut buf = [0; 4]; -/// BigEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, BigEndian::read_u32(&buf)); -/// ``` -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum BigEndian {} - -impl Default for BigEndian { - fn default() -> BigEndian { - panic!("BigEndian default") - } -} - -/// A type alias for [`BigEndian`]. -/// -/// [`BigEndian`]: enum.BigEndian.html -pub type BE = BigEndian; - -/// Defines little-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `u32` numbers in little endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, LittleEndian}; -/// -/// let mut buf = [0; 4]; -/// LittleEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); -/// ``` -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum LittleEndian {} - -impl Default for LittleEndian { - fn default() -> LittleEndian { - panic!("LittleEndian default") - } -} - -/// A type alias for [`LittleEndian`]. -/// -/// [`LittleEndian`]: enum.LittleEndian.html -pub type LE = LittleEndian; - -/// Defines network byte order serialization. -/// -/// Network byte order is defined by [RFC 1700][1] to be big-endian, and is -/// referred to in several protocol specifications. This type is an alias of -/// [`BigEndian`]. -/// -/// [1]: https://tools.ietf.org/html/rfc1700 -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `i16` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, NetworkEndian, BigEndian}; -/// -/// let mut buf = [0; 2]; -/// BigEndian::write_i16(&mut buf, -5_000); -/// assert_eq!(-5_000, NetworkEndian::read_i16(&buf)); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -pub type NetworkEndian = BigEndian; - -/// Defines system native-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// On this platform, this is an alias for [`LittleEndian`]. -/// -/// [`LittleEndian`]: enum.LittleEndian.html -#[cfg(target_endian = "little")] -pub type NativeEndian = LittleEndian; - -/// Defines system native-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// On this platform, this is an alias for [`BigEndian`]. -/// -/// [`BigEndian`]: enum.BigEndian.html -#[cfg(target_endian = "big")] -pub type NativeEndian = BigEndian; - -/// Copies $size bytes from a number $n to a &mut [u8] $dst. $ty represents the -/// numeric type of $n and $which must be either to_be or to_le, depending on -/// which endianness one wants to use when writing to $dst. -/// -/// This macro is only safe to call when $ty is a numeric type and $size == -/// size_of::<$ty>() and where $dst is a &mut [u8]. -macro_rules! unsafe_write_num_bytes { - ($ty:ty, $size:expr, $n:expr, $dst:expr, $which:ident) => {{ - assert!($size <= $dst.len()); - unsafe { - // N.B. https://github.com/rust-lang/rust/issues/22776 - let bytes = *(&$n.$which() as *const _ as *const [u8; $size]); - copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size); - } - }}; -} - -/// Copies a &[u8] $src into a &mut [] $dst for the endianness given -/// by $which (must be either to_be or to_le). -/// -/// This macro is only safe to call when $src and $dst are &[u8] and &mut [u8], -/// respectively. The macro will panic if $src.len() != $size * $dst.len(), -/// where $size represents the size of the integers encoded in $src. -macro_rules! unsafe_read_slice { - ($src:expr, $dst:expr, $size:expr, $which:ident) => {{ - assert_eq!($src.len(), $size * $dst.len()); - - unsafe { - copy_nonoverlapping( - $src.as_ptr(), - $dst.as_mut_ptr() as *mut u8, - $src.len(), - ); - } - for v in $dst.iter_mut() { - *v = v.$which(); - } - }}; -} - -/// Copies a &[$ty] $src into a &mut [u8] $dst, where $ty must be a numeric -/// type. This panics if size_of::<$ty>() * $src.len() != $dst.len(). -/// -/// This macro is only safe to call when $src is a slice of numeric types and -/// $dst is a &mut [u8] and where $ty represents the type of the integers in -/// $src. -macro_rules! unsafe_write_slice_native { - ($src:expr, $dst:expr, $ty:ty) => {{ - let size = core::mem::size_of::<$ty>(); - assert_eq!(size * $src.len(), $dst.len()); - - unsafe { - copy_nonoverlapping( - $src.as_ptr() as *const u8, - $dst.as_mut_ptr(), - $dst.len(), - ); - } - }}; -} - -macro_rules! write_slice { - ($src:expr, $dst:expr, $ty:ty, $size:expr, $write:expr) => {{ - assert!($size == ::core::mem::size_of::<$ty>()); - assert_eq!($size * $src.len(), $dst.len()); - - for (&n, chunk) in $src.iter().zip($dst.chunks_mut($size)) { - $write(chunk, n); - } - }}; -} - -impl ByteOrder for BigEndian { - #[inline] - fn read_u16(buf: &[u8]) -> u16 { - u16::from_be_bytes(buf[..2].try_into().unwrap()) - } - - #[inline] - fn read_u32(buf: &[u8]) -> u32 { - u32::from_be_bytes(buf[..4].try_into().unwrap()) - } - - #[inline] - fn read_u64(buf: &[u8]) -> u64 { - u64::from_be_bytes(buf[..8].try_into().unwrap()) - } - - #[inline] - fn read_u128(buf: &[u8]) -> u128 { - u128::from_be_bytes(buf[..16].try_into().unwrap()) - } - - #[inline] - fn read_uint(buf: &[u8], nbytes: usize) -> u64 { - assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len()); - let mut out = 0u64; - let ptr_out = &mut out as *mut u64 as *mut u8; - unsafe { - copy_nonoverlapping( - buf.as_ptr(), - ptr_out.offset((8 - nbytes) as isize), - nbytes, - ); - } - out.to_be() - } - - #[inline] - fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { - assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len()); - let mut out: u128 = 0; - let ptr_out = &mut out as *mut u128 as *mut u8; - unsafe { - copy_nonoverlapping( - buf.as_ptr(), - ptr_out.offset((16 - nbytes) as isize), - nbytes, - ); - } - out.to_be() - } - - #[inline] - fn write_u16(buf: &mut [u8], n: u16) { - unsafe_write_num_bytes!(u16, 2, n, buf, to_be); - } - - #[inline] - fn write_u32(buf: &mut [u8], n: u32) { - unsafe_write_num_bytes!(u32, 4, n, buf, to_be); - } - - #[inline] - fn write_u64(buf: &mut [u8], n: u64) { - unsafe_write_num_bytes!(u64, 8, n, buf, to_be); - } - - #[inline] - fn write_u128(buf: &mut [u8], n: u128) { - unsafe_write_num_bytes!(u128, 16, n, buf, to_be); - } - - #[inline] - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { - assert!(pack_size(n) <= nbytes && nbytes <= 8); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_be() as *const u64 as *const [u8; 8]); - copy_nonoverlapping( - bytes.as_ptr().offset((8 - nbytes) as isize), - buf.as_mut_ptr(), - nbytes, - ); - } - } - - #[inline] - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { - assert!(pack_size128(n) <= nbytes && nbytes <= 16); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_be() as *const u128 as *const [u8; 16]); - copy_nonoverlapping( - bytes.as_ptr().offset((16 - nbytes) as isize), - buf.as_mut_ptr(), - nbytes, - ); - } - } - - #[inline] - fn read_u16_into(src: &[u8], dst: &mut [u16]) { - unsafe_read_slice!(src, dst, 2, to_be); - } - - #[inline] - fn read_u32_into(src: &[u8], dst: &mut [u32]) { - unsafe_read_slice!(src, dst, 4, to_be); - } - - #[inline] - fn read_u64_into(src: &[u8], dst: &mut [u64]) { - unsafe_read_slice!(src, dst, 8, to_be); - } - - #[inline] - fn read_u128_into(src: &[u8], dst: &mut [u128]) { - unsafe_read_slice!(src, dst, 16, to_be); - } - - #[inline] - fn write_u16_into(src: &[u16], dst: &mut [u8]) { - if cfg!(target_endian = "big") { - unsafe_write_slice_native!(src, dst, u16); - } else { - write_slice!(src, dst, u16, 2, Self::write_u16); - } - } - - #[inline] - fn write_u32_into(src: &[u32], dst: &mut [u8]) { - if cfg!(target_endian = "big") { - unsafe_write_slice_native!(src, dst, u32); - } else { - write_slice!(src, dst, u32, 4, Self::write_u32); - } - } - - #[inline] - fn write_u64_into(src: &[u64], dst: &mut [u8]) { - if cfg!(target_endian = "big") { - unsafe_write_slice_native!(src, dst, u64); - } else { - write_slice!(src, dst, u64, 8, Self::write_u64); - } - } - - #[inline] - fn write_u128_into(src: &[u128], dst: &mut [u8]) { - if cfg!(target_endian = "big") { - unsafe_write_slice_native!(src, dst, u128); - } else { - write_slice!(src, dst, u128, 16, Self::write_u128); - } - } - - #[inline] - fn from_slice_u16(numbers: &mut [u16]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u32(numbers: &mut [u32]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u64(numbers: &mut [u64]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u128(numbers: &mut [u128]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_f32(numbers: &mut [f32]) { - if cfg!(target_endian = "little") { - for n in numbers { - unsafe { - let int = *(n as *const f32 as *const u32); - *n = *(&int.to_be() as *const u32 as *const f32); - } - } - } - } - - #[inline] - fn from_slice_f64(numbers: &mut [f64]) { - if cfg!(target_endian = "little") { - for n in numbers { - unsafe { - let int = *(n as *const f64 as *const u64); - *n = *(&int.to_be() as *const u64 as *const f64); - } - } - } - } -} - -impl ByteOrder for LittleEndian { - #[inline] - fn read_u16(buf: &[u8]) -> u16 { - u16::from_le_bytes(buf[..2].try_into().unwrap()) - } - - #[inline] - fn read_u32(buf: &[u8]) -> u32 { - u32::from_le_bytes(buf[..4].try_into().unwrap()) - } - - #[inline] - fn read_u64(buf: &[u8]) -> u64 { - u64::from_le_bytes(buf[..8].try_into().unwrap()) - } - - #[inline] - fn read_u128(buf: &[u8]) -> u128 { - u128::from_le_bytes(buf[..16].try_into().unwrap()) - } - - #[inline] - fn read_uint(buf: &[u8], nbytes: usize) -> u64 { - assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len()); - let mut out = 0u64; - let ptr_out = &mut out as *mut u64 as *mut u8; - unsafe { - copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes); - } - out.to_le() - } - - #[inline] - fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { - assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len()); - let mut out: u128 = 0; - let ptr_out = &mut out as *mut u128 as *mut u8; - unsafe { - copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes); - } - out.to_le() - } - - #[inline] - fn write_u16(buf: &mut [u8], n: u16) { - unsafe_write_num_bytes!(u16, 2, n, buf, to_le); - } - - #[inline] - fn write_u32(buf: &mut [u8], n: u32) { - unsafe_write_num_bytes!(u32, 4, n, buf, to_le); - } - - #[inline] - fn write_u64(buf: &mut [u8], n: u64) { - unsafe_write_num_bytes!(u64, 8, n, buf, to_le); - } - - #[inline] - fn write_u128(buf: &mut [u8], n: u128) { - unsafe_write_num_bytes!(u128, 16, n, buf, to_le); - } - - #[inline] - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { - assert!(pack_size(n as u64) <= nbytes && nbytes <= 8); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_le() as *const u64 as *const [u8; 8]); - copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); - } - } - - #[inline] - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { - assert!(pack_size128(n as u128) <= nbytes && nbytes <= 16); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_le() as *const u128 as *const [u8; 16]); - copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); - } - } - - #[inline] - fn read_u16_into(src: &[u8], dst: &mut [u16]) { - unsafe_read_slice!(src, dst, 2, to_le); - } - - #[inline] - fn read_u32_into(src: &[u8], dst: &mut [u32]) { - unsafe_read_slice!(src, dst, 4, to_le); - } - - #[inline] - fn read_u64_into(src: &[u8], dst: &mut [u64]) { - unsafe_read_slice!(src, dst, 8, to_le); - } - - #[inline] - fn read_u128_into(src: &[u8], dst: &mut [u128]) { - unsafe_read_slice!(src, dst, 16, to_le); - } - - #[inline] - fn write_u16_into(src: &[u16], dst: &mut [u8]) { - if cfg!(target_endian = "little") { - unsafe_write_slice_native!(src, dst, u16); - } else { - write_slice!(src, dst, u16, 2, Self::write_u16); - } - } - - #[inline] - fn write_u32_into(src: &[u32], dst: &mut [u8]) { - if cfg!(target_endian = "little") { - unsafe_write_slice_native!(src, dst, u32); - } else { - write_slice!(src, dst, u32, 4, Self::write_u32); - } - } - - #[inline] - fn write_u64_into(src: &[u64], dst: &mut [u8]) { - if cfg!(target_endian = "little") { - unsafe_write_slice_native!(src, dst, u64); - } else { - write_slice!(src, dst, u64, 8, Self::write_u64); - } - } - - #[inline] - fn write_u128_into(src: &[u128], dst: &mut [u8]) { - if cfg!(target_endian = "little") { - unsafe_write_slice_native!(src, dst, u128); - } else { - write_slice!(src, dst, u128, 16, Self::write_u128); - } - } - - #[inline] - fn from_slice_u16(numbers: &mut [u16]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u32(numbers: &mut [u32]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u64(numbers: &mut [u64]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u128(numbers: &mut [u128]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_f32(numbers: &mut [f32]) { - if cfg!(target_endian = "big") { - for n in numbers { - unsafe { - let int = *(n as *const f32 as *const u32); - *n = *(&int.to_le() as *const u32 as *const f32); - } - } - } - } - - #[inline] - fn from_slice_f64(numbers: &mut [f64]) { - if cfg!(target_endian = "big") { - for n in numbers { - unsafe { - let int = *(n as *const f64 as *const u64); - *n = *(&int.to_le() as *const u64 as *const f64); - } - } - } - } -} - -#[cfg(test)] -mod test { - use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen, Testable}; - use rand::{thread_rng, Rng}; - - pub const U24_MAX: u32 = 16_777_215; - pub const I24_MAX: i32 = 8_388_607; - pub const U48_MAX: u64 = 281_474_976_710_655; - pub const I48_MAX: i64 = 140_737_488_355_327; - - pub const U64_MAX: u64 = ::core::u64::MAX; - pub const I64_MAX: u64 = ::core::i64::MAX as u64; - - macro_rules! calc_max { - ($max:expr, $bytes:expr) => { - calc_max!($max, $bytes, 8) - }; - ($max:expr, $bytes:expr, $maxbytes:expr) => { - ($max - 1) >> (8 * ($maxbytes - $bytes)) - }; - } - - #[derive(Clone, Debug)] - pub struct Wi128(pub T); - - impl Wi128 { - pub fn clone(&self) -> T { - self.0.clone() - } - } - - impl PartialEq for Wi128 { - fn eq(&self, other: &T) -> bool { - self.0.eq(other) - } - } - - impl Arbitrary for Wi128 { - fn arbitrary(gen: &mut G) -> Wi128 { - let max = calc_max!(::core::u128::MAX, gen.size(), 16); - let output = (gen.gen::() as u128) - | ((gen.gen::() as u128) << 64); - Wi128(output & (max - 1)) - } - } - - impl Arbitrary for Wi128 { - fn arbitrary(gen: &mut G) -> Wi128 { - let max = calc_max!(::core::i128::MAX, gen.size(), 16); - let output = (gen.gen::() as i128) - | ((gen.gen::() as i128) << 64); - Wi128(output & (max - 1)) - } - } - - pub fn qc_sized(f: A, size: u64) { - QuickCheck::new() - .gen(StdGen::new(thread_rng(), size as usize)) - .tests(1_00) - .max_tests(10_000) - .quickcheck(f); - } - - macro_rules! qc_byte_order { - ($name:ident, $ty_int:ty, $max:expr, - $bytes:expr, $read:ident, $write:ident) => { - mod $name { - #[allow(unused_imports)] - use super::{qc_sized, Wi128}; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - BigEndian::$write(&mut buf, n.clone(), $bytes); - n == BigEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - LittleEndian::$write(&mut buf, n.clone(), $bytes); - n == LittleEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - NativeEndian::$write(&mut buf, n.clone(), $bytes); - n == NativeEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - } - }; - ($name:ident, $ty_int:ty, $max:expr, - $read:ident, $write:ident) => { - mod $name { - #[allow(unused_imports)] - use super::{qc_sized, Wi128}; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use core::mem::size_of; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - BigEndian::$write(&mut buf[16 - bytes..], n.clone()); - n == BigEndian::$read(&buf[16 - bytes..]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - LittleEndian::$write(&mut buf[..bytes], n.clone()); - n == LittleEndian::$read(&buf[..bytes]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - NativeEndian::$write(&mut buf[..bytes], n.clone()); - n == NativeEndian::$read(&buf[..bytes]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - } - }; - } - - qc_byte_order!( - prop_u16, - u16, - ::core::u16::MAX as u64, - read_u16, - write_u16 - ); - qc_byte_order!( - prop_i16, - i16, - ::core::i16::MAX as u64, - read_i16, - write_i16 - ); - qc_byte_order!( - prop_u24, - u32, - crate::test::U24_MAX as u64, - read_u24, - write_u24 - ); - qc_byte_order!( - prop_i24, - i32, - crate::test::I24_MAX as u64, - read_i24, - write_i24 - ); - qc_byte_order!( - prop_u32, - u32, - ::core::u32::MAX as u64, - read_u32, - write_u32 - ); - qc_byte_order!( - prop_i32, - i32, - ::core::i32::MAX as u64, - read_i32, - write_i32 - ); - qc_byte_order!( - prop_u48, - u64, - crate::test::U48_MAX as u64, - read_u48, - write_u48 - ); - qc_byte_order!( - prop_i48, - i64, - crate::test::I48_MAX as u64, - read_i48, - write_i48 - ); - qc_byte_order!( - prop_u64, - u64, - ::core::u64::MAX as u64, - read_u64, - write_u64 - ); - qc_byte_order!( - prop_i64, - i64, - ::core::i64::MAX as u64, - read_i64, - write_i64 - ); - qc_byte_order!( - prop_f32, - f32, - ::core::u64::MAX as u64, - read_f32, - write_f32 - ); - qc_byte_order!( - prop_f64, - f64, - ::core::i64::MAX as u64, - read_f64, - write_f64 - ); - - qc_byte_order!(prop_u128, Wi128, 16 + 1, read_u128, write_u128); - qc_byte_order!(prop_i128, Wi128, 16 + 1, read_i128, write_i128); - - qc_byte_order!( - prop_uint_1, - u64, - calc_max!(super::U64_MAX, 1), - 1, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_2, - u64, - calc_max!(super::U64_MAX, 2), - 2, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_3, - u64, - calc_max!(super::U64_MAX, 3), - 3, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_4, - u64, - calc_max!(super::U64_MAX, 4), - 4, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_5, - u64, - calc_max!(super::U64_MAX, 5), - 5, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_6, - u64, - calc_max!(super::U64_MAX, 6), - 6, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_7, - u64, - calc_max!(super::U64_MAX, 7), - 7, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_8, - u64, - calc_max!(super::U64_MAX, 8), - 8, - read_uint, - write_uint - ); - - qc_byte_order!( - prop_uint128_1, - Wi128, - 1, - 1, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_2, - Wi128, - 2, - 2, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_3, - Wi128, - 3, - 3, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_4, - Wi128, - 4, - 4, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_5, - Wi128, - 5, - 5, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_6, - Wi128, - 6, - 6, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_7, - Wi128, - 7, - 7, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_8, - Wi128, - 8, - 8, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_9, - Wi128, - 9, - 9, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_10, - Wi128, - 10, - 10, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_11, - Wi128, - 11, - 11, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_12, - Wi128, - 12, - 12, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_13, - Wi128, - 13, - 13, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_14, - Wi128, - 14, - 14, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_15, - Wi128, - 15, - 15, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_16, - Wi128, - 16, - 16, - read_uint128, - write_uint128 - ); - - qc_byte_order!( - prop_int_1, - i64, - calc_max!(super::I64_MAX, 1), - 1, - read_int, - write_int - ); - qc_byte_order!( - prop_int_2, - i64, - calc_max!(super::I64_MAX, 2), - 2, - read_int, - write_int - ); - qc_byte_order!( - prop_int_3, - i64, - calc_max!(super::I64_MAX, 3), - 3, - read_int, - write_int - ); - qc_byte_order!( - prop_int_4, - i64, - calc_max!(super::I64_MAX, 4), - 4, - read_int, - write_int - ); - qc_byte_order!( - prop_int_5, - i64, - calc_max!(super::I64_MAX, 5), - 5, - read_int, - write_int - ); - qc_byte_order!( - prop_int_6, - i64, - calc_max!(super::I64_MAX, 6), - 6, - read_int, - write_int - ); - qc_byte_order!( - prop_int_7, - i64, - calc_max!(super::I64_MAX, 7), - 7, - read_int, - write_int - ); - qc_byte_order!( - prop_int_8, - i64, - calc_max!(super::I64_MAX, 8), - 8, - read_int, - write_int - ); - - qc_byte_order!( - prop_int128_1, - Wi128, - 1, - 1, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_2, - Wi128, - 2, - 2, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_3, - Wi128, - 3, - 3, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_4, - Wi128, - 4, - 4, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_5, - Wi128, - 5, - 5, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_6, - Wi128, - 6, - 6, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_7, - Wi128, - 7, - 7, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_8, - Wi128, - 8, - 8, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_9, - Wi128, - 9, - 9, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_10, - Wi128, - 10, - 10, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_11, - Wi128, - 11, - 11, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_12, - Wi128, - 12, - 12, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_13, - Wi128, - 13, - 13, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_14, - Wi128, - 14, - 14, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_15, - Wi128, - 15, - 15, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_16, - Wi128, - 16, - 16, - read_int128, - write_int128 - ); - - // Test that all of the byte conversion functions panic when given a - // buffer that is too small. - // - // These tests are critical to ensure safety, otherwise we might end up - // with a buffer overflow. - macro_rules! too_small { - ($name:ident, $maximally_small:expr, $zero:expr, - $read:ident, $write:ident) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let buf = [0; $maximally_small]; - BigEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let buf = [0; $maximally_small]; - LittleEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let buf = [0; $maximally_small]; - NativeEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn write_big_endian() { - let mut buf = [0; $maximally_small]; - BigEndian::$write(&mut buf, $zero); - } - - #[test] - #[should_panic] - fn write_little_endian() { - let mut buf = [0; $maximally_small]; - LittleEndian::$write(&mut buf, $zero); - } - - #[test] - #[should_panic] - fn write_native_endian() { - let mut buf = [0; $maximally_small]; - NativeEndian::$write(&mut buf, $zero); - } - } - }; - ($name:ident, $maximally_small:expr, $read:ident) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let buf = [0; $maximally_small]; - BigEndian::$read(&buf, $maximally_small + 1); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let buf = [0; $maximally_small]; - LittleEndian::$read(&buf, $maximally_small + 1); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let buf = [0; $maximally_small]; - NativeEndian::$read(&buf, $maximally_small + 1); - } - } - }; - } - - too_small!(small_u16, 1, 0, read_u16, write_u16); - too_small!(small_i16, 1, 0, read_i16, write_i16); - too_small!(small_u32, 3, 0, read_u32, write_u32); - too_small!(small_i32, 3, 0, read_i32, write_i32); - too_small!(small_u64, 7, 0, read_u64, write_u64); - too_small!(small_i64, 7, 0, read_i64, write_i64); - too_small!(small_f32, 3, 0.0, read_f32, write_f32); - too_small!(small_f64, 7, 0.0, read_f64, write_f64); - too_small!(small_u128, 15, 0, read_u128, write_u128); - too_small!(small_i128, 15, 0, read_i128, write_i128); - - too_small!(small_uint_1, 1, read_uint); - too_small!(small_uint_2, 2, read_uint); - too_small!(small_uint_3, 3, read_uint); - too_small!(small_uint_4, 4, read_uint); - too_small!(small_uint_5, 5, read_uint); - too_small!(small_uint_6, 6, read_uint); - too_small!(small_uint_7, 7, read_uint); - - too_small!(small_uint128_1, 1, read_uint128); - too_small!(small_uint128_2, 2, read_uint128); - too_small!(small_uint128_3, 3, read_uint128); - too_small!(small_uint128_4, 4, read_uint128); - too_small!(small_uint128_5, 5, read_uint128); - too_small!(small_uint128_6, 6, read_uint128); - too_small!(small_uint128_7, 7, read_uint128); - too_small!(small_uint128_8, 8, read_uint128); - too_small!(small_uint128_9, 9, read_uint128); - too_small!(small_uint128_10, 10, read_uint128); - too_small!(small_uint128_11, 11, read_uint128); - too_small!(small_uint128_12, 12, read_uint128); - too_small!(small_uint128_13, 13, read_uint128); - too_small!(small_uint128_14, 14, read_uint128); - too_small!(small_uint128_15, 15, read_uint128); - - too_small!(small_int_1, 1, read_int); - too_small!(small_int_2, 2, read_int); - too_small!(small_int_3, 3, read_int); - too_small!(small_int_4, 4, read_int); - too_small!(small_int_5, 5, read_int); - too_small!(small_int_6, 6, read_int); - too_small!(small_int_7, 7, read_int); - - too_small!(small_int128_1, 1, read_int128); - too_small!(small_int128_2, 2, read_int128); - too_small!(small_int128_3, 3, read_int128); - too_small!(small_int128_4, 4, read_int128); - too_small!(small_int128_5, 5, read_int128); - too_small!(small_int128_6, 6, read_int128); - too_small!(small_int128_7, 7, read_int128); - too_small!(small_int128_8, 8, read_int128); - too_small!(small_int128_9, 9, read_int128); - too_small!(small_int128_10, 10, read_int128); - too_small!(small_int128_11, 11, read_int128); - too_small!(small_int128_12, 12, read_int128); - too_small!(small_int128_13, 13, read_int128); - too_small!(small_int128_14, 14, read_int128); - too_small!(small_int128_15, 15, read_int128); - - // Test that reading/writing slices enforces the correct lengths. - macro_rules! slice_lengths { - ($name:ident, $read:ident, $write:ident, - $num_bytes:expr, $numbers:expr) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - BigEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - LittleEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - NativeEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn write_big_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - BigEndian::$write(&numbers, &mut bytes); - } - - #[test] - #[should_panic] - fn write_little_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - LittleEndian::$write(&numbers, &mut bytes); - } - - #[test] - #[should_panic] - fn write_native_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - NativeEndian::$write(&numbers, &mut bytes); - } - } - }; - } - - slice_lengths!( - slice_len_too_small_u16, - read_u16_into, - write_u16_into, - 3, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u16, - read_u16_into, - write_u16_into, - 5, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i16, - read_i16_into, - write_i16_into, - 3, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i16, - read_i16_into, - write_i16_into, - 5, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u32, - read_u32_into, - write_u32_into, - 7, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u32, - read_u32_into, - write_u32_into, - 9, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i32, - read_i32_into, - write_i32_into, - 7, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i32, - read_i32_into, - write_i32_into, - 9, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u64, - read_u64_into, - write_u64_into, - 15, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u64, - read_u64_into, - write_u64_into, - 17, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i64, - read_i64_into, - write_i64_into, - 15, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i64, - read_i64_into, - write_i64_into, - 17, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u128, - read_u128_into, - write_u128_into, - 31, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u128, - read_u128_into, - write_u128_into, - 33, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i128, - read_i128_into, - write_i128_into, - 31, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i128, - read_i128_into, - write_i128_into, - 33, - [0, 0] - ); - - #[test] - fn uint_bigger_buffer() { - use crate::{ByteOrder, LittleEndian}; - let n = LittleEndian::read_uint(&[1, 2, 3, 4, 5, 6, 7, 8], 5); - assert_eq!(n, 0x05_0403_0201); - } - - #[test] - fn regression173_array_impl() { - use crate::{BigEndian, ByteOrder, LittleEndian}; - - let xs = [0; 100]; - - let x = BigEndian::read_u16(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u32(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u64(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u128(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i16(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i32(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i64(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i128(&xs); - assert_eq!(x, 0); - - let x = LittleEndian::read_u16(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u32(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u64(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u128(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i16(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i32(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i64(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i128(&xs); - assert_eq!(x, 0); - } -} - -#[cfg(test)] -#[cfg(feature = "std")] -mod stdtests { - extern crate quickcheck; - extern crate rand; - - use self::quickcheck::{QuickCheck, StdGen, Testable}; - use self::rand::thread_rng; - - fn qc_unsized(f: A) { - QuickCheck::new() - .gen(StdGen::new(thread_rng(), 16)) - .tests(1_00) - .max_tests(10_000) - .quickcheck(f); - } - - macro_rules! calc_max { - ($max:expr, $bytes:expr) => { - ($max - 1) >> (8 * (8 - $bytes)) - }; - } - - macro_rules! qc_bytes_ext { - ($name:ident, $ty_int:ty, $max:expr, - $bytes:expr, $read:ident, $write:ident) => { - mod $name { - #[allow(unused_imports)] - use crate::test::{qc_sized, Wi128}; - use crate::{ - BigEndian, LittleEndian, NativeEndian, ReadBytesExt, - WriteBytesExt, - }; - use std::io::Cursor; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let offset = wtr.len() - $bytes; - let mut rdr = Cursor::new(&mut wtr[offset..]); - n == rdr.$read::($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let offset = if cfg!(target_endian = "big") { - wtr.len() - $bytes - } else { - 0 - }; - let mut rdr = Cursor::new(&mut wtr[offset..]); - n == rdr.$read::($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - } - }; - ($name:ident, $ty_int:ty, $max:expr, $read:ident, $write:ident) => { - mod $name { - #[allow(unused_imports)] - use crate::test::{qc_sized, Wi128}; - use crate::{ - BigEndian, LittleEndian, NativeEndian, ReadBytesExt, - WriteBytesExt, - }; - use std::io::Cursor; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - } - }; - } - - qc_bytes_ext!( - prop_ext_u16, - u16, - ::std::u16::MAX as u64, - read_u16, - write_u16 - ); - qc_bytes_ext!( - prop_ext_i16, - i16, - ::std::i16::MAX as u64, - read_i16, - write_i16 - ); - qc_bytes_ext!( - prop_ext_u32, - u32, - ::std::u32::MAX as u64, - read_u32, - write_u32 - ); - qc_bytes_ext!( - prop_ext_i32, - i32, - ::std::i32::MAX as u64, - read_i32, - write_i32 - ); - qc_bytes_ext!( - prop_ext_u64, - u64, - ::std::u64::MAX as u64, - read_u64, - write_u64 - ); - qc_bytes_ext!( - prop_ext_i64, - i64, - ::std::i64::MAX as u64, - read_i64, - write_i64 - ); - qc_bytes_ext!( - prop_ext_f32, - f32, - ::std::u64::MAX as u64, - read_f32, - write_f32 - ); - qc_bytes_ext!( - prop_ext_f64, - f64, - ::std::i64::MAX as u64, - read_f64, - write_f64 - ); - - qc_bytes_ext!(prop_ext_u128, Wi128, 16 + 1, read_u128, write_u128); - qc_bytes_ext!(prop_ext_i128, Wi128, 16 + 1, read_i128, write_i128); - - qc_bytes_ext!( - prop_ext_uint_1, - u64, - calc_max!(crate::test::U64_MAX, 1), - 1, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_2, - u64, - calc_max!(crate::test::U64_MAX, 2), - 2, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_3, - u64, - calc_max!(crate::test::U64_MAX, 3), - 3, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_4, - u64, - calc_max!(crate::test::U64_MAX, 4), - 4, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_5, - u64, - calc_max!(crate::test::U64_MAX, 5), - 5, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_6, - u64, - calc_max!(crate::test::U64_MAX, 6), - 6, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_7, - u64, - calc_max!(crate::test::U64_MAX, 7), - 7, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_8, - u64, - calc_max!(crate::test::U64_MAX, 8), - 8, - read_uint, - write_u64 - ); - - qc_bytes_ext!( - prop_ext_uint128_1, - Wi128, - 1, - 1, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_2, - Wi128, - 2, - 2, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_3, - Wi128, - 3, - 3, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_4, - Wi128, - 4, - 4, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_5, - Wi128, - 5, - 5, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_6, - Wi128, - 6, - 6, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_7, - Wi128, - 7, - 7, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_8, - Wi128, - 8, - 8, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_9, - Wi128, - 9, - 9, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_10, - Wi128, - 10, - 10, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_11, - Wi128, - 11, - 11, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_12, - Wi128, - 12, - 12, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_13, - Wi128, - 13, - 13, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_14, - Wi128, - 14, - 14, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_15, - Wi128, - 15, - 15, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_16, - Wi128, - 16, - 16, - read_uint128, - write_u128 - ); - - qc_bytes_ext!( - prop_ext_int_1, - i64, - calc_max!(crate::test::I64_MAX, 1), - 1, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_2, - i64, - calc_max!(crate::test::I64_MAX, 2), - 2, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_3, - i64, - calc_max!(crate::test::I64_MAX, 3), - 3, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_4, - i64, - calc_max!(crate::test::I64_MAX, 4), - 4, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_5, - i64, - calc_max!(crate::test::I64_MAX, 5), - 5, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_6, - i64, - calc_max!(crate::test::I64_MAX, 6), - 6, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_7, - i64, - calc_max!(crate::test::I64_MAX, 1), - 7, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_8, - i64, - calc_max!(crate::test::I64_MAX, 8), - 8, - read_int, - write_i64 - ); - - qc_bytes_ext!( - prop_ext_int128_1, - Wi128, - 1, - 1, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_2, - Wi128, - 2, - 2, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_3, - Wi128, - 3, - 3, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_4, - Wi128, - 4, - 4, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_5, - Wi128, - 5, - 5, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_6, - Wi128, - 6, - 6, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_7, - Wi128, - 7, - 7, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_8, - Wi128, - 8, - 8, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_9, - Wi128, - 9, - 9, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_10, - Wi128, - 10, - 10, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_11, - Wi128, - 11, - 11, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_12, - Wi128, - 12, - 12, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_13, - Wi128, - 13, - 13, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_14, - Wi128, - 14, - 14, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_15, - Wi128, - 15, - 15, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_16, - Wi128, - 16, - 16, - read_int128, - write_i128 - ); - - // Test slice serialization/deserialization. - macro_rules! qc_slice { - ($name:ident, $ty_int:ty, $read:ident, $write:ident, $zero:expr) => { - mod $name { - use super::qc_unsized; - #[allow(unused_imports)] - use crate::test::Wi128; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use core::mem::size_of; - - #[test] - fn big_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - BigEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - BigEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - - #[test] - fn little_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - LittleEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - LittleEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - - #[test] - fn native_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - NativeEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - NativeEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - } - }; - } - - qc_slice!(prop_slice_u16, u16, read_u16_into, write_u16_into, 0); - qc_slice!(prop_slice_i16, i16, read_i16_into, write_i16_into, 0); - qc_slice!(prop_slice_u32, u32, read_u32_into, write_u32_into, 0); - qc_slice!(prop_slice_i32, i32, read_i32_into, write_i32_into, 0); - qc_slice!(prop_slice_u64, u64, read_u64_into, write_u64_into, 0); - qc_slice!(prop_slice_i64, i64, read_i64_into, write_i64_into, 0); - qc_slice!( - prop_slice_u128, - Wi128, - read_u128_into, - write_u128_into, - 0 - ); - qc_slice!( - prop_slice_i128, - Wi128, - read_i128_into, - write_i128_into, - 0 - ); - - qc_slice!(prop_slice_f32, f32, read_f32_into, write_f32_into, 0.0); - qc_slice!(prop_slice_f64, f64, read_f64_into, write_f64_into, 0.0); -} diff --git a/vendor/camino/.cargo-checksum.json b/vendor/camino/.cargo-checksum.json index 1de1f0c97..81a1f0f60 100644 --- a/vendor/camino/.cargo-checksum.json +++ b/vendor/camino/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"886087c5abaa1078e179e173b997fd4bffd93e47b2914defd8148f3f396e98f0","CODE_OF_CONDUCT.md":"f51e207c2961ec061cac5c8aa9dd3098c3437de2c106d740c2aae90771bc0f86","Cargo.toml":"17bc7f765ef82a295aff4292261d23dc0c6c75b44e6c3016631cc087d5fe20f6","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"84762d717d0f2358c56f54ee46a6ca5f1582b7d3843f7a4d6e553ea04a57ca1b","build.rs":"4e46d73efd79ec269ddc1b2578cad051c66195225bfdf012e4ed430f9f98a3ab","clippy.toml":"818cba7332cc56b019d59e09805a3498f523da788f51454742905f1987c0b563","rustfmt.toml":"bf9776adb152b3fdc0d75c0929ede148c3e28c58f909a7d052865bc332e8958f","src/lib.rs":"a59a425a4bf1e2ae8f16bc0349fadf0fe3f7ec2effa44137bd59e17c3ff15456","src/proptest_impls.rs":"aa17bad810abe4a7b6c7a2c3163ae9749b03dd8bcef5043b0c4b9d00977f981c","src/serde_impls.rs":"eb7f00d1ceb7135506047dbefd7e6acee0364b5a9194111f49dbf2d1eb3661ac","src/tests.rs":"d6108c540dc93446b17d297b50372f799ef777c2cb0280fd37824a102ec24533","tests/integration_tests.rs":"b664a7555d2e5ac9ab71384e3ccfb73c01abe4c401f8de32e234c03b4d19d0f8"},"package":"869119e97797867fd90f5e22af7d0bd274bd4635ebb9eb68c04f3f513ae6c412"} \ No newline at end of file +{"files":{"CHANGELOG.md":"2530b12d7ddf3395bbc4c10557e57531498039ba28528b91ffc3f3deefc76f77","CODE_OF_CONDUCT.md":"f51e207c2961ec061cac5c8aa9dd3098c3437de2c106d740c2aae90771bc0f86","Cargo.toml":"7bf7de17ab10cd95aadf102f37c0b8a58f0c31f90cfeee81126ead8ad3cb0a26","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"84762d717d0f2358c56f54ee46a6ca5f1582b7d3843f7a4d6e553ea04a57ca1b","build.rs":"ca6914ad35e69842b6fba6e436d0417f39dbe6ee18694d4dd89b372d31cbf715","clippy.toml":"818cba7332cc56b019d59e09805a3498f523da788f51454742905f1987c0b563","rustfmt.toml":"bf9776adb152b3fdc0d75c0929ede148c3e28c58f909a7d052865bc332e8958f","src/lib.rs":"3a744ca7df473bb8bd97e1f4a961d517cb7379b8756e38893dd9d53a169c41e1","src/proptest_impls.rs":"aa17bad810abe4a7b6c7a2c3163ae9749b03dd8bcef5043b0c4b9d00977f981c","src/serde_impls.rs":"eb7f00d1ceb7135506047dbefd7e6acee0364b5a9194111f49dbf2d1eb3661ac","src/tests.rs":"d6108c540dc93446b17d297b50372f799ef777c2cb0280fd37824a102ec24533","tests/integration_tests.rs":"b664a7555d2e5ac9ab71384e3ccfb73c01abe4c401f8de32e234c03b4d19d0f8"},"package":"88ad0e1e3e88dd237a156ab9f571021b8a158caa0ae44b1968a241efb5144c1e"} \ No newline at end of file diff --git a/vendor/camino/CHANGELOG.md b/vendor/camino/CHANGELOG.md index b9a04de7a..67c2ea8d3 100644 --- a/vendor/camino/CHANGELOG.md +++ b/vendor/camino/CHANGELOG.md @@ -3,6 +3,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.1.1] - 2022-08-12 + +### Fixed + +- Fixed a build regression on older nightlies in the 1.63 series + ([#22](https://github.com/camino-rs/camino/issues/22)). +- Documentation fixes. + +## [1.1.0] - 2022-08-11 + +### Added + +- New methods, mirroring those in recent versions of Rust: + - `Utf8Path::try_exists` checks whether a path exists. Note that while `std::path::Path` only provides this method for Rust 1.58 and above, `camino` backfills the method for all Rust versions it supports. + - `Utf8PathBuf::shrink_to` shrinks a `Utf8PathBuf` to a given size. This was added in, and is gated on, Rust 1.56+. + - `Utf8PathBuf::try_reserve` and `Utf8PathBuf::try_reserve_exact` implement fallible allocations. These were added in, and are gated on, Rust 1.63+. +- A number of `#[must_use]` annotations to APIs, mirroring those added to `Path` and `PathBuf` in recent versions of Rust. The minor version bump is due to this change. + ## [1.0.9] - 2022-05-19 ### Fixed @@ -24,7 +42,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `Utf8Path::is_symlink` checks whether a path is a symlink. Note that while `std::path::Path` only - provides this method for version 1.58 and above, `camino` polyfills the method for all Rust versions + provides this method for version 1.58 and above, `camino` backfills the method for all Rust versions it supports. ### Changed @@ -83,6 +101,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Initial release. +[1.1.1]: https://github.com/camino-rs/camino/releases/tag/camino-1.1.1 +[1.1.0]: https://github.com/camino-rs/camino/releases/tag/camino-1.1.0 [1.0.9]: https://github.com/camino-rs/camino/releases/tag/camino-1.0.9 [1.0.8]: https://github.com/camino-rs/camino/releases/tag/camino-1.0.8 [1.0.7]: https://github.com/camino-rs/camino/releases/tag/camino-1.0.7 diff --git a/vendor/camino/Cargo.toml b/vendor/camino/Cargo.toml index cd2bd9fea..28c007855 100644 --- a/vendor/camino/Cargo.toml +++ b/vendor/camino/Cargo.toml @@ -12,7 +12,7 @@ [package] edition = "2018" name = "camino" -version = "1.0.9" +version = "1.1.1" authors = [ "Without Boats ", "Ashley Williams ", diff --git a/vendor/camino/build.rs b/vendor/camino/build.rs index bc3e4480d..7f5cbdf9b 100644 --- a/vendor/camino/build.rs +++ b/vendor/camino/build.rs @@ -21,10 +21,28 @@ fn main() { if compiler.minor >= 44 { println!("cargo:rustc-cfg=path_buf_capacity"); } + if compiler.minor >= 56 { + println!("cargo:rustc-cfg=shrink_to"); + } + // Stable and beta 1.63 have a stable try_reserve_2. + if (compiler.minor >= 63 + && (compiler.channel == ReleaseChannel::Stable || compiler.channel == ReleaseChannel::Beta)) + || compiler.minor >= 64 + { + println!("cargo:rustc-cfg=try_reserve_2"); + } } struct Compiler { minor: u32, + channel: ReleaseChannel, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ReleaseChannel { + Stable, + Beta, + Nightly, } fn rustc_version() -> Option { @@ -36,5 +54,12 @@ fn rustc_version() -> Option { return None; } let minor = pieces.next()?.parse().ok()?; - Some(Compiler { minor }) + let channel = if version.contains("nightly") { + ReleaseChannel::Nightly + } else if version.contains("beta") { + ReleaseChannel::Beta + } else { + ReleaseChannel::Stable + }; + Some(Compiler { minor, channel }) } diff --git a/vendor/camino/src/lib.rs b/vendor/camino/src/lib.rs index 4a1b6dfd7..fcfba3805 100644 --- a/vendor/camino/src/lib.rs +++ b/vendor/camino/src/lib.rs @@ -120,6 +120,7 @@ impl Utf8PathBuf { /// /// let path = Utf8PathBuf::new(); /// ``` + #[must_use] pub fn new() -> Utf8PathBuf { Utf8PathBuf(PathBuf::new()) } @@ -177,6 +178,7 @@ impl Utf8PathBuf { /// let new_utf8_path_buf = Utf8PathBuf::from_path_buf(std_path_buf).unwrap(); /// assert_eq!(new_utf8_path_buf, "foo.txt"); /// ``` + #[must_use = "`self` will be dropped if the result is not used"] pub fn into_std_path_buf(self) -> PathBuf { self.into() } @@ -202,6 +204,7 @@ impl Utf8PathBuf { /// /// [`with_capacity`]: PathBuf::with_capacity #[cfg(path_buf_capacity)] + #[must_use] pub fn with_capacity(capacity: usize) -> Utf8PathBuf { Utf8PathBuf(PathBuf::with_capacity(capacity)) } @@ -216,6 +219,7 @@ impl Utf8PathBuf { /// let p = Utf8PathBuf::from("/test"); /// assert_eq!(Utf8Path::new("/test"), p.as_path()); /// ``` + #[must_use] pub fn as_path(&self) -> &Utf8Path { // SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8 unsafe { Utf8Path::assume_utf8(&*self.0) } @@ -347,6 +351,7 @@ impl Utf8PathBuf { /// let s = p.into_string(); /// assert_eq!(s, "/the/head"); /// ``` + #[must_use = "`self` will be dropped if the result is not used"] pub fn into_string(self) -> String { self.into_os_string().into_string().unwrap() } @@ -363,11 +368,13 @@ impl Utf8PathBuf { /// let s = p.into_os_string(); /// assert_eq!(s, OsStr::new("/the/head")); /// ``` + #[must_use = "`self` will be dropped if the result is not used"] pub fn into_os_string(self) -> OsString { self.0.into_os_string() } /// Converts this `Utf8PathBuf` into a [boxed](Box) [`Utf8Path`]. + #[must_use = "`self` will be dropped if the result is not used"] pub fn into_boxed_path(self) -> Box { let ptr = Box::into_raw(self.0.into_boxed_path()) as *mut Utf8Path; // SAFETY: @@ -384,6 +391,7 @@ impl Utf8PathBuf { /// /// [`capacity`]: PathBuf::capacity #[cfg(path_buf_capacity)] + #[must_use] pub fn capacity(&self) -> usize { self.0.capacity() } @@ -408,6 +416,20 @@ impl Utf8PathBuf { self.0.reserve(additional) } + /// Invokes [`try_reserve`] on the underlying instance of [`PathBuf`]. + /// + /// *Requires Rust 1.63 or newer.* + /// + /// [`try_reserve`]: PathBuf::try_reserve + #[cfg(try_reserve_2)] + #[inline] + pub fn try_reserve( + &mut self, + additional: usize, + ) -> Result<(), std::collections::TryReserveError> { + self.0.try_reserve(additional) + } + /// Invokes [`reserve_exact`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* @@ -418,6 +440,20 @@ impl Utf8PathBuf { self.0.reserve_exact(additional) } + /// Invokes [`try_reserve_exact`] on the underlying instance of [`PathBuf`]. + /// + /// *Requires Rust 1.63 or newer.* + /// + /// [`try_reserve_exact`]: PathBuf::try_reserve_exact + #[cfg(try_reserve_2)] + #[inline] + pub fn try_reserve_exact( + &mut self, + additional: usize, + ) -> Result<(), std::collections::TryReserveError> { + self.0.try_reserve_exact(additional) + } + /// Invokes [`shrink_to_fit`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* @@ -427,6 +463,17 @@ impl Utf8PathBuf { pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit() } + + /// Invokes [`shrink_to`] on the underlying instance of [`PathBuf`]. + /// + /// *Requires Rust 1.56 or newer.* + /// + /// [`shrink_to`]: PathBuf::shrink_to + #[cfg(shrink_to)] + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.0.shrink_to(min_capacity) + } } impl Deref for Utf8PathBuf { @@ -586,6 +633,7 @@ impl Utf8Path { /// ``` /// /// [`str`]: str + #[must_use] pub fn as_str(&self) -> &str { // SAFETY: every Utf8Path constructor ensures that self is valid UTF-8 unsafe { assume_utf8(self.as_os_str()) } @@ -601,6 +649,7 @@ impl Utf8Path { /// let os_str = Utf8Path::new("foo.txt").as_os_str(); /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); /// ``` + #[must_use] pub fn as_os_str(&self) -> &OsStr { self.0.as_os_str() } @@ -615,6 +664,8 @@ impl Utf8Path { /// let path_buf = Utf8Path::new("foo.txt").to_path_buf(); /// assert_eq!(path_buf, Utf8PathBuf::from("foo.txt")); /// ``` + #[must_use = "this returns the result of the operation, \ + without modifying the original"] pub fn to_path_buf(&self) -> Utf8PathBuf { Utf8PathBuf(self.0.to_path_buf()) } @@ -637,6 +688,7 @@ impl Utf8Path { /// ``` /// /// [`has_root`]: Utf8Path::has_root + #[must_use] pub fn is_absolute(&self) -> bool { self.0.is_absolute() } @@ -654,6 +706,7 @@ impl Utf8Path { /// ``` /// /// [`is_absolute`]: Utf8Path::is_absolute + #[must_use] pub fn is_relative(&self) -> bool { self.0.is_relative() } @@ -674,6 +727,7 @@ impl Utf8Path { /// /// assert!(Utf8Path::new("/etc/passwd").has_root()); /// ``` + #[must_use] pub fn has_root(&self) -> bool { self.0.has_root() } @@ -695,6 +749,7 @@ impl Utf8Path { /// assert_eq!(grand_parent, Utf8Path::new("/")); /// assert_eq!(grand_parent.parent(), None); /// ``` + #[must_use] pub fn parent(&self) -> Option<&Utf8Path> { self.0.parent().map(|path| { // SAFETY: self is valid UTF-8, so parent is valid UTF-8 as well @@ -753,6 +808,7 @@ impl Utf8Path { /// assert_eq!(None, Utf8Path::new("foo.txt/..").file_name()); /// assert_eq!(None, Utf8Path::new("/").file_name()); /// ``` + #[must_use] pub fn file_name(&self) -> Option<&str> { self.0.file_name().map(|s| { // SAFETY: self is valid UTF-8, so file_name is valid UTF-8 as well @@ -818,6 +874,7 @@ impl Utf8Path { /// /// assert!(!Utf8Path::new("/etc/foo.rs").starts_with("/etc/foo")); /// ``` + #[must_use] pub fn starts_with(&self, base: impl AsRef) -> bool { self.0.starts_with(base) } @@ -840,6 +897,7 @@ impl Utf8Path { /// assert!(!path.ends_with("/resolv.conf")); /// assert!(!path.ends_with("conf")); // use .extension() instead /// ``` + #[must_use] pub fn ends_with(&self, base: impl AsRef) -> bool { self.0.ends_with(base) } @@ -863,6 +921,7 @@ impl Utf8Path { /// assert_eq!("foo", Utf8Path::new("foo.rs").file_stem().unwrap()); /// assert_eq!("foo.tar", Utf8Path::new("foo.tar.gz").file_stem().unwrap()); /// ``` + #[must_use] pub fn file_stem(&self) -> Option<&str> { self.0.file_stem().map(|s| { // SAFETY: self is valid UTF-8, so file_stem is valid UTF-8 as well @@ -889,6 +948,7 @@ impl Utf8Path { /// assert_eq!("rs", Utf8Path::new("foo.rs").extension().unwrap()); /// assert_eq!("gz", Utf8Path::new("foo.tar.gz").extension().unwrap()); /// ``` + #[must_use] pub fn extension(&self) -> Option<&str> { self.0.extension().map(|s| { // SAFETY: self is valid UTF-8, so extension is valid UTF-8 as well @@ -907,6 +967,7 @@ impl Utf8Path { /// /// assert_eq!(Utf8Path::new("/etc").join("passwd"), Utf8PathBuf::from("/etc/passwd")); /// ``` + #[must_use] pub fn join(&self, path: impl AsRef) -> Utf8PathBuf { Utf8PathBuf(self.0.join(&path.as_ref().0)) } @@ -923,6 +984,7 @@ impl Utf8Path { /// /// assert_eq!(Utf8Path::new("/etc").join_os("passwd"), PathBuf::from("/etc/passwd")); /// ``` + #[must_use] pub fn join_os(&self, path: impl AsRef) -> PathBuf { self.0.join(path) } @@ -942,6 +1004,7 @@ impl Utf8Path { /// let path = Utf8Path::new("/tmp"); /// assert_eq!(path.with_file_name("var"), Utf8PathBuf::from("/var")); /// ``` + #[must_use] pub fn with_file_name(&self, file_name: impl AsRef) -> Utf8PathBuf { Utf8PathBuf(self.0.with_file_name(file_name.as_ref())) } @@ -1223,6 +1286,9 @@ impl Utf8Path { /// Returns `true` if the path points at an existing entity. /// + /// Warning: this method may be error-prone, consider using [`try_exists()`] instead! + /// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs. + /// /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// @@ -1240,10 +1306,51 @@ impl Utf8Path { /// /// This is a convenience function that coerces errors to false. If you want to /// check errors, call [`fs::metadata`]. + /// + /// [`try_exists()`]: Self::try_exists + #[must_use] pub fn exists(&self) -> bool { self.0.exists() } + /// Returns `Ok(true)` if the path points at an existing entity. + /// + /// This function will traverse symbolic links to query information about the + /// destination file. In case of broken symbolic links this will return `Ok(false)`. + /// + /// As opposed to the [`exists()`] method, this one doesn't silently ignore errors + /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission + /// denied on some of the parent directories.) + /// + /// Note that while this avoids some pitfalls of the `exists()` method, it still can not + /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios + /// where those bugs are not an issue. + /// + /// # Examples + /// + /// ```no_run + /// use camino::Utf8Path; + /// assert!(!Utf8Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt")); + /// assert!(Utf8Path::new("/root/secret_file.txt").try_exists().is_err()); + /// ``` + /// + /// [`exists()`]: Self::exists + #[inline] + pub fn try_exists(&self) -> io::Result { + // Note: this block is written this way rather than with a pattern guard to appease Rust + // 1.34. + match fs::metadata(self) { + Ok(_) => Ok(true), + Err(error) => { + if error.kind() == io::ErrorKind::NotFound { + Ok(false) + } else { + Err(error) + } + } + } + } + /// Returns `true` if the path exists on disk and is pointing at a regular file. /// /// This function will traverse symbolic links to query information about the @@ -1271,6 +1378,7 @@ impl Utf8Path { /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on /// a Unix-like system for example. See [`fs::File::open`] or /// [`fs::OpenOptions::open`] for more information. + #[must_use] pub fn is_file(&self) -> bool { self.0.is_file() } @@ -1296,6 +1404,7 @@ impl Utf8Path { /// This is a convenience function that coerces errors to false. If you want to /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call /// [`fs::Metadata::is_dir`] if it was [`Ok`]. + #[must_use] pub fn is_dir(&self) -> bool { self.0.is_dir() } @@ -1334,6 +1443,7 @@ impl Utf8Path { } /// Converts a `Box` into a [`Utf8PathBuf`] without copying or allocating. + #[must_use = "`self` will be dropped if the result is not used"] pub fn into_path_buf(self: Box) -> Utf8PathBuf { let ptr = Box::into_raw(self) as *mut Path; // SAFETY: @@ -1397,6 +1507,7 @@ impl fmt::Debug for Utf8Path { /// /// [`ancestors`]: Utf8Path::ancestors #[derive(Copy, Clone)] +#[must_use = "iterators are lazy and do nothing unless consumed"] #[repr(transparent)] pub struct Utf8Ancestors<'a>(Ancestors<'a>); @@ -1439,6 +1550,7 @@ impl<'a> FusedIterator for Utf8Ancestors<'a> {} /// /// [`components`]: Utf8Path::components #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)] +#[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Utf8Components<'a>(Components<'a>); impl<'a> Utf8Components<'a> { @@ -1455,6 +1567,7 @@ impl<'a> Utf8Components<'a> { /// /// assert_eq!(Utf8Path::new("foo/bar.txt"), components.as_path()); /// ``` + #[must_use] pub fn as_path(&self) -> &'a Utf8Path { // SAFETY: Utf8Components was constructed from a Utf8Path, so it is guaranteed to be valid // UTF-8 @@ -1523,6 +1636,7 @@ impl AsRef for Utf8Components<'_> { /// /// [`iter`]: Utf8Path::iter #[derive(Clone)] +#[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Iter<'a> { inner: Utf8Components<'a>, } @@ -1557,6 +1671,7 @@ impl<'a> Iter<'a> { /// /// assert_eq!(Utf8Path::new("foo/bar.txt"), iter.as_path()); /// ``` + #[must_use] pub fn as_path(&self) -> &'a Utf8Path { self.inner.as_path() } @@ -1674,6 +1789,7 @@ impl<'a> Utf8Component<'a> { /// let components: Vec<_> = path.components().map(|comp| comp.as_str()).collect(); /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]); /// ``` + #[must_use] pub fn as_str(&self) -> &'a str { // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 @@ -1691,6 +1807,7 @@ impl<'a> Utf8Component<'a> { /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect(); /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]); /// ``` + #[must_use] pub fn as_os_str(&self) -> &'a OsStr { match *self { Utf8Component::Prefix(prefix) => prefix.as_os_str(), @@ -1821,6 +1938,7 @@ impl<'a> Utf8Prefix<'a> { /// assert!(!UNC("server", "share").is_verbatim()); /// assert!(!Disk(b'C').is_verbatim()); /// ``` + #[must_use] pub fn is_verbatim(&self) -> bool { use Utf8Prefix::*; match self { @@ -1872,6 +1990,7 @@ impl<'a> Utf8PrefixComponent<'a> { /// /// See [`Utf8Prefix`]'s documentation for more information on the different /// kinds of prefixes. + #[must_use] pub fn kind(&self) -> Utf8Prefix<'a> { // SAFETY for all the below unsafe blocks: the path self was originally constructed from was // UTF-8 so any parts of it are valid UTF-8 @@ -1894,6 +2013,7 @@ impl<'a> Utf8PrefixComponent<'a> { } /// Returns the [`str`] slice for this prefix. + #[must_use] pub fn as_str(&self) -> &'a str { // SAFETY: Utf8PrefixComponent was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 @@ -1901,6 +2021,7 @@ impl<'a> Utf8PrefixComponent<'a> { } /// Returns the raw [`OsStr`] slice for this prefix. + #[must_use] pub fn as_os_str(&self) -> &'a OsStr { self.0.as_os_str() } @@ -2596,6 +2717,7 @@ impl<'a> IntoIterator for &'a Utf8Path { macro_rules! impl_cmp { ($lhs:ty, $rhs: ty) => { + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { @@ -2603,6 +2725,7 @@ macro_rules! impl_cmp { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { @@ -2610,6 +2733,7 @@ macro_rules! impl_cmp { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { @@ -2617,6 +2741,7 @@ macro_rules! impl_cmp { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { @@ -2634,6 +2759,7 @@ impl_cmp!(Cow<'a, Utf8Path>, Utf8PathBuf); macro_rules! impl_cmp_std_path { ($lhs:ty, $rhs: ty) => { + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { @@ -2641,6 +2767,7 @@ macro_rules! impl_cmp_std_path { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { @@ -2648,6 +2775,7 @@ macro_rules! impl_cmp_std_path { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { @@ -2655,6 +2783,7 @@ macro_rules! impl_cmp_std_path { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { @@ -2679,6 +2808,7 @@ impl_cmp_std_path!(&'a Utf8Path, PathBuf); macro_rules! impl_cmp_str { ($lhs:ty, $rhs: ty) => { + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { @@ -2686,6 +2816,7 @@ macro_rules! impl_cmp_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { @@ -2693,6 +2824,7 @@ macro_rules! impl_cmp_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { @@ -2700,6 +2832,7 @@ macro_rules! impl_cmp_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { @@ -2724,6 +2857,7 @@ impl_cmp_str!(&'a Utf8Path, String); macro_rules! impl_cmp_os_str { ($lhs:ty, $rhs: ty) => { + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { @@ -2731,6 +2865,7 @@ macro_rules! impl_cmp_os_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { @@ -2738,6 +2873,7 @@ macro_rules! impl_cmp_os_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { @@ -2745,6 +2881,7 @@ macro_rules! impl_cmp_os_str { } } + #[allow(clippy::extra_unused_lifetimes)] impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { diff --git a/vendor/clap-3.2.20/.cargo-checksum.json b/vendor/clap-3.2.20/.cargo-checksum.json new file mode 100644 index 000000000..22fa24875 --- /dev/null +++ b/vendor/clap-3.2.20/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"60560d6b2bec73734ebea64f8b916cbe9361e672157119801ba0e2f89334453c","Cargo.toml":"5def59eada2aa1a035cb39b38da4ba02baec2dd9271e4ef16731a8ef06c4d58f","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"0d687e1f07b58fe68bda74668ff6326125e5e5efa184cce755cd84ac535b7058","README.md":"ee049ee3ccab683cd3fa7c980db71c22ed8577378433cad5a93c1bc2a9dbe20f","examples/cargo-example-derive.md":"8305e66dd56619ec3a1d116951c893965cc8435574f5bf8baea923492357c626","examples/cargo-example-derive.rs":"a94003c9fadd1a11c35616ea4e5132c768bad08650e207848e1de56bffd86c8f","examples/cargo-example.md":"b7e51be8f05538ae39ce232ef12c873af81ab5abb5740c079d09b7cdd27a3b71","examples/cargo-example.rs":"be19a1ccb9d91882d76e7553f692ef89fa2a7acbbc1500232ce9fb60b6e8a85b","examples/demo.md":"9db305e9ff333f5e783dcc3142683280816d7bc111a57e9dcc4127f07ca44055","examples/demo.rs":"8a18ab15a235b84efd82017e51a891ed2df5f0154adbfce2806dcac089296b64","examples/derive_ref/augment_args.rs":"93fa1e122328a5d12ca4f921d17902dff6ec47b69fb2140124e2a00809ec4a1a","examples/derive_ref/augment_subcommands.rs":"5535f8ca1893101acb5eba8edc311497431ff9aa26f62f1d9743bdc147bef7a4","examples/derive_ref/custom-bool.md":"d92e441199c7584d4b888c45124366cc4802ec8ea67cdcbb3423ffaa3c5268ac","examples/derive_ref/custom-bool.rs":"f88e9c68d2447a24bc98e05124fea17836155f32cff30a2b8a03ad254383247c","examples/derive_ref/flatten_hand_args.rs":"abdb4e55b0cb71e5c4d14fe20ae0930df6888b2dca01225a02d3c6828bcbc791","examples/derive_ref/hand_subcommand.rs":"1a5464b9c5791361930b5591adeb6fcf6f14b83abdfa6443d2c80bcf0c097b3e","examples/derive_ref/interop_tests.md":"3a357e82cfc155f71e0348be33f78295aa77839c3e3a5b7c1783cbd1259e6a61","examples/escaped-positional-derive.md":"64329a454ad399cfde7cae37c2419fb68f1dfcdf2b7d809e113bab69c5f9b947","examples/escaped-positional-derive.rs":"68b0b474509d0d0b19a2ad756c15a18a9d3b30278390ddf1b7bc11b40fe5f937","examples/escaped-positional.md":"a8259da128ad7ad1f898527bb9e3c1c55541fdc2a59a8599fcddbe9cf58a3563","examples/escaped-positional.rs":"ca33f37267df8de835eeb5817e906a957e96c4ee9bd95b97abee3af25639f3c2","examples/git-derive.md":"280909b56757f102cad3a3274a92c884a0cec4e698c0f8718d2edee73fbbd810","examples/git-derive.rs":"2e8310364f2622b1b11c916643dda7392ec4a4fd585f30d537672d2fed48ea6e","examples/git.md":"31c172433b05ce581179aaba10d610de5cf097b0da894f1330a0437ef332feab","examples/git.rs":"9da386531604fc2afbd375685e213200ad10e34100ec92b4bfa6fb5730283aa1","examples/multicall-busybox.md":"0e07a2f79f94daf4586db85bf207b4bd8f0653b59858d6b4f0b66956a5b2178f","examples/multicall-busybox.rs":"709f71a82295a539d0a239371d35d1eeb517eaa3bb0a4db406bb7e5d3541a4a5","examples/multicall-hostname.md":"b547e42135269ab1e8be8dea4da6a4e99dfaa006a320fa319198d5934e1e97ab","examples/multicall-hostname.rs":"cc58a924dd2e57281f36e30481a1cbc8186952adbf149f9e1e13f9c673614fd9","examples/pacman.md":"c91e1582caf8a2cdeca208c856d1ede3f3ff26948b288a98ef69ea695f12f555","examples/pacman.rs":"f249824b950e1c34fae37afe04389143a037452a1f699c215172ac20e0285984","examples/repl.rs":"d50c1da634c237b26989994b1efa6fd1a087874a82d1fc8c1863be4ea8deaa8c","examples/tutorial_builder/01_quick.md":"80878c8630e0ecf7bb172c2645c2c17480ca5a37e5f4f481ab99e88d3a37da8e","examples/tutorial_builder/01_quick.rs":"c19b165fce9468fb3c9d3d9354a2b9829ceea7ffba6b7134d4941a6e986429a9","examples/tutorial_builder/02_app_settings.md":"f0f7b48afa7a97c9270f9d63a0e9e0f3117733ee0201639eae2199a4aca4944e","examples/tutorial_builder/02_app_settings.rs":"dd770d131726c3f37e202c9b10c969cc4eba90249c54a05594535cea6efe2749","examples/tutorial_builder/02_apps.md":"815a9197925d403b1d93969ace87e80e32667333fa83f2c86abcbdfa17cf0d7e","examples/tutorial_builder/02_apps.rs":"a7016469d10259ae0025fb6ad5b9d3c732cf082869348005d4774d2bb0722d2d","examples/tutorial_builder/02_crate.md":"086581912b34d305bb7cf3c5a35238c151bd366fac4c0923057883253731c250","examples/tutorial_builder/02_crate.rs":"2742c6a3f1946b89b4f1146893e126d68e1cf55ad4130fb94105091900421273","examples/tutorial_builder/03_01_flag_bool.md":"068378b1e76ce624dd0153dfaa9a7ae2d1a84205b1e169f5f1a16bebd50715cf","examples/tutorial_builder/03_01_flag_bool.rs":"d49b30b527faa6a383b334e572d546fab5c4b298a5549842073ab42a33a05c94","examples/tutorial_builder/03_01_flag_count.md":"8d62fbef076eac962a1d0082afa4916de22277aee973d693de33e9fd73b16669","examples/tutorial_builder/03_01_flag_count.rs":"2bfaac3aa9bcbbf37e18e74a40d966391e208d44b45a1e9c4ab61d22fd14dd40","examples/tutorial_builder/03_02_option.md":"585793524138da00c25b9fdd883b25eb8addfaf8742365d84cde63169a9289a7","examples/tutorial_builder/03_02_option.rs":"ce43934605e0438f1e8706e5e970cfcd930f76c4ebee02450ffc63de520994bd","examples/tutorial_builder/03_03_positional.md":"46fe5085841342243efd9614e80db7db3c52ae5af7c6cdd402b569d310e63fe9","examples/tutorial_builder/03_03_positional.rs":"fc7538d0fe8501c56070f0f22be699f128890636aa4ff8478cd6c7beeea279da","examples/tutorial_builder/03_04_subcommands.md":"fc5a92c5290b3cc119a6421779cdd8f4791465a1d3f50f4f29ccb08f3063a6f5","examples/tutorial_builder/03_04_subcommands.rs":"a309a332004edbed6dc14b64b1ba6cc0cd42871f3c5b8da7daab772764839c68","examples/tutorial_builder/03_05_default_values.md":"431800610a29d9a5587b74b30d709e67af5a0b8980900de20e5876fb9491144c","examples/tutorial_builder/03_05_default_values.rs":"b277be9cfe5d87958f9cf2e8a178bb007b070723528bedc8b81163aedb3a2880","examples/tutorial_builder/04_01_enum.md":"d1310efc5c8acb5ca9c86b57deebbcbd8766869284d2e8ea51e32b3eeac38439","examples/tutorial_builder/04_01_enum.rs":"596aa44bc401674a4ccf091b81b2df79b911dbb01d61fd167fd270d1e21a3609","examples/tutorial_builder/04_01_possible.md":"308cd6530b3c389bf2a82b2b66ad33025be230d84d94835273af35a90eb6a753","examples/tutorial_builder/04_01_possible.rs":"3d781b26d257061b55a957744c2dbd99c1d2346c151230fb18fe5f576d19585c","examples/tutorial_builder/04_02_parse.md":"ea14a355913fd7a8af5aac4be2bdecfda72c039b62ccadfb91ff8d39a447955e","examples/tutorial_builder/04_02_parse.rs":"a65f596341e65f41d555b38a6f5e22a5e03aac6faa4e8b3e3c85fa0e0935a2d7","examples/tutorial_builder/04_02_validate.md":"7536f4fb1a11ab94e54b6b98b7364c77912b7600803aeda5988c5b29f3f037c8","examples/tutorial_builder/04_02_validate.rs":"af6d9f748c6956aaa1006ce96834e0d013a9dbfb6d0acc63df5eb63caac56eef","examples/tutorial_builder/04_03_relations.md":"ffc6b8a2d606856fbb6cce677c5280e08eaffbe6a4c8e40cd68ce35959370ed7","examples/tutorial_builder/04_03_relations.rs":"a2dbb6d77587f64775ef57c4bb3869a2760e5c124e2870898bbf1191ef349b99","examples/tutorial_builder/04_04_custom.md":"d562fd072b5d91e8ea145771a2b6eb0284d3d21bfac707ba48ee00e92d76ad2d","examples/tutorial_builder/04_04_custom.rs":"ea0879629da2dab2d2e7fd25bdde53386d863a3e2d468e7ea306a6f8240a5522","examples/tutorial_builder/05_01_assert.rs":"69fc5a3d330be1f90055f886d65684204d7f0585459f362cf3c43b5caf4bbd7b","examples/tutorial_derive/01_quick.md":"1416029b09409468ba6b39ae5f91c41547f7f389c2534961f867ab17260638da","examples/tutorial_derive/01_quick.rs":"e17262c915199c4507d8950d5eafb73f3047e09b6dee2abbfe9f82ebf1b7ddd5","examples/tutorial_derive/02_app_settings.md":"3f4a81ebc7b674482768763bab70acf9bc31f68cc3ecb118c6f5493feaff3d42","examples/tutorial_derive/02_app_settings.rs":"7e81f4c1640b0bfbd87aedd3eda79ae7c47c669dee79b643b35e54c1dc076ee8","examples/tutorial_derive/02_apps.md":"27d22d45e438f60b346d34508a75783871e0fe9b1ae41ec759e56118a10feff7","examples/tutorial_derive/02_apps.rs":"e8cd02b5983b2203f1585b96858fade4cedfb124e366171d6b21fcb3f05b514e","examples/tutorial_derive/02_crate.md":"eb396e17db1dd68eb7689bcd806b63dbfe01ad48dfc12c285f00c42e1d4b8c1f","examples/tutorial_derive/02_crate.rs":"0b12a0790d23cee1e5d275893f428cc0af36d5532c2af00806e64c18ef9d309c","examples/tutorial_derive/03_01_flag_bool.md":"f6dd5ab050f0f1ac5924949a4ba45f248b2d4b1bd77210d78b9d8e9b3395d111","examples/tutorial_derive/03_01_flag_bool.rs":"07c31218d0332d7437d80e19c7e3c7be711bf0f56bee3ffb1c4d6f7f253b9304","examples/tutorial_derive/03_01_flag_count.md":"74d5c8a79581ceb7e6a11ec20ae59fa8c7f42591e10464aad50bbdd3d06916fc","examples/tutorial_derive/03_01_flag_count.rs":"945be42994845145b9c579b3834f8c6375f239293ded84fba35754bbe9fdcf9b","examples/tutorial_derive/03_02_option.md":"034b65008d05c1598fe3c1918f23d654d7a14cb610dd636a3c649d9d7a3b1559","examples/tutorial_derive/03_02_option.rs":"48be4cf49b498173200ad86d5d3cd64ce9381f86fdaaab70f05fc471f64a2185","examples/tutorial_derive/03_03_positional.md":"14f6b36eee218a38733b534e7b621f68a6f799bd96682a82980cba9f6e99a40e","examples/tutorial_derive/03_03_positional.rs":"f368ab1465ee4d84b84d175b97af6f64ce0676bec2482adef3ce966d2d8de26a","examples/tutorial_derive/03_04_subcommands.md":"3e1870fb10c78a01b63903060b1164f3f4d0e51c052e449abe11e2d06c252811","examples/tutorial_derive/03_04_subcommands.rs":"b25c8aec8f3816923b1154be91caafe0c2d2841fc1af5f0ef048f03d1273879e","examples/tutorial_derive/03_04_subcommands_alt.rs":"7ba6e81c2af6085b7e2721254500b34ee3e8622e20790b3c6f2786e165151b70","examples/tutorial_derive/03_05_default_values.md":"9ac52230ba7d9c214dcb64922cbf161970947d9650e8e7ea8d0ee949eba99c0e","examples/tutorial_derive/03_05_default_values.rs":"0ba14153a3c72a2435ac3688b990171a1670eb3f2f7cef21886732e489fad435","examples/tutorial_derive/04_01_enum.md":"ee57dc12a88a560d70f344629ac79cc497f96e967e97b4c643467747c8075172","examples/tutorial_derive/04_01_enum.rs":"d30abd8570357be26871c06939dee8173d34408250b6bdc3b1e76f1cbc06f888","examples/tutorial_derive/04_02_parse.md":"f191e6c77e6b133f78bd1123cec2b09c8dfe8bb17198d6348e26adade7465daf","examples/tutorial_derive/04_02_parse.rs":"fbb23ef2d98d3cb401cec9dd29d5818e4c189cc9f54fe961a2fbd08632a9634c","examples/tutorial_derive/04_02_validate.md":"c88670017d06261d454818ff18f21a06275f35d564e637c5346ce3b7fca8a02b","examples/tutorial_derive/04_02_validate.rs":"87d9c465f912b69e5839ea87404a221a39421404012c1a7fd6e327b03ceb12f0","examples/tutorial_derive/04_03_relations.md":"5657bbeee193f21a312db682cfa216f1001a94ace024c56a959985feb2e29069","examples/tutorial_derive/04_03_relations.rs":"eb8e737733261d3d1b7f4def7a05c37ba7c1c010357c7de33ee42c8adfdf6dc2","examples/tutorial_derive/04_04_custom.md":"9627d0025c5c063682387d8e00b3fb097114d1431c1ce8808038be34f781576a","examples/tutorial_derive/04_04_custom.rs":"0e745c6dab0881c62190e82e01409b70cf3286dd0983db4a612f1be88fdd1a8d","examples/tutorial_derive/05_01_assert.rs":"653450ff2e528f29b6b31d979fd7da094ea8e74b8b61a4657935c9ac2efbc28e","examples/typed-derive.md":"c22bb8da2e294f1d3725624e0c442713e5f263b10a2ee76a22ffa07f89af735a","examples/typed-derive.rs":"1c88bb1c8cec4e2e7a452552fa52675d96ffd6f201f5384b4e98d0a70fce1e4c","src/_cookbook/cargo_example.rs":"fe7594a5233e9106a159aa1f5d5f0cde0d844356f630d55c78b8ef322327d4e5","src/_cookbook/cargo_example_derive":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/_cookbook/cargo_example_derive.rs":"badf3e931ef5d5b7f5addc4912aca057ba83ee6302c43d7eeecd1661673fd407","src/_cookbook/escaped_positional.rs":"2789d8fea126355805b29e76b52c6cea4982565014087a46e0d48e4ddfbed7ab","src/_cookbook/escaped_positional_derive.rs":"802d0b672f4ed48152235d4a26a64c97fa921b361177bdd3a1a33cbac96f665d","src/_cookbook/git.rs":"372977252a22fc776e3acaa4629e964114ccd6a49b8ef334d2b6646f12e8b5ee","src/_cookbook/git_derive.rs":"4ab7c0197efda06607ca60c2a85ea743aed3494f5fe9e408d935ea0500a345fc","src/_cookbook/mod.rs":"34c53c6273512976676a82dded921f8d99e0312dd3e823ae1549606754625827","src/_cookbook/multicall_busybox.rs":"56176b4fa15e7a39c433706971d4e68aaf26ddc2a5790078b6dbe722ee13efee","src/_cookbook/multicall_hostname.rs":"907f8decf81ea4d4cbf81639ea4cd2f925eda64d4831454a7656369b65522780","src/_cookbook/pacman.rs":"863125b2d3d7931a9e4541c8ab1242b8bfcb421d8b5c604ea681efd805f68da7","src/_cookbook/repl.rs":"1393209b2cc5c203296d57c5a065b764b4318be7855e48baf16de851e250cf90","src/_cookbook/typed_derive.rs":"3d28e78cd0b068b4fcb32a7fea6244de176f2fe75dfcb59e99c33b66a7ae4864","src/_derive/_tutorial.rs":"237d316ad5f9838dc011283e454afce24d47bf2e9c5038ba5402bafeb2959090","src/_derive/mod.rs":"7f1f6b59332044681324f0753dfb51641e52f46dee74a21b8c94a413bc06be02","src/_faq.rs":"06d10de865ae34305fa973db9b00dc31f54e0f63f8fe039805aa371c36a796b9","src/_features.rs":"bbcbf1b256136d20f89e4f8a16ff37b04f07dfee0d2d4f2b013f445467628032","src/_tutorial.rs":"e7c7359b6b6c86cf6e18f4bdc3c90ce440b82bf07ce304ca2e127fb2a04cbf9f","src/bin/stdio-fixture.rs":"e8f10afbfe1857bcf986d2f55be0ca19a50c905d9f650c6e1fd42dbacf219b04","src/builder/action.rs":"beab4d8dca6337dfd64f387ee3198a88a6dcb71ec94f5bbbfe6bb4c0175ab9ee","src/builder/app_settings.rs":"17b094a5c044b2387467706bade1b19b5703bf99fc5081ac9508f410f871a1f2","src/builder/arg.rs":"e7120b60bf72d2572fc1f325b377a32da9ece4d7ac00b4a580a0f6a42c08ea8a","src/builder/arg_group.rs":"263d9c79e03015fe4e2fab4616fc73089be60fb2ec17aa2a06f3d6a24740432c","src/builder/arg_predicate.rs":"8c9fd14780cd42465f32f2e8927b97c06e686d09b5927ba3cd5bbd792af7a13d","src/builder/arg_settings.rs":"b7966dfea529a1be1164ca2d76494b1712cb2f73b024d2a23307dcd473933887","src/builder/command.rs":"57f0076465feb3cf6a0a16610b345fae8dbde8d248e4ef94111a27051c40789b","src/builder/debug_asserts.rs":"d1d5adc82cb8269445b2ef197f1e566f61e7f13d6a24afaad928e45e95aed170","src/builder/macros.rs":"904e42e72c49107ae324f45d5df24fbff13b9c7d4589f1a4ae38594add704434","src/builder/mod.rs":"205367cb5ba5d5ba7894091535ce3a5dd23b35fd436e003196d89523e7705566","src/builder/possible_value.rs":"62268b9da9eec8f4d1904ebfbd3a288fb78cfa71c357efadced28f0378bcfb93","src/builder/regex.rs":"b18891310186ecdcca9bb611833b7188cc80fe72e9fef27b63fa076b880a1acb","src/builder/tests.rs":"995c7d6be608b94c6f392f1356eba0cb8adb9ca661ffeebf7ebe6e8ad01a868c","src/builder/usage_parser.rs":"91d1af89196116aac2c0fb021f42f43f954aa3252df264e19a02a0cf5911d16b","src/builder/value_hint.rs":"0dd974d495c313430898d28b79991a70983c9aa44e88fa9aa1776d3308935438","src/builder/value_parser.rs":"64bb7f4808bdf65f30cb434198038a06db556e5ca045d900da392cc1a3186896","src/derive.rs":"11eaddc27a06229322a6bbce4458cb1424e6a5805c79166cba342c2905093b51","src/error/context.rs":"1dc561c7877d7f9b90f04bb7915744f0b3cc4ac2aa928ae100b2825a97077142","src/error/kind.rs":"3b4f9dfe5be5843cec8380c8f8965dcb9d0beee0aaa02cadf8dcffd400626ede","src/error/mod.rs":"e5b60fee401975d95c460c2567d09e17972eaae336154a8b90d9c806083f63fa","src/lib.rs":"4a197eab3f447c58a266af4f9a787af5c98b18f4612f33d9189cce52f4f9de18","src/macros.rs":"72585e32051a6872bbb29e39f7e9f9a88334a03f39ec3c768984db2f38211001","src/mkeymap.rs":"3565a5bae5d6cdcf8ba41a24eb602c510a14e150c4a6d3085ad72a35778e9c5f","src/output/fmt.rs":"efb741b5854500d946c6c09763ece1badc2b9cd3efa616cb58012039836c2b7f","src/output/help.rs":"ebdd123d6b70279c25af4b08432b547498834853adf99821ff6c6cd65dd87d4e","src/output/mod.rs":"3a61f89a4568e95114a3ab839da8f3c4c92de2a228549308f5d1be076a474917","src/output/usage.rs":"1921d2fa362f111b3f9613fc98eb5e24686483fe112b337855da7eb17b643f71","src/parser/arg_matcher.rs":"0c9ae639ed241e8ff1f62cd9e5eab2de9e5db1be0e86f58d5d94619d6dad05fd","src/parser/error.rs":"51e8fbd7cc73bba78cca50417e9b4fb25e11eefc60ff4b957940176bdb995e5c","src/parser/features/mod.rs":"6ed075e97af56bff22f22ed1ee83ff6479360e05f9d3661a3145f822c242b694","src/parser/features/suggestions.rs":"79127956b2f1adb9d658925e2779ebebfe9ddea434408762fefb60afdb545f47","src/parser/matches/any_value.rs":"7b6e711fe205e8808394c562dd6a260b56ce350cf9298a308ba9727ab012b664","src/parser/matches/arg_matches.rs":"666e3640b5347aba5806fc15b5caa599b171e684ee15d933ddc7f8185a0d2032","src/parser/matches/matched_arg.rs":"fb12eb2afaf631bb60aa8c4e42b0f510a877d35a9eaa07a7afd253280c27c251","src/parser/matches/mod.rs":"1467aa752cb1c79d30e4aeaaa55e10a0bb9dcf6f3980496234251431c79c49e6","src/parser/matches/value_source.rs":"e6a477ae36f2f7155960239a97b7d142eef4eb227c41c9eefea147289547d713","src/parser/mod.rs":"358f46d3b7f43dec2563d4c35bd2536fab2491f28e300a9bcdeaf6ca0513ce12","src/parser/parser.rs":"9e338dfd60aa8bfbcfbbda15c73d4722767a4d2e7b8f8ed3a07c296ddd98762c","src/parser/validator.rs":"30066cb41ab23800231fb6b028cbce57d118570859659ebc67affbe5226f31f9","src/util/color.rs":"63df5e1cda1001b4c536dc0b04e09dd85dae6d317e34e660abbe3c71e17eaa29","src/util/fnv.rs":"82492d91d990f38b62de8b3c3e67f1fad55919117b1f448aa28acf6d21919fd7","src/util/graph.rs":"f35396b6e2a427377dcbbca69b1b98737d89684a3834cfda98cbf8cc70ff9c2f","src/util/id.rs":"fc498c65887385d92a51359a2f72556c2e508ee49b8cac4b3f827512795d690d","src/util/mod.rs":"8d328a15ef06989d0ce5e65cf3b7ec79c083984b25c0b31ba177bdb22df28a10","src/util/str_to_bool.rs":"1ce90b4939a884eeefc73392722bdfcf906e3070c4398e1557c586c10c684cd0"},"package":"23b71c3ce99b7611011217b366d923f1d0a7e07a92bb2dbf1e84508c673ca3bd"} \ No newline at end of file diff --git a/vendor/clap-3.2.20/Cargo.lock b/vendor/clap-3.2.20/Cargo.lock new file mode 100644 index 000000000..57d007104 --- /dev/null +++ b/vendor/clap-3.2.20/Cargo.lock @@ -0,0 +1,746 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bytes" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0b3de4a0c5e67e16066a0715723abd91edc2f9001d09c46e1dca929351e130e" + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "3.2.20" +dependencies = [ + "atty", + "backtrace", + "bitflags", + "clap_derive", + "clap_lex", + "humantime", + "indexmap", + "once_cell", + "regex", + "rustversion", + "shlex", + "snapbox", + "static_assertions", + "strsim", + "termcolor", + "terminal_size", + "textwrap", + "trybuild", + "trycmd", + "unicase", + "yaml-rust", +] + +[[package]] +name = "clap_derive" +version = "3.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "combine" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a604e93b79d1808327a6fca85a6f2d69de66461e7620f5a4cbf5fb4d1d7c948" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concolor" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "015267563b1df20adccdd00cb05257b1dfbea70a04928e9cf88ffb850c1a40af" +dependencies = [ + "atty", + "bitflags", + "concolor-query", +] + +[[package]] +name = "concolor-query" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6417fe6fc03a8b533fd2177742eeb39a90c7233eedec7bac96d4d6b69a09449" + +[[package]] +name = "crossbeam-channel" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c02a4d71819009c192cf4872265391563fd6a84c81ff2c0f2a7026ca4c1d85c" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07db9d94cbd326813772c968ccd25999e5f8ae22f4f8d1b11effa37ef6ce281d" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "memoffset", + "once_cell", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d82ee10ce34d7bc12c2122495e7593a9c41347ecdd64185af4ecf72cb1a7f83" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "either" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f107b87b6afc2a64fd13cac55fe06d6c8859f12d4b14cbcdd2c67d0976781be" + +[[package]] +name = "escargot" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5584ba17d7ab26a8a7284f13e5bd196294dd2f2d79773cff29b9e9edef601a6" +dependencies = [ + "log", + "once_cell", + "serde", + "serde_json", +] + +[[package]] +name = "gimli" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "indexmap" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "itertools" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" + +[[package]] +name = "libc" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" +dependencies = [ + "adler", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" + +[[package]] +name = "os_pipe" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c92f2b54f081d635c77e7120862d48db8e91f7f21cef23ab1b4fe9971c59f55" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rayon" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "regex" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" + +[[package]] +name = "rustc-demangle" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" + +[[package]] +name = "rustversion" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24c8ad4f0c00e1eb5bc7614d236a7f1300e3dbd76b68cac8e06fb00b015ad8d8" + +[[package]] +name = "ryu" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "serde" +version = "1.0.139" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0171ebb889e45aa68b44aee0859b3eede84c6f5f5c228e6f140c0b2a0a46cad6" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.139" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1d3230c1de7932af58ad8ffbe1d784bd55efd5a9d84ac24f69c72d83543dfb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82c2c1fdcd807d1098552c5b9a36e425e42e9fbd7c6a37a8425f390f781f7fa7" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" + +[[package]] +name = "similar" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e24979f63a11545f5f2c60141afe249d4f19f84581ea2138065e400941d83d3" + +[[package]] +name = "snapbox" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "767a1d5da232b6959cd1bd5c9e8db8a7cce09c3038e89deedb49a549a2aefd93" +dependencies = [ + "concolor", + "normalize-line-endings", + "os_pipe", + "similar", + "snapbox-macros", + "wait-timeout", + "yansi", +] + +[[package]] +name = "snapbox-macros" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c01dea7e04cbb27ef4c86e9922184608185f7cd95c1763bc30d727cda4a5e930" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "terminal_size" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "textwrap" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" +dependencies = [ + "terminal_size", + "unicode-width", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5376256e44f2443f8896ac012507c19a012df0fe8758b55246ae51a2279db51f" +dependencies = [ + "combine", + "indexmap", + "itertools", + "serde", +] + +[[package]] +name = "trybuild" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "764b9e244b482a9b81bde596aa37aa6f1347bf8007adab25e59f901b32b4e0a0" +dependencies = [ + "glob", + "once_cell", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "trycmd" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb4185126cc904642173a54c185083f410c86d1202ada6761aacf7c40829f13" +dependencies = [ + "escargot", + "glob", + "humantime", + "humantime-serde", + "rayon", + "serde", + "shlex", + "snapbox", + "toml_edit", +] + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-ident" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" diff --git a/vendor/clap-3.2.20/Cargo.toml b/vendor/clap-3.2.20/Cargo.toml new file mode 100644 index 000000000..197454c07 --- /dev/null +++ b/vendor/clap-3.2.20/Cargo.toml @@ -0,0 +1,471 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.56.1" +name = "clap" +version = "3.2.20" +include = [ + "build.rs", + "src/**/*", + "Cargo.toml", + "LICENSE*", + "README.md", + "benches/**/*", + "examples/**/*", +] +description = "A simple to use, efficient, and full-featured Command Line Argument Parser" +readme = "README.md" +keywords = [ + "argument", + "cli", + "arg", + "parser", + "parse", +] +categories = ["command-line-interface"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/clap-rs/clap" +resolver = "2" + +[package.metadata.docs.rs] +features = ["unstable-doc"] +rustdoc-args = [ + "--cfg", + "docsrs", +] +cargo-args = [ + "-Zunstable-options", + "-Zrustdoc-scrape-examples=examples", +] + +[package.metadata.playground] +features = ["unstable-doc"] + +[package.metadata.release] +shared-version = true +tag-name = "v{{version}}" + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "Unreleased" +replace = "{{version}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = '\.\.\.HEAD' +replace = "...{{tag_name}}" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "ReleaseDate" +replace = "{{date}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "" +replace = """ + +## [Unreleased] - ReleaseDate +""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "" +replace = """ + +[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" +exactly = 1 + +[profile.bench] +lto = true +codegen-units = 1 + +[profile.test] +opt-level = 1 + +[lib] +bench = false + +[[example]] +name = "demo" +required-features = ["derive"] + +[[example]] +name = "cargo-example" +required-features = ["cargo"] + +[[example]] +name = "cargo-example-derive" +required-features = ["derive"] + +[[example]] +name = "escaped-positional" +required-features = ["cargo"] + +[[example]] +name = "escaped-positional-derive" +required-features = ["derive"] + +[[example]] +name = "git-derive" +required-features = ["derive"] + +[[example]] +name = "typed-derive" +required-features = ["derive"] + +[[example]] +name = "busybox" +path = "examples/multicall-busybox.rs" + +[[example]] +name = "hostname" +path = "examples/multicall-hostname.rs" + +[[example]] +name = "repl" +path = "examples/repl.rs" + +[[example]] +name = "01_quick" +path = "examples/tutorial_builder/01_quick.rs" +required-features = ["cargo"] + +[[example]] +name = "02_apps" +path = "examples/tutorial_builder/02_apps.rs" + +[[example]] +name = "02_crate" +path = "examples/tutorial_builder/02_crate.rs" +required-features = ["cargo"] + +[[example]] +name = "02_app_settings" +path = "examples/tutorial_builder/02_app_settings.rs" +required-features = ["cargo"] + +[[example]] +name = "03_01_flag_bool" +path = "examples/tutorial_builder/03_01_flag_bool.rs" +required-features = ["cargo"] + +[[example]] +name = "03_01_flag_count" +path = "examples/tutorial_builder/03_01_flag_count.rs" +required-features = ["cargo"] + +[[example]] +name = "03_02_option" +path = "examples/tutorial_builder/03_02_option.rs" +required-features = ["cargo"] + +[[example]] +name = "03_03_positional" +path = "examples/tutorial_builder/03_03_positional.rs" +required-features = ["cargo"] + +[[example]] +name = "03_04_subcommands" +path = "examples/tutorial_builder/03_04_subcommands.rs" +required-features = ["cargo"] + +[[example]] +name = "03_05_default_values" +path = "examples/tutorial_builder/03_05_default_values.rs" +required-features = ["cargo"] + +[[example]] +name = "04_01_possible" +path = "examples/tutorial_builder/04_01_possible.rs" +required-features = ["cargo"] + +[[example]] +name = "04_01_enum" +path = "examples/tutorial_builder/04_01_enum.rs" +required-features = ["cargo"] + +[[example]] +name = "04_02_parse" +path = "examples/tutorial_builder/04_02_parse.rs" +required-features = ["cargo"] + +[[example]] +name = "04_02_validate" +path = "examples/tutorial_builder/04_02_validate.rs" +required-features = ["cargo"] + +[[example]] +name = "04_03_relations" +path = "examples/tutorial_builder/04_03_relations.rs" +required-features = ["cargo"] + +[[example]] +name = "04_04_custom" +path = "examples/tutorial_builder/04_04_custom.rs" +required-features = ["cargo"] + +[[example]] +name = "05_01_assert" +path = "examples/tutorial_builder/05_01_assert.rs" +test = true +required-features = ["cargo"] + +[[example]] +name = "01_quick_derive" +path = "examples/tutorial_derive/01_quick.rs" +required-features = ["derive"] + +[[example]] +name = "02_apps_derive" +path = "examples/tutorial_derive/02_apps.rs" +required-features = ["derive"] + +[[example]] +name = "02_crate_derive" +path = "examples/tutorial_derive/02_crate.rs" +required-features = ["derive"] + +[[example]] +name = "02_app_settings_derive" +path = "examples/tutorial_derive/02_app_settings.rs" +required-features = ["derive"] + +[[example]] +name = "03_01_flag_bool_derive" +path = "examples/tutorial_derive/03_01_flag_bool.rs" +required-features = ["derive"] + +[[example]] +name = "03_01_flag_count_derive" +path = "examples/tutorial_derive/03_01_flag_count.rs" +required-features = ["derive"] + +[[example]] +name = "03_02_option_derive" +path = "examples/tutorial_derive/03_02_option.rs" +required-features = ["derive"] + +[[example]] +name = "03_03_positional_derive" +path = "examples/tutorial_derive/03_03_positional.rs" +required-features = ["derive"] + +[[example]] +name = "03_04_subcommands_derive" +path = "examples/tutorial_derive/03_04_subcommands.rs" +required-features = ["derive"] + +[[example]] +name = "03_04_subcommands_alt_derive" +path = "examples/tutorial_derive/03_04_subcommands_alt.rs" +required-features = ["derive"] + +[[example]] +name = "03_05_default_values_derive" +path = "examples/tutorial_derive/03_05_default_values.rs" +required-features = ["derive"] + +[[example]] +name = "04_01_enum_derive" +path = "examples/tutorial_derive/04_01_enum.rs" +required-features = ["derive"] + +[[example]] +name = "04_02_parse_derive" +path = "examples/tutorial_derive/04_02_parse.rs" +required-features = ["derive"] + +[[example]] +name = "04_02_validate_derive" +path = "examples/tutorial_derive/04_02_validate.rs" +required-features = ["derive"] + +[[example]] +name = "04_03_relations_derive" +path = "examples/tutorial_derive/04_03_relations.rs" +required-features = ["derive"] + +[[example]] +name = "04_04_custom_derive" +path = "examples/tutorial_derive/04_04_custom.rs" +required-features = ["derive"] + +[[example]] +name = "05_01_assert_derive" +path = "examples/tutorial_derive/05_01_assert.rs" +test = true +required-features = ["derive"] + +[[example]] +name = "custom-bool" +path = "examples/derive_ref/custom-bool.rs" +required-features = ["derive"] + +[[example]] +name = "interop_augment_args" +path = "examples/derive_ref/augment_args.rs" +required-features = ["derive"] + +[[example]] +name = "interop_augment_subcommands" +path = "examples/derive_ref/augment_subcommands.rs" +required-features = ["derive"] + +[[example]] +name = "interop_hand_subcommand" +path = "examples/derive_ref/hand_subcommand.rs" +required-features = ["derive"] + +[[example]] +name = "interop_flatten_hand_args" +path = "examples/derive_ref/flatten_hand_args.rs" +required-features = ["derive"] + +[dependencies.atty] +version = "0.2" +optional = true + +[dependencies.backtrace] +version = "0.3" +optional = true + +[dependencies.bitflags] +version = "1.2" + +[dependencies.clap_derive] +version = "=3.2.18" +optional = true + +[dependencies.clap_lex] +version = "0.2.2" + +[dependencies.indexmap] +version = "1.0" + +[dependencies.once_cell] +version = "1.12.0" +optional = true + +[dependencies.regex] +version = "1.0" +optional = true + +[dependencies.strsim] +version = "0.10" +optional = true + +[dependencies.termcolor] +version = "1.1.1" +optional = true + +[dependencies.terminal_size] +version = "0.1.12" +optional = true + +[dependencies.textwrap] +version = "0.15.0" +features = [] +default-features = false + +[dependencies.unicase] +version = "2.6" +optional = true + +[dependencies.yaml-rust] +version = "0.4.1" +optional = true + +[dev-dependencies.humantime] +version = "2" + +[dev-dependencies.regex] +version = "1.0" + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.shlex] +version = "1.1.0" + +[dev-dependencies.snapbox] +version = "0.2.9" + +[dev-dependencies.static_assertions] +version = "1.1.0" + +[dev-dependencies.trybuild] +version = "1.0.18" + +[dev-dependencies.trycmd] +version = "0.13" +features = [ + "color-auto", + "diff", + "examples", +] +default-features = false + +[features] +cargo = ["once_cell"] +color = [ + "atty", + "termcolor", +] +debug = [ + "clap_derive/debug", + "backtrace", +] +default = [ + "std", + "color", + "suggestions", +] +deprecated = ["clap_derive/deprecated"] +derive = [ + "clap_derive", + "once_cell", +] +env = [] +std = ["indexmap/std"] +suggestions = ["strsim"] +unicode = [ + "textwrap/unicode-width", + "unicase", +] +unstable-doc = [ + "derive", + "cargo", + "wrap_help", + "yaml", + "env", + "unicode", + "regex", + "unstable-replace", + "unstable-grouped", +] +unstable-grouped = [] +unstable-replace = [] +unstable-v4 = [ + "clap_derive/unstable-v4", + "deprecated", +] +wrap_help = [ + "terminal_size", + "textwrap/terminal_size", +] +yaml = ["yaml-rust"] diff --git a/vendor/clap-3.2.20/LICENSE-APACHE b/vendor/clap-3.2.20/LICENSE-APACHE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/clap-3.2.20/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/clap-3.2.20/LICENSE-MIT b/vendor/clap-3.2.20/LICENSE-MIT new file mode 100644 index 000000000..7b05b8453 --- /dev/null +++ b/vendor/clap-3.2.20/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2022 Kevin B. Knapp and Clap Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/clap-3.2.20/README.md b/vendor/clap-3.2.20/README.md new file mode 100644 index 000000000..eea6ba6f0 --- /dev/null +++ b/vendor/clap-3.2.20/README.md @@ -0,0 +1,43 @@ +# clap + +> **Command Line Argument Parser for Rust** + +[![Crates.io](https://img.shields.io/crates/v/clap?style=flat-square)](https://crates.io/crates/clap) +[![Crates.io](https://img.shields.io/crates/d/clap?style=flat-square)](https://crates.io/crates/clap) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE-MIT) +[![Build Status](https://img.shields.io/github/workflow/status/clap-rs/clap/CI/staging?style=flat-square)](https://github.com/clap-rs/clap/actions/workflows/ci.yml?query=branch%3Astaging) +[![Coverage Status](https://img.shields.io/coveralls/github/clap-rs/clap/master?style=flat-square)](https://coveralls.io/github/clap-rs/clap?branch=master) +[![Contributors](https://img.shields.io/github/contributors/clap-rs/clap?style=flat-square)](https://github.com/clap-rs/clap/graphs/contributors) + +Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). + +## About + +Create your command-line parser, with all of the bells and whistles, declaratively or procedurally. + +For more details, see: +- [docs.rs](https://docs.rs/clap/latest/clap/) +- [examples](examples/) + +## Sponsors + + +### Gold + +[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Silver + +[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Bronze + +[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Backer + +[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) diff --git a/vendor/clap-3.2.20/examples/cargo-example-derive.md b/vendor/clap-3.2.20/examples/cargo-example-derive.md new file mode 100644 index 000000000..2c7a11b88 --- /dev/null +++ b/vendor/clap-3.2.20/examples/cargo-example-derive.md @@ -0,0 +1,43 @@ +For more on creating a custom subcommand, see [the cargo +book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). +The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in +mimicking cargo's interface. + +The help looks like: +```console +$ cargo-example-derive --help +cargo + +USAGE: + cargo + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + example-derive A simple to use, efficient, and full-featured Command Line Argument Parser + help Print this message or the help of the given subcommand(s) + +$ cargo-example-derive example-derive --help +cargo-example-derive [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + cargo example-derive [OPTIONS] + +OPTIONS: + -h, --help Print help information + --manifest-path + -V, --version Print version information + +``` + +Then to directly invoke the command, run: +```console +$ cargo-example-derive example-derive +None + +$ cargo-example-derive example-derive --manifest-path Cargo.toml +Some("Cargo.toml") + +``` diff --git a/vendor/clap-3.2.20/examples/cargo-example-derive.rs b/vendor/clap-3.2.20/examples/cargo-example-derive.rs new file mode 100644 index 000000000..f0aad29c7 --- /dev/null +++ b/vendor/clap-3.2.20/examples/cargo-example-derive.rs @@ -0,0 +1,20 @@ +use clap::Parser; + +#[derive(Parser)] // requires `derive` feature +#[clap(name = "cargo")] +#[clap(bin_name = "cargo")] +enum Cargo { + ExampleDerive(ExampleDerive), +} + +#[derive(clap::Args)] +#[clap(author, version, about, long_about = None)] +struct ExampleDerive { + #[clap(long, value_parser)] + manifest_path: Option, +} + +fn main() { + let Cargo::ExampleDerive(args) = Cargo::parse(); + println!("{:?}", args.manifest_path); +} diff --git a/vendor/clap-3.2.20/examples/cargo-example.md b/vendor/clap-3.2.20/examples/cargo-example.md new file mode 100644 index 000000000..6fb6a3c4d --- /dev/null +++ b/vendor/clap-3.2.20/examples/cargo-example.md @@ -0,0 +1,43 @@ +For more on creating a custom subcommand, see [the cargo +book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). +The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in +mimicking cargo's interface. + +The help looks like: +```console +$ cargo-example --help +cargo + +USAGE: + cargo + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + example A simple to use, efficient, and full-featured Command Line Argument Parser + help Print this message or the help of the given subcommand(s) + +$ cargo-example example --help +cargo-example [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + cargo example [OPTIONS] + +OPTIONS: + -h, --help Print help information + --manifest-path + -V, --version Print version information + +``` + +Then to directly invoke the command, run: +```console +$ cargo-example example +None + +$ cargo-example example --manifest-path Cargo.toml +Some("Cargo.toml") + +``` diff --git a/vendor/clap-3.2.20/examples/cargo-example.rs b/vendor/clap-3.2.20/examples/cargo-example.rs new file mode 100644 index 000000000..d9a909f4f --- /dev/null +++ b/vendor/clap-3.2.20/examples/cargo-example.rs @@ -0,0 +1,19 @@ +fn main() { + let cmd = clap::Command::new("cargo") + .bin_name("cargo") + .subcommand_required(true) + .subcommand( + clap::command!("example").arg( + clap::arg!(--"manifest-path" ) + .required(false) + .value_parser(clap::value_parser!(std::path::PathBuf)), + ), + ); + let matches = cmd.get_matches(); + let matches = match matches.subcommand() { + Some(("example", matches)) => matches, + _ => unreachable!("clap should ensure we don't get here"), + }; + let manifest_path = matches.get_one::("manifest-path"); + println!("{:?}", manifest_path); +} diff --git a/vendor/clap-3.2.20/examples/demo.md b/vendor/clap-3.2.20/examples/demo.md new file mode 100644 index 000000000..93ee49c37 --- /dev/null +++ b/vendor/clap-3.2.20/examples/demo.md @@ -0,0 +1,19 @@ +```console +$ demo --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + demo[EXE] [OPTIONS] --name + +OPTIONS: + -c, --count Number of times to greet [default: 1] + -h, --help Print help information + -n, --name Name of the person to greet + -V, --version Print version information + +$ demo --name Me +Hello Me! + +``` +*(version number and `.exe` extension on windows replaced by placeholders)* diff --git a/vendor/clap-3.2.20/examples/demo.rs b/vendor/clap-3.2.20/examples/demo.rs new file mode 100644 index 000000000..a7cecfb0c --- /dev/null +++ b/vendor/clap-3.2.20/examples/demo.rs @@ -0,0 +1,22 @@ +use clap::Parser; + +/// Simple program to greet a person +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Name of the person to greet + #[clap(short, long, value_parser)] + name: String, + + /// Number of times to greet + #[clap(short, long, value_parser, default_value_t = 1)] + count: u8, +} + +fn main() { + let args = Args::parse(); + + for _ in 0..args.count { + println!("Hello {}!", args.name) + } +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/augment_args.rs b/vendor/clap-3.2.20/examples/derive_ref/augment_args.rs new file mode 100644 index 000000000..310556914 --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/augment_args.rs @@ -0,0 +1,27 @@ +use clap::{arg, Args, Command, FromArgMatches as _}; + +#[derive(Args, Debug)] +struct DerivedArgs { + #[clap(short, long, action)] + derived: bool, +} + +fn main() { + let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue)); + // Augment built args with derived args + let cli = DerivedArgs::augment_args(cli); + + let matches = cli.get_matches(); + println!("Value of built: {:?}", matches.get_flag("built")); + println!( + "Value of derived via ArgMatches: {:?}", + matches.get_flag("derived") + ); + + // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches. + // This is the main benefit of using derived arguments. + let derived_matches = DerivedArgs::from_arg_matches(&matches) + .map_err(|err| err.exit()) + .unwrap(); + println!("Value of derived: {:#?}", derived_matches); +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/augment_subcommands.rs b/vendor/clap-3.2.20/examples/derive_ref/augment_subcommands.rs new file mode 100644 index 000000000..199da98b4 --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/augment_subcommands.rs @@ -0,0 +1,21 @@ +use clap::{Command, FromArgMatches as _, Parser, Subcommand as _}; + +#[derive(Parser, Debug)] +enum Subcommands { + Derived { + #[clap(short, long, action)] + derived_flag: bool, + }, +} + +fn main() { + let cli = Command::new("Built CLI"); + // Augment with derived subcommands + let cli = Subcommands::augment_subcommands(cli); + + let matches = cli.get_matches(); + let derived_subcommands = Subcommands::from_arg_matches(&matches) + .map_err(|err| err.exit()) + .unwrap(); + println!("Derived subcommands: {:#?}", derived_subcommands); +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/custom-bool.md b/vendor/clap-3.2.20/examples/derive_ref/custom-bool.md new file mode 100644 index 000000000..619f9ba8e --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/custom-bool.md @@ -0,0 +1,47 @@ +*Jump to [source](custom-bool.rs)* + +Example of overriding the magic `bool` behavior + +```console +$ custom-bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + custom-bool[EXE] [OPTIONS] --foo + +ARGS: + [possible values: true, false] + +OPTIONS: + --bar [default: false] + --foo [possible values: true, false] + -h, --help Print help information + -V, --version Print version information + +$ custom-bool +? failed +error: The following required arguments were not provided: + --foo + + +USAGE: + custom-bool[EXE] [OPTIONS] --foo + +For more information try --help + +$ custom-bool --foo true false +[examples/derive_ref/custom-bool.rs:31] opt = Opt { + foo: true, + bar: false, + boom: false, +} + +$ custom-bool --foo true --bar true false +[examples/derive_ref/custom-bool.rs:31] opt = Opt { + foo: true, + bar: true, + boom: false, +} + +``` diff --git a/vendor/clap-3.2.20/examples/derive_ref/custom-bool.rs b/vendor/clap-3.2.20/examples/derive_ref/custom-bool.rs new file mode 100644 index 000000000..d3c321e72 --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/custom-bool.rs @@ -0,0 +1,32 @@ +use clap::Parser; + +#[derive(Parser, Debug, PartialEq)] +#[clap(author, version, about, long_about = None)] +struct Opt { + // Default parser for `Set` is FromStr::from_str. + // `impl FromStr for bool` parses `true` or `false` so this + // works as expected. + #[clap(long, action = clap::ArgAction::Set)] + foo: bool, + + // Of course, this could be done with an explicit parser function. + #[clap(long, action = clap::ArgAction::Set, value_parser = true_or_false, default_value_t)] + bar: bool, + + // `bool` can be positional only with explicit `action` annotation + #[clap(action = clap::ArgAction::Set)] + boom: bool, +} + +fn true_or_false(s: &str) -> Result { + match s { + "true" => Ok(true), + "false" => Ok(false), + _ => Err("expected `true` or `false`"), + } +} + +fn main() { + let opt = Opt::parse(); + dbg!(opt); +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/flatten_hand_args.rs b/vendor/clap-3.2.20/examples/derive_ref/flatten_hand_args.rs new file mode 100644 index 000000000..c10e0b29f --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/flatten_hand_args.rs @@ -0,0 +1,81 @@ +use clap::error::Error; +use clap::{Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches, Parser}; + +#[derive(Debug)] +struct CliArgs { + foo: bool, + bar: bool, + quuz: Option, +} + +impl FromArgMatches for CliArgs { + fn from_arg_matches(matches: &ArgMatches) -> Result { + let mut matches = matches.clone(); + Self::from_arg_matches_mut(&mut matches) + } + fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { + Ok(Self { + foo: matches.get_flag("foo"), + bar: matches.get_flag("bar"), + quuz: matches.remove_one::("quuz"), + }) + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + let mut matches = matches.clone(); + self.update_from_arg_matches_mut(&mut matches) + } + fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { + self.foo |= matches.get_flag("foo"); + self.bar |= matches.get_flag("bar"); + if let Some(quuz) = matches.remove_one::("quuz") { + self.quuz = Some(quuz); + } + Ok(()) + } +} + +impl Args for CliArgs { + fn augment_args(cmd: Command<'_>) -> Command<'_> { + cmd.arg( + Arg::new("foo") + .short('f') + .long("foo") + .action(ArgAction::SetTrue), + ) + .arg( + Arg::new("bar") + .short('b') + .long("bar") + .action(ArgAction::SetTrue), + ) + .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) + } + fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> { + cmd.arg( + Arg::new("foo") + .short('f') + .long("foo") + .action(ArgAction::SetTrue), + ) + .arg( + Arg::new("bar") + .short('b') + .long("bar") + .action(ArgAction::SetTrue), + ) + .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) + } +} + +#[derive(Parser, Debug)] +struct Cli { + #[clap(short, long, action)] + top_level: bool, + #[clap(flatten)] + more_args: CliArgs, +} + +fn main() { + let args = Cli::parse(); + println!("{:#?}", args); +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/hand_subcommand.rs b/vendor/clap-3.2.20/examples/derive_ref/hand_subcommand.rs new file mode 100644 index 000000000..e9423bdc0 --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/hand_subcommand.rs @@ -0,0 +1,81 @@ +use clap::error::{Error, ErrorKind}; +use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand}; + +#[derive(Parser, Debug)] +struct AddArgs { + #[clap(value_parser)] + name: Vec, +} +#[derive(Parser, Debug)] +struct RemoveArgs { + #[clap(short, long, action)] + force: bool, + #[clap(value_parser)] + name: Vec, +} + +#[derive(Debug)] +enum CliSub { + Add(AddArgs), + Remove(RemoveArgs), +} + +impl FromArgMatches for CliSub { + fn from_arg_matches(matches: &ArgMatches) -> Result { + match matches.subcommand() { + Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)), + Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)), + Some((_, _)) => Err(Error::raw( + ErrorKind::UnrecognizedSubcommand, + "Valid subcommands are `add` and `remove`", + )), + None => Err(Error::raw( + ErrorKind::MissingSubcommand, + "Valid subcommands are `add` and `remove`", + )), + } + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + match matches.subcommand() { + Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?), + Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?), + Some((_, _)) => { + return Err(Error::raw( + ErrorKind::UnrecognizedSubcommand, + "Valid subcommands are `add` and `remove`", + )) + } + None => (), + }; + Ok(()) + } +} + +impl Subcommand for CliSub { + fn augment_subcommands(cmd: Command<'_>) -> Command<'_> { + cmd.subcommand(AddArgs::augment_args(Command::new("add"))) + .subcommand(RemoveArgs::augment_args(Command::new("remove"))) + .subcommand_required(true) + } + fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> { + cmd.subcommand(AddArgs::augment_args(Command::new("add"))) + .subcommand(RemoveArgs::augment_args(Command::new("remove"))) + .subcommand_required(true) + } + fn has_subcommand(name: &str) -> bool { + matches!(name, "add" | "remove") + } +} + +#[derive(Parser, Debug)] +struct Cli { + #[clap(short, long, action)] + top_level: bool, + #[clap(subcommand)] + subcommand: CliSub, +} + +fn main() { + let args = Cli::parse(); + println!("{:#?}", args); +} diff --git a/vendor/clap-3.2.20/examples/derive_ref/interop_tests.md b/vendor/clap-3.2.20/examples/derive_ref/interop_tests.md new file mode 100644 index 000000000..746fe1878 --- /dev/null +++ b/vendor/clap-3.2.20/examples/derive_ref/interop_tests.md @@ -0,0 +1,256 @@ +Following are tests for the interop examples in this directory. + +## Augment Args + +```console +$ interop_augment_args +Value of built: false +Value of derived via ArgMatches: false +Value of derived: DerivedArgs { + derived: false, +} + +``` + +```console +$ interop_augment_args -b --derived +Value of built: true +Value of derived via ArgMatches: true +Value of derived: DerivedArgs { + derived: true, +} + +``` + +```console +$ interop_augment_args -d --built +Value of built: true +Value of derived via ArgMatches: true +Value of derived: DerivedArgs { + derived: true, +} + +``` + +```console +$ interop_augment_args --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_augment_args[EXE] [OPTIONS] + +For more information try --help + +``` + +## Augment Subcommands + +```console +$ interop_augment_subcommands +? failed +error: A subcommand is required but one was not provided. +``` + +```console +$ interop_augment_subcommands derived +Derived subcommands: Derived { + derived_flag: false, +} + +``` + +```console +$ interop_augment_subcommands derived --derived-flag +Derived subcommands: Derived { + derived_flag: true, +} + +``` + +```console +$ interop_augment_subcommands derived --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_augment_subcommands[EXE] derived [OPTIONS] + +For more information try --help + +``` + +```console +$ interop_augment_subcommands unknown +? failed +error: Found argument 'unknown' which wasn't expected, or isn't valid in this context + +USAGE: + interop_augment_subcommands[EXE] [SUBCOMMAND] + +For more information try --help + +``` + +## Hand-Implemented Subcommand + +```console +$ interop_hand_subcommand +? failed +error: 'interop_hand_subcommand[EXE]' requires a subcommand but one was not provided + +USAGE: + interop_hand_subcommand[EXE] [OPTIONS] + +For more information try --help + +``` + +```console +$ interop_hand_subcommand add +Cli { + top_level: false, + subcommand: Add( + AddArgs { + name: [], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand add a b c +Cli { + top_level: false, + subcommand: Add( + AddArgs { + name: [ + "a", + "b", + "c", + ], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand add --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_hand_subcommand[EXE] add [NAME]... + +For more information try --help + +``` + +```console +$ interop_hand_subcommand remove +Cli { + top_level: false, + subcommand: Remove( + RemoveArgs { + force: false, + name: [], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand remove --force a b c +Cli { + top_level: false, + subcommand: Remove( + RemoveArgs { + force: true, + name: [ + "a", + "b", + "c", + ], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand unknown +? failed +error: Found argument 'unknown' which wasn't expected, or isn't valid in this context + +USAGE: + interop_hand_subcommand[EXE] [OPTIONS] + +For more information try --help + +``` + +## Flatten Hand-Implemented Args + +```console +$ interop_flatten_hand_args +Cli { + top_level: false, + more_args: CliArgs { + foo: false, + bar: false, + quuz: None, + }, +} + +``` + +```console +$ interop_flatten_hand_args -f --bar +Cli { + top_level: false, + more_args: CliArgs { + foo: true, + bar: true, + quuz: None, + }, +} + +``` + +```console +$ interop_flatten_hand_args --quuz abc +Cli { + top_level: false, + more_args: CliArgs { + foo: false, + bar: false, + quuz: Some( + "abc", + ), + }, +} + +``` + +```console +$ interop_flatten_hand_args --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_flatten_hand_args[EXE] [OPTIONS] + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/escaped-positional-derive.md b/vendor/clap-3.2.20/examples/escaped-positional-derive.md new file mode 100644 index 000000000..fa39a2c03 --- /dev/null +++ b/vendor/clap-3.2.20/examples/escaped-positional-derive.md @@ -0,0 +1,63 @@ +**This requires enabling the [`derive` feature flag][crate::_features].** + +You can use `--` to escape further arguments. + +Let's see what this looks like in the help: +```console +$ escaped-positional-derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + escaped-positional-derive[EXE] [OPTIONS] [-- ...] + +ARGS: + ... + +OPTIONS: + -f + -h, --help Print help information + -p + -V, --version Print version information + +``` + +Here is a baseline without any arguments: +```console +$ escaped-positional-derive +-f used: false +-p's value: None +'slops' values: [] + +``` + +Notice that we can't pass positional arguments before `--`: +```console +$ escaped-positional-derive foo bar +? failed +error: Found argument 'foo' which wasn't expected, or isn't valid in this context + +USAGE: + escaped-positional-derive[EXE] [OPTIONS] [-- ...] + +For more information try --help + +``` + +But you can after: +```console +$ escaped-positional-derive -f -p=bob -- sloppy slop slop +-f used: true +-p's value: Some("bob") +'slops' values: ["sloppy", "slop", "slop"] + +``` + +As mentioned, the parser will directly pass everything through: +```console +$ escaped-positional-derive -- -f -p=bob sloppy slop slop +-f used: false +-p's value: None +'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] + +``` diff --git a/vendor/clap-3.2.20/examples/escaped-positional-derive.rs b/vendor/clap-3.2.20/examples/escaped-positional-derive.rs new file mode 100644 index 000000000..fd8fde4ed --- /dev/null +++ b/vendor/clap-3.2.20/examples/escaped-positional-derive.rs @@ -0,0 +1,25 @@ +use clap::Parser; + +#[derive(Parser)] // requires `derive` feature +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short = 'f', action)] + eff: bool, + + #[clap(short = 'p', value_name = "PEAR", value_parser)] + pea: Option, + + #[clap(last = true, value_parser)] + slop: Vec, +} + +fn main() { + let args = Cli::parse(); + + // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... + println!("-f used: {:?}", args.eff); // -f used: true + println!("-p's value: {:?}", args.pea); // -p's value: Some("bob") + println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"]) + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/escaped-positional.md b/vendor/clap-3.2.20/examples/escaped-positional.md new file mode 100644 index 000000000..987b26139 --- /dev/null +++ b/vendor/clap-3.2.20/examples/escaped-positional.md @@ -0,0 +1,63 @@ +**This requires enabling the [`cargo` feature flag][crate::_features].** + +You can use `--` to escape further arguments. + +Let's see what this looks like in the help: +```console +$ escaped-positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + escaped-positional[EXE] [OPTIONS] [-- ...] + +ARGS: + ... + +OPTIONS: + -f + -h, --help Print help information + -p + -V, --version Print version information + +``` + +Here is a baseline without any arguments: +```console +$ escaped-positional +-f used: false +-p's value: None +'slops' values: [] + +``` + +Notice that we can't pass positional arguments before `--`: +```console +$ escaped-positional foo bar +? failed +error: Found argument 'foo' which wasn't expected, or isn't valid in this context + +USAGE: + escaped-positional[EXE] [OPTIONS] [-- ...] + +For more information try --help + +``` + +But you can after: +```console +$ escaped-positional -f -p=bob -- sloppy slop slop +-f used: true +-p's value: Some("bob") +'slops' values: ["sloppy", "slop", "slop"] + +``` + +As mentioned, the parser will directly pass everything through: +```console +$ escaped-positional -- -f -p=bob sloppy slop slop +-f used: false +-p's value: None +'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] + +``` diff --git a/vendor/clap-3.2.20/examples/escaped-positional.rs b/vendor/clap-3.2.20/examples/escaped-positional.rs new file mode 100644 index 000000000..fdcb930fb --- /dev/null +++ b/vendor/clap-3.2.20/examples/escaped-positional.rs @@ -0,0 +1,36 @@ +use clap::{arg, command, value_parser, ArgAction}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!(eff: -f).action(ArgAction::SetTrue)) + .arg( + arg!(pea: -p ) + .required(false) + .value_parser(value_parser!(String)), + ) + .arg( + // Indicates that `slop` is only accessible after `--`. + arg!(slop: [SLOP]) + .multiple_values(true) + .last(true) + .value_parser(value_parser!(String)), + ) + .get_matches(); + + // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... + + // -f used: true + println!("-f used: {:?}", matches.get_flag("eff")); + // -p's value: Some("bob") + println!("-p's value: {:?}", matches.get_one::("pea")); + // 'slops' values: Some(["sloppy", "slop", "slop"]) + println!( + "'slops' values: {:?}", + matches + .get_many::("slop") + .map(|vals| vals.collect::>()) + .unwrap_or_default() + ); + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/git-derive.md b/vendor/clap-3.2.20/examples/git-derive.md new file mode 100644 index 000000000..aa1ca6d9d --- /dev/null +++ b/vendor/clap-3.2.20/examples/git-derive.md @@ -0,0 +1,138 @@ +**This requires enabling the [`derive` feature flag][crate::_features].** + +Git is an example of several common subcommand patterns. + +Help: +```console +$ git-derive +? failed +git +A fictional versioning CLI + +USAGE: + git-derive[EXE] + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git-derive help +git +A fictional versioning CLI + +USAGE: + git-derive[EXE] + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git-derive help add +git-derive[EXE]-add +adds things + +USAGE: + git-derive[EXE] add ... + +ARGS: + ... Stuff to add + +OPTIONS: + -h, --help Print help information + +``` + +A basic argument: +```console +$ git-derive add +? failed +git-derive[EXE]-add +adds things + +USAGE: + git-derive[EXE] add ... + +ARGS: + ... Stuff to add + +OPTIONS: + -h, --help Print help information + +$ git-derive add Cargo.toml Cargo.lock +Adding ["Cargo.toml", "Cargo.lock"] + +``` + +Default subcommand: +```console +$ git-derive stash -h +git-derive[EXE]-stash + +USAGE: + git-derive[EXE] stash [OPTIONS] + git-derive[EXE] stash + +OPTIONS: + -h, --help Print help information + -m, --message + +SUBCOMMANDS: + apply + help Print this message or the help of the given subcommand(s) + pop + push + +$ git-derive stash push -h +git-derive[EXE]-stash-push + +USAGE: + git-derive[EXE] stash push [OPTIONS] + +OPTIONS: + -h, --help Print help information + -m, --message + +$ git-derive stash pop -h +git-derive[EXE]-stash-pop + +USAGE: + git-derive[EXE] stash pop [STASH] + +ARGS: + + +OPTIONS: + -h, --help Print help information + +$ git-derive stash -m "Prototype" +Pushing StashPush { message: Some("Prototype") } + +$ git-derive stash pop +Popping None + +$ git-derive stash push -m "Prototype" +Pushing StashPush { message: Some("Prototype") } + +$ git-derive stash pop +Popping None + +``` + +External subcommands: +```console +$ git-derive custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/vendor/clap-3.2.20/examples/git-derive.rs b/vendor/clap-3.2.20/examples/git-derive.rs new file mode 100644 index 000000000..ac500ddad --- /dev/null +++ b/vendor/clap-3.2.20/examples/git-derive.rs @@ -0,0 +1,105 @@ +use std::ffi::OsString; +use std::path::PathBuf; + +use clap::{Args, Parser, Subcommand}; + +/// A fictional versioning CLI +#[derive(Debug, Parser)] // requires `derive` feature +#[clap(name = "git")] +#[clap(about = "A fictional versioning CLI", long_about = None)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Debug, Subcommand)] +enum Commands { + /// Clones repos + #[clap(arg_required_else_help = true)] + Clone { + /// The remote to clone + #[clap(value_parser)] + remote: String, + }, + /// pushes things + #[clap(arg_required_else_help = true)] + Push { + /// The remote to target + #[clap(value_parser)] + remote: String, + }, + /// adds things + #[clap(arg_required_else_help = true)] + Add { + /// Stuff to add + #[clap(required = true, value_parser)] + path: Vec, + }, + Stash(Stash), + #[clap(external_subcommand)] + External(Vec), +} + +#[derive(Debug, Args)] +#[clap(args_conflicts_with_subcommands = true)] +struct Stash { + #[clap(subcommand)] + command: Option, + + #[clap(flatten)] + push: StashPush, +} + +#[derive(Debug, Subcommand)] +enum StashCommands { + Push(StashPush), + Pop { + #[clap(value_parser)] + stash: Option, + }, + Apply { + #[clap(value_parser)] + stash: Option, + }, +} + +#[derive(Debug, Args)] +struct StashPush { + #[clap(short, long, value_parser)] + message: Option, +} + +fn main() { + let args = Cli::parse(); + + match args.command { + Commands::Clone { remote } => { + println!("Cloning {}", remote); + } + Commands::Push { remote } => { + println!("Pushing to {}", remote); + } + Commands::Add { path } => { + println!("Adding {:?}", path); + } + Commands::Stash(stash) => { + let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push)); + match stash_cmd { + StashCommands::Push(push) => { + println!("Pushing {:?}", push); + } + StashCommands::Pop { stash } => { + println!("Popping {:?}", stash); + } + StashCommands::Apply { stash } => { + println!("Applying {:?}", stash); + } + } + } + Commands::External(args) => { + println!("Calling out to {:?} with {:?}", &args[0], &args[1..]); + } + } + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/git.md b/vendor/clap-3.2.20/examples/git.md new file mode 100644 index 000000000..9e413415a --- /dev/null +++ b/vendor/clap-3.2.20/examples/git.md @@ -0,0 +1,136 @@ +Git is an example of several common subcommand patterns. + +Help: +```console +$ git +? failed +git +A fictional versioning CLI + +USAGE: + git[EXE] + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git help +git +A fictional versioning CLI + +USAGE: + git[EXE] + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git help add +git[EXE]-add +adds things + +USAGE: + git[EXE] add ... + +ARGS: + ... Stuff to add + +OPTIONS: + -h, --help Print help information + +``` + +A basic argument: +```console +$ git add +? failed +git[EXE]-add +adds things + +USAGE: + git[EXE] add ... + +ARGS: + ... Stuff to add + +OPTIONS: + -h, --help Print help information + +$ git add Cargo.toml Cargo.lock +Adding ["Cargo.toml", "Cargo.lock"] + +``` + +Default subcommand: +```console +$ git stash -h +git[EXE]-stash + +USAGE: + git[EXE] stash [OPTIONS] + git[EXE] stash + +OPTIONS: + -h, --help Print help information + -m, --message + +SUBCOMMANDS: + apply + help Print this message or the help of the given subcommand(s) + pop + push + +$ git stash push -h +git[EXE]-stash-push + +USAGE: + git[EXE] stash push [OPTIONS] + +OPTIONS: + -h, --help Print help information + -m, --message + +$ git stash pop -h +git[EXE]-stash-pop + +USAGE: + git[EXE] stash pop [STASH] + +ARGS: + + +OPTIONS: + -h, --help Print help information + +$ git stash -m "Prototype" +Pushing Some("Prototype") + +$ git stash pop +Popping None + +$ git stash push -m "Prototype" +Pushing Some("Prototype") + +$ git stash pop +Popping None + +``` + +External subcommands: +```console +$ git custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/vendor/clap-3.2.20/examples/git.rs b/vendor/clap-3.2.20/examples/git.rs new file mode 100644 index 000000000..e56f427a6 --- /dev/null +++ b/vendor/clap-3.2.20/examples/git.rs @@ -0,0 +1,101 @@ +use std::ffi::OsString; +use std::path::PathBuf; + +use clap::{arg, Command}; + +fn cli() -> Command<'static> { + Command::new("git") + .about("A fictional versioning CLI") + .subcommand_required(true) + .arg_required_else_help(true) + .allow_external_subcommands(true) + .allow_invalid_utf8_for_external_subcommands(true) + .subcommand( + Command::new("clone") + .about("Clones repos") + .arg(arg!( "The remote to clone")) + .arg_required_else_help(true), + ) + .subcommand( + Command::new("push") + .about("pushes things") + .arg(arg!( "The remote to target")) + .arg_required_else_help(true), + ) + .subcommand( + Command::new("add") + .about("adds things") + .arg_required_else_help(true) + .arg(arg!( ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))), + ) + .subcommand( + Command::new("stash") + .args_conflicts_with_subcommands(true) + .args(push_args()) + .subcommand(Command::new("push").args(push_args())) + .subcommand(Command::new("pop").arg(arg!([STASH]))) + .subcommand(Command::new("apply").arg(arg!([STASH]))), + ) +} + +fn push_args() -> Vec> { + vec![arg!(-m --message ).required(false)] +} + +fn main() { + let matches = cli().get_matches(); + + match matches.subcommand() { + Some(("clone", sub_matches)) => { + println!( + "Cloning {}", + sub_matches.get_one::("REMOTE").expect("required") + ); + } + Some(("push", sub_matches)) => { + println!( + "Pushing to {}", + sub_matches.get_one::("REMOTE").expect("required") + ); + } + Some(("add", sub_matches)) => { + let paths = sub_matches + .get_many::("PATH") + .into_iter() + .flatten() + .collect::>(); + println!("Adding {:?}", paths); + } + Some(("stash", sub_matches)) => { + let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches)); + match stash_command { + ("apply", sub_matches) => { + let stash = sub_matches.get_one::("STASH"); + println!("Applying {:?}", stash); + } + ("pop", sub_matches) => { + let stash = sub_matches.get_one::("STASH"); + println!("Popping {:?}", stash); + } + ("push", sub_matches) => { + let message = sub_matches.get_one::("message"); + println!("Pushing {:?}", message); + } + (name, _) => { + unreachable!("Unsupported subcommand `{}`", name) + } + } + } + Some((ext, sub_matches)) => { + let args = sub_matches + .get_many::("") + .into_iter() + .flatten() + .collect::>(); + println!("Calling out to {:?} with {:?}", ext, args); + } + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!() + } + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/multicall-busybox.md b/vendor/clap-3.2.20/examples/multicall-busybox.md new file mode 100644 index 000000000..5ca2cad5b --- /dev/null +++ b/vendor/clap-3.2.20/examples/multicall-busybox.md @@ -0,0 +1,42 @@ +See the documentation for [`Command::multicall`][crate::App::multicall] for rationale. + +This example omits every command except true and false, +which are the most trivial to implement, +```console +$ busybox true +? 0 + +$ busybox false +? 1 + +``` +*Note: without the links setup, we can't demonstrate the multicall behavior* + +But includes the `--install` option as an example of why it can be useful +for the main program to take arguments that aren't applet subcommands. +```console +$ busybox --install +? failed +... + +``` + +Though users must pass something: +```console +$ busybox +? failed +busybox + +USAGE: + busybox [OPTIONS] [APPLET] + +OPTIONS: + -h, --help Print help information + --install Install hardlinks for all subcommands in path + +APPLETS: + false does nothing unsuccessfully + help Print this message or the help of the given subcommand(s) + true does nothing successfully + +``` diff --git a/vendor/clap-3.2.20/examples/multicall-busybox.rs b/vendor/clap-3.2.20/examples/multicall-busybox.rs new file mode 100644 index 000000000..2e7f976c1 --- /dev/null +++ b/vendor/clap-3.2.20/examples/multicall-busybox.rs @@ -0,0 +1,48 @@ +use std::path::PathBuf; +use std::process::exit; + +use clap::{value_parser, Arg, Command}; + +fn applet_commands() -> [Command<'static>; 2] { + [ + Command::new("true").about("does nothing successfully"), + Command::new("false").about("does nothing unsuccessfully"), + ] +} + +fn main() { + let cmd = Command::new(env!("CARGO_CRATE_NAME")) + .multicall(true) + .subcommand( + Command::new("busybox") + .arg_required_else_help(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .arg( + Arg::new("install") + .long("install") + .help("Install hardlinks for all subcommands in path") + .exclusive(true) + .takes_value(true) + .default_missing_value("/usr/local/bin") + .value_parser(value_parser!(PathBuf)) + .use_value_delimiter(false), + ) + .subcommands(applet_commands()), + ) + .subcommands(applet_commands()); + + let matches = cmd.get_matches(); + let mut subcommand = matches.subcommand(); + if let Some(("busybox", cmd)) = subcommand { + if cmd.contains_id("install") { + unimplemented!("Make hardlinks to the executable here"); + } + subcommand = cmd.subcommand(); + } + match subcommand { + Some(("false", _)) => exit(1), + Some(("true", _)) => exit(0), + _ => unreachable!("parser should ensure only valid subcommand names are used"), + } +} diff --git a/vendor/clap-3.2.20/examples/multicall-hostname.md b/vendor/clap-3.2.20/examples/multicall-hostname.md new file mode 100644 index 000000000..d22b85fba --- /dev/null +++ b/vendor/clap-3.2.20/examples/multicall-hostname.md @@ -0,0 +1,10 @@ +See the documentation for [`Command::multicall`][crate::App::multicall] for rationale. + +This example omits the implementation of displaying address config + +```console +$ hostname +www + +``` +*Note: without the links setup, we can't demonstrate the multicall behavior* diff --git a/vendor/clap-3.2.20/examples/multicall-hostname.rs b/vendor/clap-3.2.20/examples/multicall-hostname.rs new file mode 100644 index 000000000..b57680a5c --- /dev/null +++ b/vendor/clap-3.2.20/examples/multicall-hostname.rs @@ -0,0 +1,17 @@ +use clap::Command; + +fn main() { + let cmd = Command::new(env!("CARGO_CRATE_NAME")) + .multicall(true) + .arg_required_else_help(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .subcommand(Command::new("hostname").about("show hostname part of FQDN")) + .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN")); + + match cmd.get_matches().subcommand_name() { + Some("hostname") => println!("www"), + Some("dnsdomainname") => println!("example.com"), + _ => unreachable!("parser should ensure only valid subcommand names are used"), + } +} diff --git a/vendor/clap-3.2.20/examples/pacman.md b/vendor/clap-3.2.20/examples/pacman.md new file mode 100644 index 000000000..b8ddd09d9 --- /dev/null +++ b/vendor/clap-3.2.20/examples/pacman.md @@ -0,0 +1,85 @@ +[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags. + +Here, `-S` is a short flag subcommand: +```console +$ pacman -S package +Installing package... + +``` + +Here `--sync` is a long flag subcommand: +```console +$ pacman --sync package +Installing package... + +``` + +Now the short flag subcommand (`-S`) with a long flag: +```console +$ pacman -S --search name +Searching for name... + +``` + +And the various forms of short flags that work: +```console +$ pacman -S -s name +Searching for name... + +$ pacman -Ss name +Searching for name... + +``` +*(users can "stack" short subcommands with short flags or with other short flag subcommands)* + +In the help, this looks like: +```console +$ pacman -h +pacman 5.2.1 +Pacman Development Team +package manager utility + +USAGE: + pacman[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + query -Q --query Query the package database. + sync -S --sync Synchronize packages. + +$ pacman -S -h +pacman[EXE]-sync +Synchronize packages. + +USAGE: + pacman[EXE] {sync|--sync|-S} [OPTIONS] [--] [package]... + +ARGS: + ... packages + +OPTIONS: + -h, --help Print help information + -i, --info view package information + -s, --search ... search remote repositories for matching strings + +``` + +And errors: +```console +$ pacman -S -s foo -i bar +? failed +error: The argument '--search ...' cannot be used with '--info' + +USAGE: + pacman[EXE] {sync|--sync|-S} --search ... ... + +For more information try --help + +``` + +**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated. +Let's make a quick program to illustrate. diff --git a/vendor/clap-3.2.20/examples/pacman.rs b/vendor/clap-3.2.20/examples/pacman.rs new file mode 100644 index 000000000..aee7cd892 --- /dev/null +++ b/vendor/clap-3.2.20/examples/pacman.rs @@ -0,0 +1,111 @@ +use clap::{Arg, ArgAction, Command}; + +fn main() { + let matches = Command::new("pacman") + .about("package manager utility") + .version("5.2.1") + .subcommand_required(true) + .arg_required_else_help(true) + .author("Pacman Development Team") + // Query subcommand + // + // Only a few of its arguments are implemented below. + .subcommand( + Command::new("query") + .short_flag('Q') + .long_flag("query") + .about("Query the package database.") + .arg( + Arg::new("search") + .short('s') + .long("search") + .help("search locally installed packages for matching strings") + .conflicts_with("info") + .takes_value(true) + .multiple_values(true), + ) + .arg( + Arg::new("info") + .long("info") + .short('i') + .conflicts_with("search") + .help("view package information") + .takes_value(true) + .multiple_values(true), + ), + ) + // Sync subcommand + // + // Only a few of its arguments are implemented below. + .subcommand( + Command::new("sync") + .short_flag('S') + .long_flag("sync") + .about("Synchronize packages.") + .arg( + Arg::new("search") + .short('s') + .long("search") + .conflicts_with("info") + .takes_value(true) + .multiple_values(true) + .help("search remote repositories for matching strings"), + ) + .arg( + Arg::new("info") + .long("info") + .conflicts_with("search") + .short('i') + .action(ArgAction::SetTrue) + .help("view package information"), + ) + .arg( + Arg::new("package") + .help("packages") + .required_unless_present("search") + .takes_value(true) + .multiple_values(true), + ), + ) + .get_matches(); + + match matches.subcommand() { + Some(("sync", sync_matches)) => { + if sync_matches.contains_id("search") { + let packages: Vec<_> = sync_matches + .get_many::("search") + .expect("contains_id") + .map(|s| s.as_str()) + .collect(); + let values = packages.join(", "); + println!("Searching for {}...", values); + return; + } + + let packages: Vec<_> = sync_matches + .get_many::("package") + .expect("is present") + .map(|s| s.as_str()) + .collect(); + let values = packages.join(", "); + + if sync_matches.get_flag("info") { + println!("Retrieving info for {}...", values); + } else { + println!("Installing {}...", values); + } + } + Some(("query", query_matches)) => { + if let Some(packages) = query_matches.get_many::("info") { + let comma_sep = packages.map(|s| s.as_str()).collect::>().join(", "); + println!("Retrieving info for {}...", comma_sep); + } else if let Some(queries) = query_matches.get_many::("search") { + let comma_sep = queries.map(|s| s.as_str()).collect::>().join(", "); + println!("Searching Locally for {}...", comma_sep); + } else { + println!("Displaying all locally installed packages..."); + } + } + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable + } +} diff --git a/vendor/clap-3.2.20/examples/repl.rs b/vendor/clap-3.2.20/examples/repl.rs new file mode 100644 index 000000000..c509adee6 --- /dev/null +++ b/vendor/clap-3.2.20/examples/repl.rs @@ -0,0 +1,92 @@ +use std::io::Write; + +use clap::Command; + +fn main() -> Result<(), String> { + loop { + let line = readline()?; + let line = line.trim(); + if line.is_empty() { + continue; + } + + match respond(line) { + Ok(quit) => { + if quit { + break; + } + } + Err(err) => { + write!(std::io::stdout(), "{}", err).map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + } + } + } + + Ok(()) +} + +fn respond(line: &str) -> Result { + let args = shlex::split(line).ok_or("error: Invalid quoting")?; + let matches = cli() + .try_get_matches_from(&args) + .map_err(|e| e.to_string())?; + match matches.subcommand() { + Some(("ping", _matches)) => { + write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + } + Some(("quit", _matches)) => { + write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + return Ok(true); + } + Some((name, _matches)) => unimplemented!("{}", name), + None => unreachable!("subcommand required"), + } + + Ok(false) +} + +fn cli() -> Command<'static> { + // strip out usage + const PARSER_TEMPLATE: &str = "\ + {all-args} + "; + // strip out name/version + const APPLET_TEMPLATE: &str = "\ + {about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + + Command::new("repl") + .multicall(true) + .arg_required_else_help(true) + .subcommand_required(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .help_template(PARSER_TEMPLATE) + .subcommand( + Command::new("ping") + .about("Get a response") + .help_template(APPLET_TEMPLATE), + ) + .subcommand( + Command::new("quit") + .alias("exit") + .about("Quit the REPL") + .help_template(APPLET_TEMPLATE), + ) +} + +fn readline() -> Result { + write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + let mut buffer = String::new(); + std::io::stdin() + .read_line(&mut buffer) + .map_err(|e| e.to_string())?; + Ok(buffer) +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.md b/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.md new file mode 100644 index 000000000..4a9e3fca1 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.md @@ -0,0 +1,37 @@ +```console +$ 01_quick --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] + +ARGS: + Optional name to operate on + +OPTIONS: + -c, --config Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick -dd test +Debug mode is on +Not printing testing lists... + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.rs b/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.rs new file mode 100644 index 000000000..393d6aeae --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/01_quick.rs @@ -0,0 +1,63 @@ +use std::path::PathBuf; + +use clap::{arg, command, value_parser, ArgAction, Command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!([name] "Optional name to operate on")) + .arg( + arg!( + -c --config "Sets a custom config file" + ) + // We don't have syntax yet for optional options, so manually calling `required` + .required(false) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + arg!( + -d --debug "Turn debugging information on" + ) + .action(ArgAction::Count), + ) + .subcommand( + Command::new("test") + .about("does testing things") + .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)), + ) + .get_matches(); + + // You can check the value provided by positional arguments, or option arguments + if let Some(name) = matches.get_one::("name") { + println!("Value for name: {}", name); + } + + if let Some(config_path) = matches.get_one::("config") { + println!("Value for config: {}", config_path.display()); + } + + // You can see how many times a particular flag or argument occurred + // Note, only flags can have multiple occurrences + match matches + .get_one::("debug") + .expect("Count's are defaulted") + { + 0 => println!("Debug mode is off"), + 1 => println!("Debug mode is kind of on"), + 2 => println!("Debug mode is on"), + _ => println!("Don't be crazy"), + } + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + if let Some(matches) = matches.subcommand_matches("test") { + // "$ myapp test" was run + if *matches.get_one::("list").expect("defaulted by clap") { + // "$ myapp test -l" was run + println!("Printing testing lists..."); + } else { + println!("Not printing testing lists..."); + } + } + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.md b/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.md new file mode 100644 index 000000000..247843bcf --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.md @@ -0,0 +1,19 @@ +```console +$ 02_app_settings --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings[EXE] --two --one + +OPTIONS: + --two + --one + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.rs b/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.rs new file mode 100644 index 000000000..5f374d7f0 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_app_settings.rs @@ -0,0 +1,19 @@ +use clap::{arg, command, AppSettings, ArgAction}; + +fn main() { + let matches = command!() // requires `cargo` feature + .global_setting(AppSettings::DeriveDisplayOrder) + .allow_negative_numbers(true) + .arg(arg!(--two ).action(ArgAction::Set)) + .arg(arg!(--one ).action(ArgAction::Set)) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.md b/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.md new file mode 100644 index 000000000..8504b5f52 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.md @@ -0,0 +1,19 @@ +```console +$ 02_apps --help +MyApp 1.0 +Kevin K. +Does awesome things + +USAGE: + 02_apps[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_apps --version +MyApp 1.0 + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.rs b/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.rs new file mode 100644 index 000000000..db9da18f9 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_apps.rs @@ -0,0 +1,20 @@ +use clap::{arg, Command}; + +fn main() { + let matches = Command::new("MyApp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .arg(arg!(--two )) + .arg(arg!(--one )) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.md b/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.md new file mode 100644 index 000000000..f76e0d608 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.md @@ -0,0 +1,18 @@ +```console +$ 02_crate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_crate --version +clap [..] + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.rs b/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.rs new file mode 100644 index 000000000..8a1722fd3 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/02_crate.rs @@ -0,0 +1,18 @@ +use clap::{arg, command}; + +fn main() { + // requires `cargo` feature, reading name, version, author, and description from `Cargo.toml` + let matches = command!() + .arg(arg!(--two )) + .arg(arg!(--one )) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.md new file mode 100644 index 000000000..b0ee2a126 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool +verbose: false + +$ 03_01_flag_bool --verbose +verbose: true + +$ 03_01_flag_bool --verbose --verbose +verbose: true + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.rs new file mode 100644 index 000000000..03f2f1756 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_bool.rs @@ -0,0 +1,14 @@ +use clap::{command, Arg, ArgAction}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg( + Arg::new("verbose") + .short('v') + .long("verbose") + .action(ArgAction::SetTrue), + ) + .get_matches(); + + println!("verbose: {:?}", matches.get_flag("verbose")); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.md new file mode 100644 index 000000000..ca4bcd6eb --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_count --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count +verbose: 0 + +$ 03_01_flag_count --verbose +verbose: 1 + +$ 03_01_flag_count --verbose --verbose +verbose: 2 + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.rs new file mode 100644 index 000000000..7f23649d6 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_01_flag_count.rs @@ -0,0 +1,9 @@ +use clap::{arg, command, ArgAction}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!(-v - -verbose).action(ArgAction::Count)) + .get_matches(); + + println!("verbose: {:?}", matches.get_count("verbose")); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.md new file mode 100644 index 000000000..6198bcc73 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.md @@ -0,0 +1,32 @@ +```console +$ 03_02_option --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name + -V, --version Print version information + +$ 03_02_option +name: None + +$ 03_02_option --name bob +name: Some("bob") + +$ 03_02_option --name=bob +name: Some("bob") + +$ 03_02_option -n bob +name: Some("bob") + +$ 03_02_option -n=bob +name: Some("bob") + +$ 03_02_option -nbob +name: Some("bob") + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.rs new file mode 100644 index 000000000..188244566 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_02_option.rs @@ -0,0 +1,9 @@ +use clap::{arg, command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!(-n --name ).required(false)) + .get_matches(); + + println!("name: {:?}", matches.get_one::("name")); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.md new file mode 100644 index 000000000..a3d7b8cf3 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.md @@ -0,0 +1,22 @@ +```console +$ 03_03_positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional[EXE] [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional +NAME: None + +$ 03_03_positional bob +NAME: Some("bob") + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.rs new file mode 100644 index 000000000..0c3a5f037 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_03_positional.rs @@ -0,0 +1,9 @@ +use clap::{arg, command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!([NAME])) + .get_matches(); + + println!("NAME: {:?}", matches.get_one::("NAME")); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.md new file mode 100644 index 000000000..8f9efa911 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.md @@ -0,0 +1,64 @@ +```console +$ 03_04_subcommands help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands help add +03_04_subcommands[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands[EXE] add [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands add bob +'myapp add' was used, name is: Some("bob") + +``` + +Because we set [`Command::arg_required_else_help`][crate::Command::arg_required_else_help]: +```console +$ 03_04_subcommands +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we set [`Command::propagate_version`][crate::Command::propagate_version]: +```console +$ 03_04_subcommands --version +clap [..] + +$ 03_04_subcommands add --version +03_04_subcommands[EXE]-add [..] + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.rs new file mode 100644 index 000000000..fbe23809e --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_04_subcommands.rs @@ -0,0 +1,22 @@ +use clap::{arg, command, Command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .propagate_version(true) + .subcommand_required(true) + .arg_required_else_help(true) + .subcommand( + Command::new("add") + .about("Adds files to myapp") + .arg(arg!([NAME])), + ) + .get_matches(); + + match matches.subcommand() { + Some(("add", sub_matches)) => println!( + "'myapp add' was used, name is: {:?}", + sub_matches.get_one::("NAME") + ), + _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"), + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.md b/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.md new file mode 100644 index 000000000..7b6c0307d --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.md @@ -0,0 +1,22 @@ +```console +$ 03_05_default_values --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values[EXE] [NAME] + +ARGS: + [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values +NAME: "alice" + +$ 03_05_default_values bob +NAME: "bob" + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.rs b/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.rs new file mode 100644 index 000000000..cb3e3831f --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/03_05_default_values.rs @@ -0,0 +1,14 @@ +use clap::{arg, command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg(arg!([NAME]).default_value("alice")) + .get_matches(); + + println!( + "NAME: {:?}", + matches + .get_one::("NAME") + .expect("default ensures there is always a value") + ); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.md new file mode 100644 index 000000000..282b1e613 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.md @@ -0,0 +1,29 @@ +```console +$ 04_01_enum --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum fast +Hare + +$ 04_01_enum slow +Tortoise + +$ 04_01_enum medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.rs new file mode 100644 index 000000000..e8cf70f5c --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_enum.rs @@ -0,0 +1,66 @@ +use clap::{arg, builder::PossibleValue, command, value_parser, ValueEnum}; + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +enum Mode { + Fast, + Slow, +} + +// Can also be derived] with feature flag `derive` +impl ValueEnum for Mode { + fn value_variants<'a>() -> &'a [Self] { + &[Mode::Fast, Mode::Slow] + } + + fn to_possible_value<'a>(&self) -> Option> { + Some(match self { + Mode::Fast => PossibleValue::new("fast"), + Mode::Slow => PossibleValue::new("slow"), + }) + } +} + +impl std::fmt::Display for Mode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.to_possible_value() + .expect("no values are skipped") + .get_name() + .fmt(f) + } +} + +impl std::str::FromStr for Mode { + type Err = String; + + fn from_str(s: &str) -> Result { + for variant in Self::value_variants() { + if variant.to_possible_value().unwrap().matches(s, false) { + return Ok(*variant); + } + } + Err(format!("Invalid variant: {}", s)) + } +} + +fn main() { + let matches = command!() // requires `cargo` feature + .arg( + arg!() + .help("What mode to run the program in") + .value_parser(value_parser!(Mode)), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .get_one::("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.md new file mode 100644 index 000000000..2909bfb17 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.md @@ -0,0 +1,29 @@ +```console +$ 04_01_possible --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_possible[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_possible fast +Hare + +$ 04_01_possible slow +Tortoise + +$ 04_01_possible medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.rs new file mode 100644 index 000000000..3da7aca74 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_01_possible.rs @@ -0,0 +1,26 @@ +use clap::{arg, command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg( + arg!() + .help("What mode to run the program in") + .value_parser(["fast", "slow"]), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .get_one::("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + .as_str() + { + "fast" => { + println!("Hare"); + } + "slow" => { + println!("Tortoise"); + } + _ => unreachable!(), + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.md new file mode 100644 index 000000000..605bf4b59 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.md @@ -0,0 +1,31 @@ +```console +$ 04_02_parse --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse 22 +PORT = 22 + +$ 04_02_parse foobar +? failed +error: Invalid value "foobar" for '': invalid digit found in string + +For more information try --help + +$ 04_02_parse_derive 0 +? failed +error: Invalid value "0" for '': 0 is not in 1..=65535 + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.rs new file mode 100644 index 000000000..13f41a18e --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_parse.rs @@ -0,0 +1,17 @@ +use clap::{arg, command, value_parser}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg( + arg!() + .help("Network port to use") + .value_parser(value_parser!(u16).range(1..)), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: u16 = *matches + .get_one::("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.md new file mode 100644 index 000000000..a317a8eb7 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.md @@ -0,0 +1,31 @@ +```console +$ 04_02_validate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate 22 +PORT = 22 + +$ 04_02_validate foobar +? failed +error: Invalid value "foobar" for '': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate 0 +? failed +error: Invalid value "0" for '': Port not in range 1-65535 + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.rs new file mode 100644 index 000000000..ea2f32e67 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_02_validate.rs @@ -0,0 +1,36 @@ +use std::ops::RangeInclusive; + +use clap::{arg, command}; + +fn main() { + let matches = command!() // requires `cargo` feature + .arg( + arg!() + .help("Network port to use") + .value_parser(port_in_range), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: u16 = *matches + .get_one::("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +const PORT_RANGE: RangeInclusive = 1..=65535; + +fn port_in_range(s: &str) -> Result { + let port: usize = s + .parse() + .map_err(|_| format!("`{}` isn't a port number", s))?; + if PORT_RANGE.contains(&port) { + Ok(port as u16) + } else { + Err(format!( + "Port not in range {}-{}", + PORT_RANGE.start(), + PORT_RANGE.end() + )) + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.md new file mode 100644 index 000000000..3ea336363 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.md @@ -0,0 +1,58 @@ +```console +$ 04_03_relations --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_03_relations +? failed +error: The following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations --major +Version: 2.2.3 + +$ 04_03_relations --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations[EXE] <--set-ver |--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations --major -c config.toml +? failed +error: The following required arguments were not provided: + > + +USAGE: + 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > + +For more information try --help + +$ 04_03_relations --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.rs new file mode 100644 index 000000000..8e26d3ea9 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_03_relations.rs @@ -0,0 +1,80 @@ +use std::path::PathBuf; + +use clap::{arg, command, value_parser, ArgAction, ArgGroup}; + +fn main() { + // Create application like normal + let matches = command!() // requires `cargo` feature + // Add the version arguments + .arg(arg!(--"set-ver" "set version manually").required(false)) + .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) + .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue)) + .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue)) + // Create a group, make it required, and add the above arguments + .group( + ArgGroup::new("vers") + .required(true) + .args(&["set-ver", "major", "minor", "patch"]), + ) + // Arguments can also be added to a group individually, these two arguments + // are part of the "input" group which is not required + .arg( + arg!([INPUT_FILE] "some regular input") + .value_parser(value_parser!(PathBuf)) + .group("input"), + ) + .arg( + arg!(--"spec-in" "some special input argument") + .required(false) + .value_parser(value_parser!(PathBuf)) + .group("input"), + ) + // Now let's assume we have a -c [config] argument which requires one of + // (but **not** both) the "input" arguments + .arg( + arg!(config: -c ) + .required(false) + .value_parser(value_parser!(PathBuf)) + .requires("input"), + ) + .get_matches(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = matches.get_one::("set-ver") { + ver.to_owned() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = ( + matches.get_flag("major"), + matches.get_flag("minor"), + matches.get_flag("patch"), + ); + match (maj, min, pat) { + (true, _, _) => major += 1, + (_, true, _) => minor += 1, + (_, _, true) => patch += 1, + _ => unreachable!(), + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if matches.contains_id("config") { + let input = matches + .get_one::("INPUT_FILE") + .unwrap_or_else(|| matches.get_one::("spec-in").unwrap()) + .display(); + println!( + "Doing work using input {} and config {}", + input, + matches.get_one::("config").unwrap().display() + ); + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.md b/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.md new file mode 100644 index 000000000..26a3df1ab --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.md @@ -0,0 +1,57 @@ +```console +$ 04_04_custom --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_04_custom +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major +Version: 2.2.3 + +$ 04_04_custom --major --minor +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.rs b/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.rs new file mode 100644 index 000000000..fb40b2fc4 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/04_04_custom.rs @@ -0,0 +1,88 @@ +use std::path::PathBuf; + +use clap::{arg, command, value_parser, ArgAction, ErrorKind}; + +fn main() { + // Create application like normal + let mut cmd = command!() // requires `cargo` feature + // Add the version arguments + .arg(arg!(--"set-ver" "set version manually").required(false)) + .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) + .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue)) + .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue)) + // Arguments can also be added to a group individually, these two arguments + // are part of the "input" group which is not required + .arg(arg!([INPUT_FILE] "some regular input").value_parser(value_parser!(PathBuf))) + .arg( + arg!(--"spec-in" "some special input argument") + .required(false) + .value_parser(value_parser!(PathBuf)), + ) + // Now let's assume we have a -c [config] argument which requires one of + // (but **not** both) the "input" arguments + .arg( + arg!(config: -c ) + .required(false) + .value_parser(value_parser!(PathBuf)), + ); + let matches = cmd.get_matches_mut(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = matches.get_one::("set-ver") { + if matches.get_flag("major") || matches.get_flag("minor") || matches.get_flag("patch") { + cmd.error( + ErrorKind::ArgumentConflict, + "Can't do relative and absolute version change", + ) + .exit(); + } + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = ( + matches.get_flag("major"), + matches.get_flag("minor"), + matches.get_flag("patch"), + ); + match (maj, min, pat) { + (true, false, false) => major += 1, + (false, true, false) => minor += 1, + (false, false, true) => patch += 1, + _ => { + cmd.error( + ErrorKind::ArgumentConflict, + "Can only modify one version field", + ) + .exit(); + } + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if matches.contains_id("config") { + let input = matches + .get_one::("INPUT_FILE") + .or_else(|| matches.get_one::("spec-in")) + .unwrap_or_else(|| { + cmd.error( + ErrorKind::MissingRequiredArgument, + "INPUT_FILE or --spec-in is required when using --config", + ) + .exit() + }) + .display(); + println!( + "Doing work using input {} and config {}", + input, + matches.get_one::("config").unwrap().display() + ); + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_builder/05_01_assert.rs b/vendor/clap-3.2.20/examples/tutorial_builder/05_01_assert.rs new file mode 100644 index 000000000..4b9254230 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_builder/05_01_assert.rs @@ -0,0 +1,25 @@ +use clap::{arg, command, value_parser}; + +fn main() { + let matches = cmd().get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = *matches + .get_one::("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +fn cmd() -> clap::Command<'static> { + command!() // requires `cargo` feature + .arg( + arg!() + .help("Network port to use") + .value_parser(value_parser!(usize)), + ) +} + +#[test] +fn verify_cmd() { + cmd().debug_assert(); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.md b/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.md new file mode 100644 index 000000000..6f70d2cce --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.md @@ -0,0 +1,37 @@ +```console +$ 01_quick_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick_derive[EXE] [OPTIONS] [NAME] [SUBCOMMAND] + +ARGS: + Optional name to operate on + +OPTIONS: + -c, --config Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick_derive +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick_derive -dd test +Debug mode is on +Not printing testing lists... + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.rs b/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.rs new file mode 100644 index 000000000..2c2031061 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/01_quick.rs @@ -0,0 +1,69 @@ +use std::path::PathBuf; + +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Optional name to operate on + #[clap(value_parser)] + name: Option, + + /// Sets a custom config file + #[clap(short, long, value_parser, value_name = "FILE")] + config: Option, + + /// Turn debugging information on + #[clap(short, long, action = clap::ArgAction::Count)] + debug: u8, + + #[clap(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Commands { + /// does testing things + Test { + /// lists test values + #[clap(short, long, action)] + list: bool, + }, +} + +fn main() { + let cli = Cli::parse(); + + // You can check the value provided by positional arguments, or option arguments + if let Some(name) = cli.name.as_deref() { + println!("Value for name: {}", name); + } + + if let Some(config_path) = cli.config.as_deref() { + println!("Value for config: {}", config_path.display()); + } + + // You can see how many times a particular flag or argument occurred + // Note, only flags can have multiple occurrences + match cli.debug { + 0 => println!("Debug mode is off"), + 1 => println!("Debug mode is kind of on"), + 2 => println!("Debug mode is on"), + _ => println!("Don't be crazy"), + } + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Some(Commands::Test { list }) => { + if *list { + println!("Printing testing lists..."); + } else { + println!("Not printing testing lists..."); + } + } + None => {} + } + + // Continued program logic goes here... +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.md b/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.md new file mode 100644 index 000000000..ee16c66df --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.md @@ -0,0 +1,19 @@ +```console +$ 02_app_settings_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings_derive[EXE] --two --one + +OPTIONS: + --two + --one + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings_derive --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.rs b/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.rs new file mode 100644 index 000000000..6a06929bb --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_app_settings.rs @@ -0,0 +1,19 @@ +use clap::{AppSettings, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(allow_negative_numbers = true)] +#[clap(global_setting(AppSettings::DeriveDisplayOrder))] +struct Cli { + #[clap(long, value_parser)] + two: String, + #[clap(long, value_parser)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.md b/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.md new file mode 100644 index 000000000..0141581c4 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.md @@ -0,0 +1,19 @@ +```console +$ 02_apps_derive --help +MyApp 1.0 +Kevin K. +Does awesome things + +USAGE: + 02_apps_derive[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_apps_derive --version +MyApp 1.0 + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.rs b/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.rs new file mode 100644 index 000000000..b97ce1eed --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_apps.rs @@ -0,0 +1,20 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(name = "MyApp")] +#[clap(author = "Kevin K. ")] +#[clap(version = "1.0")] +#[clap(about = "Does awesome things", long_about = None)] +struct Cli { + #[clap(long, value_parser)] + two: String, + #[clap(long, value_parser)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.md b/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.md new file mode 100644 index 000000000..92c820758 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.md @@ -0,0 +1,18 @@ +```console +$ 02_crate_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate_derive[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_crate_derive --version +clap [..] + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.rs b/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.rs new file mode 100644 index 000000000..5576f998c --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/02_crate.rs @@ -0,0 +1,17 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] // Read from `Cargo.toml` +struct Cli { + #[clap(long, value_parser)] + two: String, + #[clap(long, value_parser)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.md new file mode 100644 index 000000000..0baaa10ca --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_bool_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool_derive +verbose: false + +$ 03_01_flag_bool_derive --verbose +verbose: true + +$ 03_01_flag_bool_derive --verbose --verbose +verbose: true + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.rs new file mode 100644 index 000000000..de677d8c6 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_bool.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long, action)] + verbose: bool, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.md new file mode 100644 index 000000000..3d5a53084 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_count_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count_derive +verbose: 0 + +$ 03_01_flag_count_derive --verbose +verbose: 1 + +$ 03_01_flag_count_derive --verbose --verbose +verbose: 2 + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.rs new file mode 100644 index 000000000..680f7f5e5 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_01_flag_count.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long, action = clap::ArgAction::Count)] + verbose: u8, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.md new file mode 100644 index 000000000..84ff7fa74 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.md @@ -0,0 +1,32 @@ +```console +$ 03_02_option_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name + -V, --version Print version information + +$ 03_02_option_derive +name: None + +$ 03_02_option_derive --name bob +name: Some("bob") + +$ 03_02_option_derive --name=bob +name: Some("bob") + +$ 03_02_option_derive -n bob +name: Some("bob") + +$ 03_02_option_derive -n=bob +name: Some("bob") + +$ 03_02_option_derive -nbob +name: Some("bob") + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.rs new file mode 100644 index 000000000..75b67afe7 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_02_option.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long, value_parser)] + name: Option, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.md new file mode 100644 index 000000000..7281fe3ff --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.md @@ -0,0 +1,22 @@ +```console +$ 03_03_positional_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional_derive[EXE] [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional_derive +name: None + +$ 03_03_positional_derive bob +name: Some("bob") + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.rs new file mode 100644 index 000000000..7478951f1 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_03_positional.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(value_parser)] + name: Option, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.md new file mode 100644 index 000000000..02f96e3d3 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.md @@ -0,0 +1,64 @@ +```console +$ 03_04_subcommands_derive help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands_derive[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands_derive help add +03_04_subcommands_derive[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands_derive[EXE] add [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands_derive add bob +'myapp add' was used, name is: Some("bob") + +``` + +Because we used `command: Commands` instead of `command: Option`: +```console +$ 03_04_subcommands_derive +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands_derive[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we added `#[clap(propagate_version = true)]`: +```console +$ 03_04_subcommands_derive --version +clap [..] + +$ 03_04_subcommands_derive add --version +03_04_subcommands_derive[EXE]-add [..] + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.rs new file mode 100644 index 000000000..62a45a97e --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands.rs @@ -0,0 +1,30 @@ +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(propagate_version = true)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Adds files to myapp + Add { + #[clap(value_parser)] + name: Option, + }, +} + +fn main() { + let cli = Cli::parse(); + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Commands::Add { name } => { + println!("'myapp add' was used, name is: {:?}", name) + } + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands_alt.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands_alt.rs new file mode 100644 index 000000000..b6124936c --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_04_subcommands_alt.rs @@ -0,0 +1,33 @@ +use clap::{Args, Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(propagate_version = true)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Adds files to myapp + Add(Add), +} + +#[derive(Args)] +struct Add { + #[clap(value_parser)] + name: Option, +} + +fn main() { + let cli = Cli::parse(); + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Commands::Add(name) => { + println!("'myapp add' was used, name is: {:?}", name.name) + } + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.md b/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.md new file mode 100644 index 000000000..f7315e736 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.md @@ -0,0 +1,22 @@ +```console +$ 03_05_default_values_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values_derive[EXE] [NAME] + +ARGS: + [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values_derive +name: "alice" + +$ 03_05_default_values_derive bob +name: "bob" + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.rs b/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.rs new file mode 100644 index 000000000..10a1ec808 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/03_05_default_values.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(default_value_t = String::from("alice"), value_parser)] + name: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.md b/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.md new file mode 100644 index 000000000..2523af924 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.md @@ -0,0 +1,29 @@ +```console +$ 04_01_enum_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum_derive[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum_derive fast +Hare + +$ 04_01_enum_derive slow +Tortoise + +$ 04_01_enum_derive medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.rs b/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.rs new file mode 100644 index 000000000..1ac984288 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_01_enum.rs @@ -0,0 +1,28 @@ +use clap::{Parser, ValueEnum}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// What mode to run the program in + #[clap(arg_enum, value_parser)] + mode: Mode, +} + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +enum Mode { + Fast, + Slow, +} + +fn main() { + let cli = Cli::parse(); + + match cli.mode { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.md b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.md new file mode 100644 index 000000000..6079ef193 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.md @@ -0,0 +1,31 @@ +```console +$ 04_02_parse_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse_derive[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse_derive 22 +PORT = 22 + +$ 04_02_parse_derive foobar +? failed +error: Invalid value "foobar" for '': invalid digit found in string + +For more information try --help + +$ 04_02_parse_derive 0 +? failed +error: Invalid value "0" for '': 0 is not in 1..=65535 + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.rs b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.rs new file mode 100644 index 000000000..6336a9cf1 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_parse.rs @@ -0,0 +1,15 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(value_parser = clap::value_parser!(u16).range(1..))] + port: u16, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.md b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.md new file mode 100644 index 000000000..cc43440ef --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.md @@ -0,0 +1,31 @@ +```console +$ 04_02_validate_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate_derive[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate_derive 22 +PORT = 22 + +$ 04_02_validate_derive foobar +? failed +error: Invalid value "foobar" for '': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate_derive 0 +? failed +error: Invalid value "0" for '': Port not in range 1-65535 + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.rs b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.rs new file mode 100644 index 000000000..7dac79c9f --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_02_validate.rs @@ -0,0 +1,34 @@ +use std::ops::RangeInclusive; + +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(value_parser = port_in_range)] + port: u16, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} + +const PORT_RANGE: RangeInclusive = 1..=65535; + +fn port_in_range(s: &str) -> Result { + let port: usize = s + .parse() + .map_err(|_| format!("`{}` isn't a port number", s))?; + if PORT_RANGE.contains(&port) { + Ok(port as u16) + } else { + Err(format!( + "Port not in range {}-{}", + PORT_RANGE.start(), + PORT_RANGE.end() + )) + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.md b/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.md new file mode 100644 index 000000000..4f5703d82 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.md @@ -0,0 +1,58 @@ +```console +$ 04_03_relations_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_03_relations_derive +? failed +error: The following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +USAGE: + 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations_derive --major +Version: 2.2.3 + +$ 04_03_relations_derive --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations_derive[EXE] <--set-ver |--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations_derive --major -c config.toml +? failed +error: The following required arguments were not provided: + > + +USAGE: + 04_03_relations_derive[EXE] -c <--set-ver |--major|--minor|--patch> > + +For more information try --help + +$ 04_03_relations_derive --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.rs b/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.rs new file mode 100644 index 000000000..37efe95e3 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_03_relations.rs @@ -0,0 +1,72 @@ +use clap::{ArgGroup, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(group( + ArgGroup::new("vers") + .required(true) + .args(&["set-ver", "major", "minor", "patch"]), + ))] +struct Cli { + /// set version manually + #[clap(long, value_name = "VER", value_parser)] + set_ver: Option, + + /// auto inc major + #[clap(long, action)] + major: bool, + + /// auto inc minor + #[clap(long, action)] + minor: bool, + + /// auto inc patch + #[clap(long, action)] + patch: bool, + + /// some regular input + #[clap(group = "input", value_parser)] + input_file: Option, + + /// some special input argument + #[clap(long, group = "input", value_parser)] + spec_in: Option, + + #[clap(short, requires = "input", value_parser)] + config: Option, +} + +fn main() { + let cli = Cli::parse(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set_ver was used to set the version manually + let version = if let Some(ver) = cli.set_ver.as_deref() { + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = (cli.major, cli.minor, cli.patch); + match (maj, min, pat) { + (true, _, _) => major += 1, + (_, true, _) => minor += 1, + (_, _, true) => patch += 1, + _ => unreachable!(), + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if let Some(config) = cli.config.as_deref() { + let input = cli + .input_file + .as_deref() + .unwrap_or_else(|| cli.spec_in.as_deref().unwrap()); + println!("Doing work using input {} and config {}", input, config); + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.md b/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.md new file mode 100644 index 000000000..0f19bfe31 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.md @@ -0,0 +1,57 @@ +```console +$ 04_04_custom_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_04_custom_derive +? failed +error: Can only modify one version field + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major +Version: 2.2.3 + +$ 04_04_custom_derive --major --minor +? failed +error: Can only modify one version field + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.rs b/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.rs new file mode 100644 index 000000000..454d489c1 --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/04_04_custom.rs @@ -0,0 +1,93 @@ +use clap::{CommandFactory, ErrorKind, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// set version manually + #[clap(long, value_name = "VER", value_parser)] + set_ver: Option, + + /// auto inc major + #[clap(long, action)] + major: bool, + + /// auto inc minor + #[clap(long, action)] + minor: bool, + + /// auto inc patch + #[clap(long, action)] + patch: bool, + + /// some regular input + #[clap(value_parser)] + input_file: Option, + + /// some special input argument + #[clap(long, value_parser)] + spec_in: Option, + + #[clap(short, value_parser)] + config: Option, +} + +fn main() { + let cli = Cli::parse(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = cli.set_ver.as_deref() { + if cli.major || cli.minor || cli.patch { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::ArgumentConflict, + "Can't do relative and absolute version change", + ) + .exit(); + } + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = (cli.major, cli.minor, cli.patch); + match (maj, min, pat) { + (true, false, false) => major += 1, + (false, true, false) => minor += 1, + (false, false, true) => patch += 1, + _ => { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::ArgumentConflict, + "Can only modify one version field", + ) + .exit(); + } + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if let Some(config) = cli.config.as_deref() { + // todo: remove `#[allow(clippy::or_fun_call)]` lint when MSRV is bumped. + #[allow(clippy::or_fun_call)] + let input = cli + .input_file + .as_deref() + // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const' + .or(cli.spec_in.as_deref()) + .unwrap_or_else(|| { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::MissingRequiredArgument, + "INPUT_FILE or --spec-in is required when using --config", + ) + .exit() + }); + println!("Doing work using input {} and config {}", input, config); + } +} diff --git a/vendor/clap-3.2.20/examples/tutorial_derive/05_01_assert.rs b/vendor/clap-3.2.20/examples/tutorial_derive/05_01_assert.rs new file mode 100644 index 000000000..66dca727f --- /dev/null +++ b/vendor/clap-3.2.20/examples/tutorial_derive/05_01_assert.rs @@ -0,0 +1,21 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(value_parser)] + port: u16, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} + +#[test] +fn verify_cli() { + use clap::CommandFactory; + Cli::command().debug_assert() +} diff --git a/vendor/clap-3.2.20/examples/typed-derive.md b/vendor/clap-3.2.20/examples/typed-derive.md new file mode 100644 index 000000000..9c7615c63 --- /dev/null +++ b/vendor/clap-3.2.20/examples/typed-derive.md @@ -0,0 +1,84 @@ +**This requires enabling the [`derive` feature flag][crate::_features].** + +Help: +```console +$ typed-derive --help +clap + +USAGE: + typed-derive[EXE] [OPTIONS] + +OPTIONS: + --bind Handle IP addresses + -D Hand-written parser for tuples + -h, --help Print help information + -I Allow invalid UTF-8 paths + -O Implicitly using `std::str::FromStr` + --sleep Allow human-readable durations + +``` + +Optimization-level (number) +```console +$ typed-derive -O 1 +Args { optimization: Some(1), include: None, bind: None, sleep: None, defines: [] } + +$ typed-derive -O plaid +? failed +error: Invalid value "plaid" for '-O ': invalid digit found in string + +For more information try --help + +``` + +Include (path) +```console +$ typed-derive -I../hello +Args { optimization: None, include: Some("../hello"), bind: None, sleep: None, defines: [] } + +``` + +IP Address +```console +$ typed-derive --bind 192.0.0.1 +Args { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, defines: [] } + +$ typed-derive --bind localhost +? failed +error: Invalid value "localhost" for '--bind ': invalid IP address syntax + +For more information try --help + +``` + +Time +```console +$ typed-derive --sleep 10s +Args { optimization: None, include: None, bind: None, sleep: Some(Duration(10s)), defines: [] } + +$ typed-derive --sleep forever +? failed +error: Invalid value "forever" for '--sleep ': expected number at 0 + +For more information try --help + +``` + +Defines (key-value pairs) +```console +$ typed-derive -D Foo=10 -D Alice=30 +Args { optimization: None, include: None, bind: None, sleep: None, defines: [("Foo", 10), ("Alice", 30)] } + +$ typed-derive -D Foo +? failed +error: Invalid value "Foo" for '-D ': invalid KEY=value: no `=` found in `Foo` + +For more information try --help + +$ typed-derive -D Foo=Bar +? failed +error: Invalid value "Foo=Bar" for '-D ': invalid digit found in string + +For more information try --help + +``` diff --git a/vendor/clap-3.2.20/examples/typed-derive.rs b/vendor/clap-3.2.20/examples/typed-derive.rs new file mode 100644 index 000000000..31084029d --- /dev/null +++ b/vendor/clap-3.2.20/examples/typed-derive.rs @@ -0,0 +1,44 @@ +use clap::Parser; +use std::error::Error; + +#[derive(Parser, Debug)] // requires `derive` feature +struct Args { + /// Implicitly using `std::str::FromStr` + #[clap(short = 'O', value_parser)] + optimization: Option, + + /// Allow invalid UTF-8 paths + #[clap(short = 'I', value_parser, value_name = "DIR", value_hint = clap::ValueHint::DirPath)] + include: Option, + + /// Handle IP addresses + #[clap(long, value_parser)] + bind: Option, + + /// Allow human-readable durations + #[clap(long, value_parser)] + sleep: Option, + + /// Hand-written parser for tuples + #[clap(short = 'D', value_parser = parse_key_val::)] + defines: Vec<(String, i32)>, +} + +/// Parse a single key-value pair +fn parse_key_val(s: &str) -> Result<(T, U), Box> +where + T: std::str::FromStr, + T::Err: Error + Send + Sync + 'static, + U: std::str::FromStr, + U::Err: Error + Send + Sync + 'static, +{ + let pos = s + .find('=') + .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; + Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) +} + +fn main() { + let args = Args::parse(); + println!("{:?}", args); +} diff --git a/vendor/clap-3.2.20/src/_cookbook/cargo_example.rs b/vendor/clap-3.2.20/src/_cookbook/cargo_example.rs new file mode 100644 index 000000000..ec5d582db --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/cargo_example.rs @@ -0,0 +1,7 @@ +//! # Example: cargo subcommand (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/cargo-example.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/cargo-example.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/cargo_example_derive b/vendor/clap-3.2.20/src/_cookbook/cargo_example_derive new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/clap-3.2.20/src/_cookbook/cargo_example_derive.rs b/vendor/clap-3.2.20/src/_cookbook/cargo_example_derive.rs new file mode 100644 index 000000000..d49f956f9 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/cargo_example_derive.rs @@ -0,0 +1,7 @@ +//! # Example: cargo subcommand (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/cargo-example-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/cargo-example-derive.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/escaped_positional.rs b/vendor/clap-3.2.20/src/_cookbook/escaped_positional.rs new file mode 100644 index 000000000..99a3f83f3 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/escaped_positional.rs @@ -0,0 +1,7 @@ +//! # Example (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/escaped-positional.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/escaped-positional.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/escaped_positional_derive.rs b/vendor/clap-3.2.20/src/_cookbook/escaped_positional_derive.rs new file mode 100644 index 000000000..e6f99ad17 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/escaped_positional_derive.rs @@ -0,0 +1,7 @@ +//! # Example (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/escaped-positional-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/escaped-positional-derive.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/git.rs b/vendor/clap-3.2.20/src/_cookbook/git.rs new file mode 100644 index 000000000..03a926ca8 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/git.rs @@ -0,0 +1,7 @@ +//! # Example: git-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/git.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/git.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/git_derive.rs b/vendor/clap-3.2.20/src/_cookbook/git_derive.rs new file mode 100644 index 000000000..d3119736d --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/git_derive.rs @@ -0,0 +1,7 @@ +//! # Example: git-like CLI (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/git-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/git-derive.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/mod.rs b/vendor/clap-3.2.20/src/_cookbook/mod.rs new file mode 100644 index 000000000..1a78ed11b --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/mod.rs @@ -0,0 +1,55 @@ +// Contributing +// +// New examples: +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// - Link the `.md` file from here + +//! # Documentation: Cookbook +//! +//! Typed arguments: [derive][typed_derive] +//! - Topics: +//! - Custom `parse()` +//! +//! Custom cargo command: [builder][cargo_example], [derive][cargo_example_derive] +//! - Topics: +//! - Subcommands +//! - Cargo plugins +//! +//! git-like interface: [builder][git], [derive][git_derive] +//! - Topics: +//! - Subcommands +//! - External subcommands +//! - Optional subcommands +//! - Default subcommands +//! +//! pacman-like interface: [builder][pacman] +//! - Topics: +//! - Flag subcommands +//! - Conflicting arguments +//! +//! Escaped positionals with `--`: [builder][escaped_positional], [derive][escaped_positional_derive] +//! +//! Multi-call +//! - busybox: [builder][multicall_busybox] +//! - Topics: +//! - Subcommands +//! - hostname: [builder][multicall_hostname] +//! - Topics: +//! - Subcommands +//! +//! repl: [builder][repl] +//! - Topics: +//! - Read-Eval-Print Loops / Custom command lines + +pub mod cargo_example; +pub mod cargo_example_derive; +pub mod escaped_positional; +pub mod escaped_positional_derive; +pub mod git; +pub mod git_derive; +pub mod multicall_busybox; +pub mod multicall_hostname; +pub mod pacman; +pub mod repl; +pub mod typed_derive; diff --git a/vendor/clap-3.2.20/src/_cookbook/multicall_busybox.rs b/vendor/clap-3.2.20/src/_cookbook/multicall_busybox.rs new file mode 100644 index 000000000..e3384d682 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/multicall_busybox.rs @@ -0,0 +1,7 @@ +//! # Example: busybox-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/multicall-busybox.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/multicall-busybox.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/multicall_hostname.rs b/vendor/clap-3.2.20/src/_cookbook/multicall_hostname.rs new file mode 100644 index 000000000..9777654dc --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/multicall_hostname.rs @@ -0,0 +1,7 @@ +//! # Example: hostname-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/multicall-hostname.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/multicall-hostname.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/pacman.rs b/vendor/clap-3.2.20/src/_cookbook/pacman.rs new file mode 100644 index 000000000..880c58158 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/pacman.rs @@ -0,0 +1,7 @@ +//! # Example: pacman-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/pacman.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/pacman.md")] diff --git a/vendor/clap-3.2.20/src/_cookbook/repl.rs b/vendor/clap-3.2.20/src/_cookbook/repl.rs new file mode 100644 index 000000000..549ec8259 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/repl.rs @@ -0,0 +1,5 @@ +//! # Example: Command REPL (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/repl.rs")] +//! ``` diff --git a/vendor/clap-3.2.20/src/_cookbook/typed_derive.rs b/vendor/clap-3.2.20/src/_cookbook/typed_derive.rs new file mode 100644 index 000000000..a5fd15ff8 --- /dev/null +++ b/vendor/clap-3.2.20/src/_cookbook/typed_derive.rs @@ -0,0 +1,7 @@ +//! # Example: Custom Types (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/typed-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/typed-derive.md")] diff --git a/vendor/clap-3.2.20/src/_derive/_tutorial.rs b/vendor/clap-3.2.20/src/_derive/_tutorial.rs new file mode 100644 index 000000000..abd57cef8 --- /dev/null +++ b/vendor/clap-3.2.20/src/_derive/_tutorial.rs @@ -0,0 +1,205 @@ +// Contributing +// +// New example code: +// - Please update the corresponding section in the derive tutorial +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// +// See also the general CONTRIBUTING + +//! # Documentation: Derive Tutorial +//! +//! 1. [Quick Start](#quick-start) +//! 2. [Configuring the Parser](#configuring-the-parser) +//! 3. [Adding Arguments](#adding-arguments) +//! 1. [Positionals](#positionals) +//! 2. [Options](#options) +//! 3. [Flags](#flags) +//! 4. [Subcommands](#subcommands) +//! 5. [Defaults](#defaults) +//! 4. Validation +//! 1. [Enumerated values](#enumerated-values) +//! 2. [Validated values](#validated-values) +//! 3. [Argument Relations](#argument-relations) +//! 4. [Custom Validation](#custom-validation) +//! 5. [Testing](#testing) +//! +//! See also +//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis] +//! - The [cookbook][crate::_cookbook] for more application-focused examples +//! +//! ## Quick Start +//! +//! You can create an application declaratively with a `struct` and some +//! attributes. **This requires enabling the [`derive` feature flag][crate::_features].** +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/01_quick.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/01_quick.md")] +//! +//! ## Configuring the Parser +//! +//! You use derive [`Parser`][crate::Parser] to start building a parser. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_apps.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/02_apps.md")] +//! +//! You can use `#[clap(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_crate.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/02_crate.md")] +//! +//! You can use attributes to change the application level behavior of clap. Any [`Command`][crate::Command]] builder function can be used as an attribute. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.md")] +//! +//! ## Adding Arguments +//! +//! ### Positionals +//! +//! You can have users specify values by their position on the command-line: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.md")] +//! +//! ### Options +//! +//! You can name your arguments with a flag: +//! - Order doesn't matter +//! - They can be optional +//! - Intent is clearer +//! +//! The `#[clap(short = 'n')]` and `#[clap(long = "name")]` attributes that define +//! the flags are [`Arg`][crate::Args] methods that are derived from the field name when no value +//! is specified (`#[clap(short)]` and `#[clap(long)]`). +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.md")] +//! +//! ### Flags +//! +//! Flags can also be switches that can be on/off. This is enabled via the +//! `#[clap(action = ArgAction::SetTrue)]` attribute though this is implied when the field is a +//! `bool`. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.md")] +//! +//! Or counted with `#[clap(action = clap::ArgAction::Count)]`: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.md")] +//! +//! ### Subcommands +//! +//! Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[clap(subcommand)]` attribute. Each +//! instance of a [Subcommand][crate::Subcommand] can have its own version, author(s), Args, and even its own +//! subcommands. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.rs")] +//! ``` +//! We used a struct-variant to define the `add` subcommand. +//! Alternatively, you can use a struct for your subcommand's arguments: +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands_alt.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.md")] +//! +//! ### Defaults +//! +//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional. +//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can +//! set `#[clap(default_value_t)]`. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.md")] +//! +//! ## Validation +//! +//! ### Enumerated values +//! +//! If you have arguments of specific values you want to test for, you can derive +//! [`ValueEnum`][crate::ValueEnum]. +//! +//! This allows you specify the valid values for that argument. If the user does not use one of +//! those specific values, they will receive a graceful exit with error message informing them +//! of the mistake, and what the possible valid values are +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.md")] +//! +//! ### Validated values +//! +//! More generally, you can validate and parse into any data type. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.md")] +//! +//! A custom parser can be used to improve the error messages or provide additional validation: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.md")] +//! +//! ### Argument Relations +//! +//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even +//! [`ArgGroup`][crate::ArgGroup]s. +//! +//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list +//! each individually, or when you want a rule to apply "any but not all" arguments. +//! +//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one +//! argument to be present out of a given set. Imagine that you had multiple arguments, and you +//! want one of them to be required, but making all of them required isn't feasible because perhaps +//! they conflict with each other. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.md")] +//! +//! ### Custom Validation +//! +//! As a last resort, you can create custom errors with the basics of clap's formatting. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.md")] +//! +//! ## Testing +//! +//! clap reports most development errors as `debug_assert!`s. Rather than checking every +//! subcommand, you should have a test that calls +//! [`Command::debug_assert`][crate::App::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../../examples/tutorial_derive/05_01_assert.rs")] +//! ``` diff --git a/vendor/clap-3.2.20/src/_derive/mod.rs b/vendor/clap-3.2.20/src/_derive/mod.rs new file mode 100644 index 000000000..fc9f35db5 --- /dev/null +++ b/vendor/clap-3.2.20/src/_derive/mod.rs @@ -0,0 +1,510 @@ +//! # Documentation: Derive Reference +//! +//! 1. [Overview](#overview) +//! 2. [Attributes](#attributes) +//! 1. [Terminology](#terminology) +//! 2. [Command Attributes](#command-attributes) +//! 3. [Arg Attributes](#arg-attributes) +//! 4. [ValueEnum Attributes](#valueenum-attributes) +//! 5. [Possible Value Attributes](#possible-value-attributes) +//! 3. [Arg Types](#arg-types) +//! 4. [Doc Comments](#doc-comments) +//! 5. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis) +//! 6. [Tips](#tips) +//! +//! ## Overview +//! +//! To derive `clap` types, you need to enable the [`derive` feature flag][crate::_features]. +//! +//! Example: +//! ```rust +#![doc = include_str!("../../examples/demo.rs")] +//! ``` +//! +//! Let's start by breaking down the anatomy of the derive attributes: +//! ```rust +//! use clap::{Parser, Args, Subcommand, ValueEnum}; +//! +//! /// Doc comment +//! #[derive(Parser)] +//! #[clap(APP ATTRIBUTE)] +//! struct Cli { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! +//! #[clap(value_enum, ARG ATTRIBUTE...)] +//! field: EnumValues, +//! +//! #[clap(flatten)] +//! delegate: Struct, +//! +//! #[clap(subcommand)] +//! command: Command, +//! } +//! +//! /// Doc comment +//! #[derive(Args)] +//! #[clap(PARENT APP ATTRIBUTE)] +//! struct Struct { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! +//! /// Doc comment +//! #[derive(Subcommand)] +//! #[clap(PARENT APP ATTRIBUTE)] +//! enum Command { +//! /// Doc comment +//! #[clap(APP ATTRIBUTE)] +//! Variant1(Struct), +//! +//! /// Doc comment +//! #[clap(APP ATTRIBUTE)] +//! Variant2 { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! } +//! +//! /// Doc comment +//! #[derive(ValueEnum)] +//! #[clap(VALUE ENUM ATTRIBUTE)] +//! enum EnumValues { +//! /// Doc comment +//! #[clap(POSSIBLE VALUE ATTRIBUTE)] +//! Variant1, +//! } +//! +//! fn main() { +//! let cli = Cli::parse(); +//! } +//! ``` +//! +//! Traits: +//! - [`Parser`][crate::Parser] parses arguments into a `struct` (arguments) or `enum` (subcommands). +//! - [`Args`][crate::Args] allows defining a set of re-usable arguments that get merged into their parent container. +//! - [`Subcommand`][crate::Subcommand] defines available subcommands. +//! - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant. +//! - [`ValueEnum`][crate::ValueEnum] allows parsing a value directly into an `enum`, erroring on unsupported values. +//! - The derive doesn't work on enums that contain non-unit variants, unless they are skipped +//! +//! *See also the [derive tutorial][crate::_derive::_tutorial] and [cookbook][crate::_cookbook]* +//! +//! ## Attributes +//! +//! ### Terminology +//! +//! **Raw attributes** are forwarded directly to the underlying [`clap` builder][crate::builder]. Any +//! [`Command`][crate::Command], [`Arg`][crate::Arg], or [`PossibleValue`][crate::PossibleValue] method can be used as an attribute. +//! +//! Raw attributes come in two different syntaxes: +//! ```rust,ignore +//! #[clap( +//! global = true, // name = arg form, neat for one-arg methods +//! required_if_eq("out", "file") // name(arg1, arg2, ...) form. +//! )] +//! ``` +//! +//! - `method = arg` can only be used for methods which take only one argument. +//! - `method(arg1, arg2)` can be used with any method. +//! +//! As long as `method_name` is not one of the magical methods it will be +//! translated into a mere method call. +//! +//! **Magic attributes** have post-processing done to them, whether that is +//! - Providing of defaults +//! - Special behavior is triggered off of it +//! +//! Magic attributes are more constrained in the syntax they support, usually just +//! ` = ` though some use `()` instead. See the specific +//! magic attributes documentation for details. This allows users to access the +//! raw behavior of an attribute via `()` syntax. +//! +//! **NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc +//! Comments](#doc-comments). Explicit attributes take precedence over inferred +//! attributes. +//! +//! ### Command Attributes +//! +//! These correspond to a [`Command`][crate::Command] which is used for both top-level parsers and +//! when defining subcommands. +//! +//! **Raw attributes:** Any [`Command` method][crate::Command] can also be used as an attribute, +//! see [Terminology](#terminology) for syntax. +//! - e.g. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` +//! +//! **Magic attributes:** +//! - `name = `: [`Command::name`][crate::App::name] +//! - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (if on [`Parser`][crate::Parser] container), variant name (if on [`Subcommand`][crate::Subcommand] variant) +//! - `version [= ]`: [`Command::version`][crate::App::version] +//! - When not present: no version set +//! - Without ``: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field) +//! - `author [= ]`: [`Command::author`][crate::App::author] +//! - When not present: no author set +//! - Without ``: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field) +//! - `about [= ]`: [`Command::about`][crate::App::about] +//! - When not present: [Doc comment summary](#doc-comments) +//! - Without ``: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) ([`Parser`][crate::Parser] container) +//! - **TIP:** When a doc comment is also present, you most likely want to add +//! `#[clap(long_about = None)]` to clear the doc comment so only [`about`][crate::App::about] +//! gets shown with both `-h` and `--help`. +//! - `long_about = `: [`Command::long_about`][crate::App::long_about] +//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::App::about] / [`long_about`][crate::App::long_about] +//! - `next_display_order`: [`Command::next_display_order`][crate::App::next_display_order] +//! - `next_help_heading`: [`Command::next_help_heading`][crate::App::next_help_heading] +//! - When `flatten`ing [`Args`][crate::Args], this is scoped to just the args in this struct and any struct `flatten`ed into it +//! - `rename_all = `: Override default field / variant name case conversion for [`Command::name`][crate::Command::name] / [`Arg::id`][crate::Arg::id] +//! - When not present: `"kebab-case"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! - `rename_all_env = `: Override default field name case conversion for env variables for [`Arg::env`][crate::Arg::env] +//! - When not present: `"SCREAMING_SNAKE_CASE"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! +//! And for [`Subcommand`][crate::Subcommand] variants: +//! - `skip`: Ignore this variant +//! - `flatten`: Delegates to the variant for more subcommands (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - `subcommand`: Nest subcommands under the current set of subcommands (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - `external_subcommand`: [`Command::allow_external_subcommand(true)`][crate::App::allow_external_subcommands] +//! - Variant must be either `Variant(Vec)` or `Variant(Vec)` +//! +//! ### Arg Attributes +//! +//! These correspond to a [`Arg`][crate::Arg]. +//! +//! **Raw attributes:** Any [`Arg` method][crate::Arg] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[clap(max_values(3))]` would translate to `arg.max_values(3)` +//! +//! **Magic attributes**: +//! - `id = `: [`Arg::id`][crate::Arg::id] +//! - When not present: case-converted field name is used +//! - `name = `: [`Arg::id`][crate::Arg::id] +//! - **Deprecated:** use `id` +//! - `value_parser [= ]`: [`Arg::value_parser`][crate::Arg::value_parser] +//! - When not present: will auto-select an implementation based on the field type using +//! [`value_parser!][crate::value_parser!] +//! - When present but defaulted: opt-in to clap v4 semantics +//! - Env parsing is now dependent on inferred parser +//! - `PathBuf` will implicitly skip UTF-8 validation (before it required specifying +//! `try_from_os_str`) +//! - When present, implies `#[clap(action)]` +//! - To register a custom type's [`ValueParser`][crate::builder::ValueParser], implement [`ValueParserFactory`][crate::builder::ValueParserFactory] +//! - `action [= ]`: [`Arg::action`][crate::Arg::action] +//! - When not present: will auto-select an action based on the field type +//! - When present but defaulted: opt-in to clap v4 semantics +//! - When present, implies `#[clap(value_parser)]` +//! - `args_override_self` is forced on for single flags +//! - `help = `: [`Arg::help`][crate::Arg::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! - `long_help = `: [`Arg::long_help`][crate::Arg::long_help] +//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`help`][crate::Arg::help] / [`long_help`][crate::Arg::long_help] +//! - `short [= ]`: [`Arg::short`][crate::Arg::short] +//! - When not present: no short set +//! - Without ``: defaults to first character in the case-converted field name +//! - `long [= ]`: [`Arg::long`][crate::Arg::long] +//! - When not present: no long set +//! - Without ``: defaults to the case-converted field name +//! - `env [= ]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled) +//! - When not present: no env set +//! - Without ``: defaults to the case-converted field name +//! - `flatten`: Delegates to the field for more arguments (must implement [`Args`][crate::Args]) +//! - Only [`next_help_heading`][crate::Command::next_help_heading] can be used with `flatten`. See +//! [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why +//! arg attributes are not generally supported. +//! - **Tip:** Though we do apply a flattened [`Args`][crate::Args]'s Parent Command Attributes, this +//! makes reuse harder. Generally prefer putting the cmd attributes on the +//! [`Parser`][crate::Parser] or on the flattened field. +//! - `subcommand`: Delegates definition of subcommands to the field (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - When `Option`, the subcommand becomes optional +//! - `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in +//! - `parse( [= ])`: [`Arg::validator`][crate::Arg::validator] and [`ArgMatches::values_of_t`][crate::ArgMatches::values_of_t] +//! - **Deprecated:** +//! - Use `value_parser(...)` for `from_str`, `try_from_str`, `from_os_str`, and `try_from_os_str` +//! - Use `action(ArgAction::Count` for `from_occurrences` +//! - Use `action(ArgAction::SetTrue` for `from_flag` +//! - Default: `try_from_str` +//! - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` +//! - See [Arg Types](#arg-types) for more details +//! - `value_enum`: Parse the value using the [`ValueEnum`][crate::ValueEnum] +//! - `skip [= ]`: Ignore this field, filling in with `` +//! - Without ``: fills the field with `Default::default()` +//! - `default_value = `: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required] +//! - `default_value_t [= ]`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires `std::fmt::Display` or `#[clap(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `default_values_t = `: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::fmt::Display` or `#[clap(value_enum)]` +//! - `` must implement `IntoIterator` +//! - `default_value_os_t [= ]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires `std::convert::Into` or `#[clap(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `default_values_os_t = `: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::convert::Into` or `#[clap(value_enum)]` +//! - `` must implement `IntoIterator` +//! +//! ### ValueEnum Attributes +//! +//! - `rename_all = `: Override default field / variant name case conversion for [`PossibleValue::new`][crate::PossibleValue] +//! - When not present: `"kebab-case"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! +//! ### Possible Value Attributes +//! +//! These correspond to a [`PossibleValue`][crate::PossibleValue]. +//! +//! **Raw attributes:** Any [`PossibleValue` method][crate::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")` +//! +//! **Magic attributes**: +//! - `name = `: [`PossibleValue::new`][crate::PossibleValue::new] +//! - When not present: case-converted field name is used +//! - `help = `: [`PossibleValue::help`][crate::PossibleValue::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! +//! ## Arg Types +//! +//! `clap` assumes some intent based on the type used: +//! +//! | Type | Effect | Implies | +//! |---------------------|--------------------------------------|------------------------------------------------------------------| +//! | `bool` | flag | `#[clap(parse(from_flag))]` | +//! | `Option` | optional argument | `.takes_value(true).required(false)` | +//! | `Option>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` | +//! | `T` | required argument | `.takes_value(true).required(!has_default)` | +//! | `Vec` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | +//! | `Option>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | +//! +//! Notes: +//! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones +//! - For example, see [custom-bool](./custom-bool.md) +//! - `Option>` will be `None` instead of `vec![]` if no arguments are provided. +//! - This gives the user some flexibility in designing their argument, like with `min_values(0)` +//! +//! You can then support your custom type with `#[clap(parse( [= ]))]`: +//! +//! | `` | Signature | Default `` | +//! |--------------------------|---------------------------------------|---------------------------------| +//! | `from_str` | `fn(&str) -> T` | `::std::convert::From::from` | +//! | `try_from_str` (default) | `fn(&str) -> Result` | `::std::str::FromStr::from_str` | +//! | `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` | +//! | `try_from_os_str` | `fn(&OsStr) -> Result` | (no default function) | +//! | `from_occurrences` | `fn(u64) -> T` | `value as T` | +//! | `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` | +//! +//! Notes: +//! - `from_os_str`: +//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +//! - `try_from_os_str`: +//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +//! - `from_occurrences`: +//! - Implies `arg.takes_value(false).multiple_occurrences(true)` +//! - Reads from `clap::ArgMatches::occurrences_of` rather than a `get_one` function +//! - Note: operations on values, like `default_value`, are unlikely to do what you want +//! - `from_flag` +//! - Implies `arg.takes_value(false)` +//! - Reads from `clap::ArgMatches::is_present` rather than a `get_one` function +//! - Note: operations on values, like `default_value`, are unlikely to do what you want +//! +//! **Warning:** +//! - To support non-UTF8 paths, you should use `#[clap(value_parser)]` otherwise +//! `clap` will parse it as a `String` which will fail on some paths. +//! +//! ## Doc Comments +//! +//! In clap, help messages for the whole binary can be specified +//! via [`Command::about`][crate::App::about] and [`Command::long_about`][crate::App::long_about] while help messages +//! for individual arguments can be specified via [`Arg::help`][crate::Arg::help] and [`Arg::long_help`][crate::Arg::long_help]. +//! +//! `long_*` variants are used when user calls the program with +//! `--help` and "short" variants are used with `-h` flag. +//! +//! ```rust +//! # use clap::Parser; +//! +//! #[derive(Parser)] +//! #[clap(about = "I am a program and I work, just pass `-h`", long_about = None)] +//! struct Foo { +//! #[clap(short, help = "Pass `-h` and you'll see me!")] +//! bar: String, +//! } +//! ``` +//! +//! For convenience, doc comments can be used instead of raw methods +//! (this example works exactly like the one above): +//! +//! ```rust +//! # use clap::Parser; +//! +//! #[derive(Parser)] +//! /// I am a program and I work, just pass `-h` +//! struct Foo { +//! /// Pass `-h` and you'll see me! +//! bar: String, +//! } +//! ``` +//! +//! **NOTE:** Attributes have priority over doc comments! +//! +//! **Top level doc comments always generate `Command::about/long_about` calls!** +//! If you really want to use the `Command::about/long_about` methods (you likely don't), +//! use the `about` / `long_about` attributes to override the calls generated from +//! the doc comment. To clear `long_about`, you can use +//! `#[clap(long_about = None)]`. +//! +//! **TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time. +//! +//! ### Pre-processing +//! +//! ```rust +//! # use clap::Parser; +//! #[derive(Parser)] +//! /// Hi there, I'm Robo! +//! /// +//! /// I like beeping, stumbling, eating your electricity, +//! /// and making records of you singing in a shower. +//! /// Pay up, or I'll upload it to youtube! +//! struct Robo { +//! /// Call my brother SkyNet. +//! /// +//! /// I am artificial superintelligence. I won't rest +//! /// until I'll have destroyed humanity. Enjoy your +//! /// pathetic existence, you mere mortals. +//! #[clap(long, action)] +//! kill_all_humans: bool, +//! } +//! ``` +//! +//! A doc comment consists of three parts: +//! - Short summary +//! - A blank line (whitespace only) +//! - Detailed description, all the rest +//! +//! The summary corresponds with `Command::about` / `Arg::help`. When a blank line is +//! present, the whole doc comment will be passed to `Command::long_about` / +//! `Arg::long_help`. Or in other words, a doc may result in just a `Command::about` / +//! `Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` / +//! `Arg::long_help` +//! +//! In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including: +//! +//! - Strip leading and trailing whitespace from every line, if present. +//! +//! - Strip leading and trailing blank lines, if present. +//! +//! - Interpret each group of non-empty lines as a word-wrapped paragraph. +//! +//! We replace newlines within paragraphs with spaces to allow the output +//! to be re-wrapped to the terminal width. +//! +//! - Strip any excess blank lines so that there is exactly one per paragraph break. +//! +//! - If the first paragraph ends in exactly one period, +//! remove the trailing period (i.e. strip trailing periods but not trailing ellipses). +//! +//! Sometimes you don't want this preprocessing to apply, for example the comment contains +//! some ASCII art or markdown tables, you would need to preserve LFs along with +//! blank lines and the leading/trailing whitespace. When you pass use the +//! `verbatim_doc_comment` magic attribute, you preserve +//! them. +//! +//! **Note:** Keep in mind that `verbatim_doc_comment` will *still* +//! - Remove one leading space from each line, even if this attribute is present, +//! to allow for a space between `///` and the content. +//! - Remove leading and trailing blank lines +//! +//! ## Mixing Builder and Derive APIs +//! +//! The builder and derive APIs do not live in isolation. They can work together, which is +//! especially helpful if some arguments can be specified at compile-time while others must be +//! specified at runtime. +//! +//! ### Using derived arguments in a builder application +//! +//! When using the derive API, you can `#[clap(flatten)]` a struct deriving `Args` into a struct +//! deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance +//! created using the builder API with `Args` created using the derive API. +//! +//! It uses the [`Args::augment_args`][crate::Args::augment_args] method to add the arguments to +//! the `Command` instance. +//! +//! Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide +//! structs that implement `Args`. Without the technique shown in this example, it would not be +//! possible to use such crates with the builder API. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/augment_args.rs")] +//! ``` +//! +//! ### Using derived subcommands in a builder application +//! +//! When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also add the subcommands in that enum to a `Command` instance created with the builder API. +//! +//! It uses the [`Subcommand::augment_subcommands`][crate::Subcommand::augment_subcommands] method +//! to add the subcommands to the `Command` instance. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/augment_subcommands.rs")] +//! ``` +//! +//! ### Adding hand-implemented subcommands to a derived application +//! +//! When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also implement the `Subcommand` trait manually on this enum (or any other type) and it can +//! still be used inside the struct created with the derive API. The implementation of the +//! `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance +//! created behind the scenes for you by the derive API. +//! +//! Notice how in the previous example we used +//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] on an enum that derived +//! `Parser`, whereas now we implement +//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] ourselves, but the derive API +//! calls it automatically since we used the `#[clap(subcommand)]` attribute. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/hand_subcommand.rs")] +//! ``` +//! +//! ### Flattening hand-implemented args into a derived application +//! +//! When using the derive API, you can use `#[clap(flatten)]` inside the struct to add arguments as +//! if they were added directly to the containing struct. The type of the field is usually an +//! struct that derived `Args`. However, you can also implement the `Args` trait manually on this +//! struct (or any other type) and it can still be used inside the struct created with the derive +//! API. The implementation of the `Args` trait will use the builder API to add the arguments to +//! the `Command` instance created behind the scenes for you by the derive API. +//! +//! Notice how in the previous example we used [`augment_args`][crate::Args::augment_args] on the +//! struct that derived `Parser`, whereas now we implement +//! [`augment_args`][crate::Args::augment_args] ourselves, but the derive API calls it +//! automatically since we used the `#[clap(flatten)]` attribute. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/flatten_hand_args.rs")] +//! ``` +//! +//! ## Tips +//! +//! - To get access to a [`Command`][crate::Command] call +//! [`CommandFactory::command`][crate::CommandFactory::command] (implemented when deriving +//! [`Parser`][crate::Parser]) +//! - Proactively check for bad [`Command`][crate::Command] configurations by calling +//! [`Command::debug_assert`][crate::App::debug_assert] in a test +//! ([example](../tutorial_derive/05_01_assert.rs)) + +pub mod _tutorial; +#[doc(inline)] +pub use crate::_cookbook; diff --git a/vendor/clap-3.2.20/src/_faq.rs b/vendor/clap-3.2.20/src/_faq.rs new file mode 100644 index 000000000..661a7e73d --- /dev/null +++ b/vendor/clap-3.2.20/src/_faq.rs @@ -0,0 +1,95 @@ +//! # Documentation: FAQ +//! +//! 1. [Comparisons](#comparisons) +//! 1. [How does `clap` compare to structopt?](#how-does-clap-compare-to-structopt) +//! 2. [What are some reasons to use `clap`? (The Pitch)](#what-are-some-reasons-to-use-clap-the-pitch) +//! 3. [What are some reasons *not* to use `clap`? (The Anti Pitch)](#what-are-some-reasons-not-to-use-clap-the-anti-pitch) +//! 4. [Reasons to use `clap`](#reasons-to-use-clap) +//! 2. [How many approaches are there to create a parser?](#how-many-approaches-are-there-to-create-a-parser) +//! 3. [When should I use the builder vs derive APIs?](#when-should-i-use-the-builder-vs-derive-apis) +//! 4. [Why is there a default subcommand of help?](#why-is-there-a-default-subcommand-of-help) +//! +//! ### Comparisons +//! +//! First, let me say that these comparisons are highly subjective, and not meant +//! in a critical or harsh manner. All the argument parsing libraries out there (to +//! include `clap`) have their own strengths and weaknesses. Sometimes it just +//! comes down to personal taste when all other factors are equal. When in doubt, +//! try them all and pick one that you enjoy :) There's plenty of room in the Rust +//! community for multiple implementations! +//! +//! For less detailed but more broad comparisons, see +//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs). +//! +//! #### How does `clap` compare to [structopt](https://github.com/TeXitoi/structopt)? +//! +//! Simple! `clap` *is* `structopt`. `structopt` started as a derive API built on +//! top of clap v2. With clap v3, we've forked structopt and integrated it +//! directly into clap. structopt is in +//! [maintenance mode](https://github.com/TeXitoi/structopt/issues/516#issuecomment-989566094) +//! with the release of `clap_derive`. +//! +//! The benefits of integrating `structopt` and `clap` are: +//! - Easier cross-linking in documentation +//! - [Documentation parity](../examples) +//! - Tighter design feedback loop, ensuring all new features are designed with +//! derives in mind and easier to change `clap` in response to `structopt` bugs. +//! - Clearer endorsement of `structopt` +//! +//! See also +//! - [`clap` v3 CHANGELOG](../CHANGELOG.md#300---2021-12-31) +//! - [`structopt` migration guide](../CHANGELOG.md#migrate-structopt) +//! +//! #### What are some reasons to use `clap`? (The Pitch) +//! +//! `clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap` when just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex, and advanced requirements, without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs. +//! +//! #### What are some reasons *not* to use `clap`? (The Anti Pitch) +//! +//! Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many finetuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways which may be contrary to some users use-cases. +//! +//! #### Reasons to use `clap` +//! +//! * You want all the nice CLI features your users may expect, yet you don't want to implement them all yourself. You'd like to focus your application, not argument parsing. +//! * In addition to the point above; you don't want to sacrifice performance to get all those nice features +//! * You have complex requirements/conflicts between your various valid args. +//! * You want to use subcommands (although other libraries also support subcommands, they are not nearly as feature rich as those provided by `clap`) +//! * You want some sort of custom validation built into the argument parsing process, instead of as part of your application (which allows for earlier failures, better error messages, more cohesive experience, etc.) +//! +//! ### How many approaches are there to create a parser? +//! +//! The following APIs are supported: +//! - [Derive][crate::_derive::_tutorial] +//! - [Builder][crate::_tutorial] +//! +//! Previously, we supported: +//! - [YAML](https://github.com/clap-rs/clap/issues/3087) +//! - [docopt](http://docopt.org/)-inspired [usage parser](https://github.com/clap-rs/clap/issues/3086) +//! - [`clap_app!`](https://github.com/clap-rs/clap/issues/2835) +//! +//! There are also experiments with other APIs: +//! - [fncmd](https://github.com/yuhr/fncmd): function attribute +//! - [clap-serde](https://github.com/aobatact/clap-serde): create an `Command` from a deserializer +//! +//! ### When should I use the builder vs derive APIs? +//! +//! Our default answer is to use the [Derive API][crate::_derive::_tutorial]: +//! - Easier to read, write, and modify +//! - Easier to keep the argument declaration and reading of argument in sync +//! - Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) +//! +//! The [Builder API][crate::_tutorial] is a lower-level API that someone might want to use for +//! - Faster compile times if you aren't already using other procedural macros +//! - More flexibility, e.g. you can look up an [arguments values][crate::ArgMatches::get_many], +//! their [ordering with other arguments][crate::ArgMatches::indices_of], and [what set +//! them][crate::ArgMatches::value_source]. The Derive API can only report values and not +//! indices of or other data. +//! +//! You can [interop between Derive and Builder APIs][crate::_derive#mixing-builder-and-derive-apis]. +//! +//! ### Why is there a default subcommand of help? +//! +//! There is only a default subcommand of `help` when other subcommands have been defined manually. So it's opt-in(ish), being that you only get a `help` subcommand if you're actually using subcommands. +//! +//! Also, if the user defined a `help` subcommand themselves, the auto-generated one wouldn't be added (meaning it's only generated if the user hasn't defined one themselves). +//! diff --git a/vendor/clap-3.2.20/src/_features.rs b/vendor/clap-3.2.20/src/_features.rs new file mode 100644 index 000000000..923134c45 --- /dev/null +++ b/vendor/clap-3.2.20/src/_features.rs @@ -0,0 +1,27 @@ +//! ## Documentation: Feature Flags +//! +//! Available [compile-time feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) +//! +//! #### Default Features +//! +//! * **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner. +//! * **color**: Turns on colored error messages. +//! * **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. +//! +//! #### Optional features +//! +//! * **deprecated**: Guided experience to prepare for next breaking release (at different stages of development, this may become default) +//! * **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above. +//! * **cargo**: Turns on macros that read values from [`CARGO_*` environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates). +//! * **env**: Turns on the usage of environment variables during parsing. +//! * **regex**: Enables regex validators. +//! * **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. +//! * **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. +//! +//! #### Experimental features +//! +//! **Warning:** These may contain breaking changes between minor releases. +//! +//! * **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) +//! * **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) +//! * **unstable-v4**: Preview features which will be stable on the v4.0 release diff --git a/vendor/clap-3.2.20/src/_tutorial.rs b/vendor/clap-3.2.20/src/_tutorial.rs new file mode 100644 index 000000000..9dbfc6864 --- /dev/null +++ b/vendor/clap-3.2.20/src/_tutorial.rs @@ -0,0 +1,204 @@ +// Contributing +// +// New example code: +// - Please update the corresponding section in the derive tutorial +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// +// See also the general CONTRIBUTING + +//! # Documentation: Builder Tutorial +//! +//! 1. [Quick Start](#quick-start) +//! 2. [Configuring the Parser](#configuring-the-parser) +//! 3. [Adding Arguments](#adding-arguments) +//! 1. [Positionals](#positionals) +//! 2. [Options](#options) +//! 3. [Flags](#flags) +//! 4. [Subcommands](#subcommands) +//! 5. [Defaults](#defaults) +//! 4. Validation +//! 1. [Enumerated values](#enumerated-values) +//! 2. [Validated values](#validated-values) +//! 3. [Argument Relations](#argument-relations) +//! 4. [Custom Validation](#custom-validation) +//! 5. [Testing](#testing) +//! +//! See also +//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis] +//! - The [cookbook][crate::_cookbook] for more application-focused examples +//! +//! ## Quick Start +//! +//! You can create an application with several arguments using usage strings. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/01_quick.rs")] +//! ``` +//! +#![doc = include_str!("../examples/tutorial_builder/01_quick.md")] +//! +//! ## Configuring the Parser +//! +//! You use [`Command`][crate::Command] to start building a parser. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_apps.rs")] +//! ``` +//! +#![doc = include_str!("../examples/tutorial_builder/02_apps.md")] +//! +//! You can use [`command!()`][crate::command!] to fill these fields in from your `Cargo.toml` +//! file. **This requires the [`cargo` feature flag][crate::_features].** +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_crate.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/02_crate.md")] +//! +//! You can use [`Command`][crate::Command] methods to change the application level behavior of +//! clap. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_app_settings.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/02_app_settings.md")] +//! +//! ## Adding Arguments +//! +//! ### Positionals +//! +//! You can have users specify values by their position on the command-line: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_03_positional.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_03_positional.md")] +//! +//! ### Options +//! +//! You can name your arguments with a flag: +//! - Order doesn't matter +//! - They can be optional +//! - Intent is clearer +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_02_option.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_02_option.md")] +//! +//! ### Flags +//! +//! Flags can also be switches that can be on/off: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.md")] +//! +//! Or counted. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.md")] +//! +//! ### Subcommands +//! +//! Subcommands are defined as [`Command`][crate::Command]s that get added via +//! [`Command::subcommand`][crate::Command::subcommand]. Each instance of a Subcommand can have its +//! own version, author(s), Args, and even its own subcommands. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.md")] +//! +//! ### Defaults +//! +//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional. +//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can set +//! [`Arg::default_value`][crate::Arg::default_value]. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.md")] +//! +//! ## Validation +//! +//! ### Enumerated values +//! +//! If you have arguments of specific values you want to test for, you can use the +//! [`PossibleValuesParser`][crate::builder::PossibleValuesParser] or [`Arg::value_parser(["val1", +//! ...])`][crate::Arg::value_parser] for short. +//! +//! This allows you specify the valid values for that argument. If the user does not use one of +//! those specific values, they will receive a graceful exit with error message informing them +//! of the mistake, and what the possible valid values are +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_01_possible.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_01_possible.md")] +//! +//! When enabling the [`derive` feature][crate::_features], you can use +//! [`ValueEnum`][crate::ValueEnum] to take care of the boiler plate for you, giving the same +//! results. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_01_enum.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_01_enum.md")] +//! +//! ### Validated values +//! +//! More generally, you can validate and parse into any data type. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_02_parse.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_02_parse.md")] +//! +//! A custom parser can be used to improve the error messages or provide additional validation: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_02_validate.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_02_validate.md")] +//! +//! ### Argument Relations +//! +//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even +//! [`ArgGroup`][crate::ArgGroup]s. +//! +//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list +//! each individually, or when you want a rule to apply "any but not all" arguments. +//! +//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one +//! argument to be present out of a given set. Imagine that you had multiple arguments, and you +//! want one of them to be required, but making all of them required isn't feasible because perhaps +//! they conflict with each other. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_03_relations.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_03_relations.md")] +//! +//! ### Custom Validation +//! +//! As a last resort, you can create custom errors with the basics of clap's formatting. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_04_custom.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_04_custom.md")] +//! +//! ## Testing +//! +//! clap reports most development errors as `debug_assert!`s. Rather than checking every +//! subcommand, you should have a test that calls +//! [`Command::debug_assert`][crate::App::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../examples/tutorial_builder/05_01_assert.rs")] +//! ``` diff --git a/vendor/clap-3.2.20/src/bin/stdio-fixture.rs b/vendor/clap-3.2.20/src/bin/stdio-fixture.rs new file mode 100644 index 000000000..e3f34b41a --- /dev/null +++ b/vendor/clap-3.2.20/src/bin/stdio-fixture.rs @@ -0,0 +1,14 @@ +fn main() { + let cmd = clap::Command::new("stdio-fixture") + .version("1.0") + .long_version("1.0 - a2132c") + .arg_required_else_help(true) + .subcommand(clap::Command::new("more")) + .arg( + clap::Arg::new("verbose") + .long("verbose") + .help("log") + .long_help("more log"), + ); + cmd.get_matches(); +} diff --git a/vendor/clap-3.2.20/src/builder/action.rs b/vendor/clap-3.2.20/src/builder/action.rs new file mode 100644 index 000000000..71a91a8b1 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/action.rs @@ -0,0 +1,325 @@ +/// Behavior of arguments when they are encountered while parsing +/// +/// # Examples +/// +/// ```rust +/// # use clap::Command; +/// # use clap::Arg; +/// let cmd = Command::new("mycmd") +/// .arg( +/// Arg::new("special-help") +/// .short('?') +/// .action(clap::ArgAction::Help) +/// ); +/// +/// // Existing help still exists +/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); +/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); +/// +/// // New help available +/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); +/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); +/// ``` +#[derive(Clone, Debug)] +#[non_exhaustive] +#[allow(missing_copy_implementations)] // In the future, we may accept `Box` +pub enum ArgAction { + /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Set) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value"] + /// ); + /// ``` + Set, + /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Append) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value1", "value2"] + /// ); + /// ``` + Append, + /// Deprecated, replaced with [`ArgAction::Set`] or [`ArgAction::Append`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `ArgAction::Set` or `ArgAction::Append`" + ) + )] + StoreValue, + /// Deprecated, replaced with [`ArgAction::SetTrue`] or [`ArgAction::Count`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `ArgAction::SetTrue` or `ArgAction::Count`" + ) + )] + IncOccurrence, + /// When encountered, act as if `"true"` was encountered on the command-line + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetTrue) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(true) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(false) + /// ); + /// ``` + SetTrue, + /// When encountered, act as if `"false"` was encountered on the command-line + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetFalse) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(false) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(true) + /// ); + /// ``` + SetFalse, + /// When encountered, increment a `u8` counter + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Count) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_count("flag"), + /// 2 + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_count("flag"), + /// 0 + /// ); + /// ``` + Count, + /// When encountered, display [`Command::print_help`][super::App::print_help] + /// + /// Depending on the flag, [`Command::print_long_help`][super::App::print_long_help] may be shown + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("special-help") + /// .short('?') + /// .action(clap::ArgAction::Help) + /// ); + /// + /// // Existing help still exists + /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); + /// + /// // New help available + /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); + /// ``` + Help, + /// When encountered, display [`Command::version`][super::App::version] + /// + /// Depending on the flag, [`Command::long_version`][super::App::long_version] may be shown + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .version("1.0.0") + /// .arg( + /// Arg::new("special-version") + /// .long("special-version") + /// .action(clap::ArgAction::Version) + /// ); + /// + /// // Existing help still exists + /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); + /// + /// // New help available + /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); + /// ``` + Version, +} + +impl ArgAction { + /// Returns whether this action accepts values on the command-line + /// + /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be + /// processed. + pub fn takes_values(&self) -> bool { + match self { + Self::Set => true, + Self::Append => true, + #[allow(deprecated)] + Self::StoreValue => true, + #[allow(deprecated)] + Self::IncOccurrence => false, + Self::SetTrue => false, + Self::SetFalse => false, + Self::Count => false, + Self::Help => false, + Self::Version => false, + } + } + + pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { + match self { + Self::Set => None, + Self::Append => None, + #[allow(deprecated)] + Self::StoreValue => None, + #[allow(deprecated)] + Self::IncOccurrence => None, + Self::SetTrue => Some(std::ffi::OsStr::new("false")), + Self::SetFalse => Some(std::ffi::OsStr::new("true")), + Self::Count => Some(std::ffi::OsStr::new("0")), + Self::Help => None, + Self::Version => None, + } + } + + pub(crate) fn default_value_parser(&self) -> Option { + match self { + Self::Set => None, + Self::Append => None, + #[allow(deprecated)] + Self::StoreValue => None, + #[allow(deprecated)] + Self::IncOccurrence => None, + Self::SetTrue => Some(super::ValueParser::bool()), + Self::SetFalse => Some(super::ValueParser::bool()), + Self::Count => Some(crate::value_parser!(u8).into()), + Self::Help => None, + Self::Version => None, + } + } + + #[cfg(debug_assertions)] + pub(crate) fn value_type_id(&self) -> Option { + use crate::parser::AnyValueId; + + match self { + Self::Set => None, + Self::Append => None, + #[allow(deprecated)] + Self::StoreValue => None, + #[allow(deprecated)] + Self::IncOccurrence => None, + Self::SetTrue => Some(AnyValueId::of::()), + Self::SetFalse => Some(AnyValueId::of::()), + Self::Count => Some(AnyValueId::of::()), + Self::Help => None, + Self::Version => None, + } + } +} + +pub(crate) type CountType = u8; diff --git a/vendor/clap-3.2.20/src/builder/app_settings.rs b/vendor/clap-3.2.20/src/builder/app_settings.rs new file mode 100644 index 000000000..88bc243c4 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/app_settings.rs @@ -0,0 +1,864 @@ +#![allow(deprecated)] + +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +#[allow(unused)] +use crate::Arg; +#[allow(unused)] +use crate::Command; + +// Third party +use bitflags::bitflags; + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct AppFlags(Flags); + +impl Default for AppFlags { + fn default() -> Self { + AppFlags(Flags::COLOR_AUTO) + } +} + +/// Application level settings, which affect how [`Command`] operates +/// +/// **NOTE:** When these settings are used, they apply only to current command, and are *not* +/// propagated down or up through child or parent subcommands +/// +/// [`Command`]: crate::Command +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum AppSettings { + /// Deprecated, replaced with [`Command::ignore_errors`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::ignore_errors`") + )] + IgnoreErrors, + + /// Deprecated, replace + /// ```rust,no_run + /// let cmd = clap::Command::new("cmd") + /// .global_setting(clap::AppSettings::WaitOnError) + /// .arg(clap::arg!(--flag)); + /// let m = cmd.get_matches(); + /// ``` + /// with + /// ```rust + /// let cmd = clap::Command::new("cmd") + /// .arg(clap::arg!(--flag)); + /// let m = match cmd.try_get_matches() { + /// Ok(m) => m, + /// Err(err) => { + /// if err.use_stderr() { + /// let _ = err.print(); + /// + /// eprintln!("\nPress [ENTER] / [RETURN] to continue..."); + /// use std::io::BufRead; + /// let mut s = String::new(); + /// let i = std::io::stdin(); + /// i.lock().read_line(&mut s).unwrap(); + /// + /// std::process::exit(2); + /// } else { + /// let _ = err.print(); + /// std::process::exit(0); + /// } + /// } + /// }; + /// ``` + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "See documentation for how to hand-implement this" + ) + )] + WaitOnError, + + /// Deprecated, replaced with [`Command::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" + ) + )] + AllowHyphenValues, + + /// Deprecated, replaced with [`Command::allow_negative_numbers`] and + /// [`Command::is_allow_negative_numbers_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_negative_numbers` and `Command::is_allow_negative_numbers_set`" + ) + )] + AllowNegativeNumbers, + + /// Deprecated, replaced with [`Command::args_override_self`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::args_override_self`") + )] + AllArgsOverrideSelf, + + /// Deprecated, replaced with [`Command::allow_missing_positional`] and + /// [`Command::is_allow_missing_positional_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_missing_positional` and `Command::is_allow_missing_positional_set`" + ) + )] + AllowMissingPositional, + + /// Deprecated, replaced with [`Command::trailing_var_arg`] and [`Command::is_trailing_var_arg_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::trailing_var_arg` and `Command::is_trailing_var_arg_set`" + ) + )] + TrailingVarArg, + + /// Deprecated, replaced with [`Command::dont_delimit_trailing_values`] and + /// [`Command::is_dont_delimit_trailing_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::dont_delimit_trailing_values` and `Command::is_dont_delimit_trailing_values_set`" + ) + )] + DontDelimitTrailingValues, + + /// Deprecated, replaced with [`Command::infer_long_args`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::infer_long_args`") + )] + InferLongArgs, + + /// Deprecated, replaced with [`Command::infer_subcommands`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::infer_subcommands`") + )] + InferSubcommands, + + /// Deprecated, replaced with [`Command::subcommand_required`] and + /// [`Command::is_subcommand_required_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_required` and `Command::is_subcommand_required_set`" + ) + )] + SubcommandRequired, + + /// Deprecated, replaced with [`Command::subcommand_required`] combined with + /// [`Command::arg_required_else_help`]. + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_required` combined with `Command::arg_required_else_help`" + ) + )] + SubcommandRequiredElseHelp, + + /// Deprecated, replaced with [`Command::allow_external_subcommands`] and + /// [`Command::is_allow_external_subcommands_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_external_subcommands` and `Command::is_allow_external_subcommands_set`" + ) + )] + AllowExternalSubcommands, + + /// Deprecated, replaced with [`Command::multicall`] and [`Command::is_multicall_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::multicall` and `Command::is_multicall_set`" + ) + )] + Multicall, + + /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`" + ) + )] + AllowInvalidUtf8ForExternalSubcommands, + + /// Deprecated, this is now the default + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "This is now the default") + )] + UseLongFormatForHelpSubcommand, + + /// Deprecated, replaced with [`Command::subcommand_negates_reqs`] and + /// [`Command::is_subcommand_negates_reqs_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_negates_reqs` and `Command::is_subcommand_negates_reqs_set`" + ) + )] + SubcommandsNegateReqs, + + /// Deprecated, replaced with [`Command::args_conflicts_with_subcommands`] and + /// [`Command::is_args_conflicts_with_subcommands_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::args_conflicts_with_subcommands` and `Command::is_args_conflicts_with_subcommands_set`" + ) + )] + ArgsNegateSubcommands, + + /// Deprecated, replaced with [`Command::subcommand_precedence_over_arg`] and + /// [`Command::is_subcommand_precedence_over_arg_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_precedence_over_arg` and `Command::is_subcommand_precedence_over_arg_set`" + ) + )] + SubcommandPrecedenceOverArg, + + /// Deprecated, replaced with [`Command::arg_required_else_help`] and + /// [`Command::is_arg_required_else_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::arg_required_else_help` and `Command::is_arg_required_else_help_set`" + ) + )] + ArgRequiredElseHelp, + + /// Displays the arguments and [`subcommands`] in the help message in the order that they were + /// declared in, and not alphabetically which is the default. + /// + /// To override the declaration order, see [`Arg::display_order`] and [`Command::display_order`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, AppSettings}; + /// Command::new("myprog") + /// .global_setting(AppSettings::DeriveDisplayOrder) + /// .get_matches(); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::display_order`]: crate::Arg::display_order + /// [`Command::display_order`]: crate::Command::display_order + DeriveDisplayOrder, + + /// Deprecated, replaced with [`Command::dont_collapse_args_in_usage`] and + /// [`Command::is_dont_collapse_args_in_usage_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::dont_collapse_args_in_usage` and `Command::is_dont_collapse_args_in_usage_set`" + ) + )] + DontCollapseArgsInUsage, + + /// Deprecated, replaced with [`Command::next_line_help`] and [`Command::is_next_line_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::next_line_help` and `Command::is_next_line_help_set`" + ) + )] + NextLineHelp, + + /// Deprecated, replaced with [`Command::disable_colored_help`] and + /// [`Command::is_disable_colored_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_colored_help` and `Command::is_disable_colored_help_set`" + ) + )] + DisableColoredHelp, + + /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`" + ) + )] + DisableHelpFlag, + + /// Deprecated, replaced with [`Command::disable_help_subcommand`] and + /// [`Command::is_disable_help_subcommand_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_help_subcommand` and `Command::is_disable_help_subcommand_set`" + ) + )] + DisableHelpSubcommand, + + /// Deprecated, replaced with [`Command::disable_version_flag`] and + /// [`Command::is_disable_version_flag_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`" + ) + )] + DisableVersionFlag, + + /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`" + ) + )] + PropagateVersion, + + /// Deprecated, replaced with [`Command::hide`] and [`Command::is_hide_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::hide` and `Command::is_hide_set`" + ) + )] + Hidden, + + /// Deprecated, replaced with [`Command::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`" + ) + )] + HidePossibleValues, + + /// Deprecated, replaced with [`Command::help_expected`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::help_expected`") + )] + HelpExpected, + + /// Deprecated, replaced with [`Command::no_binary_name`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command::no_binary_name`") + )] + NoBinaryName, + + /// Deprecated, replaced with [`Arg::action`][super::Arg::action] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::action`") + )] + NoAutoHelp, + + /// Deprecated, replaced with [`Arg::action`][super::Arg::action] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::action`") + )] + NoAutoVersion, + + /// Deprecated, replaced with [`Command::allow_hyphen_values`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::allow_hyphen_values`") + )] + #[doc(hidden)] + AllowLeadingHyphen, + + /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`" + ) + )] + #[doc(hidden)] + StrictUtf8, + + /// Deprecated, this is now the default + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "This is now the default") + )] + #[doc(hidden)] + UnifiedHelpMessage, + + /// Deprecated, this is now the default + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "This is now the default") + )] + #[doc(hidden)] + ColoredHelp, + + /// Deprecated, see [`Command::color`][crate::Command::color] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::color`") + )] + #[doc(hidden)] + ColorAuto, + + /// Deprecated, replaced with [`Command::color`][crate::Command::color] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::color`") + )] + #[doc(hidden)] + ColorAlways, + + /// Deprecated, replaced with [`Command::color`][crate::Command::color] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::color`") + )] + #[doc(hidden)] + ColorNever, + + /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`" + ) + )] + #[doc(hidden)] + DisableHelpFlags, + + /// Deprecated, replaced with [`Command::disable_version_flag`] and + /// [`Command::is_disable_version_flag_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`" + ) + )] + #[doc(hidden)] + DisableVersion, + + /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`" + ) + )] + #[doc(hidden)] + GlobalVersion, + + /// Deprecated, replaced with [`Command::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`" + ) + )] + #[doc(hidden)] + HidePossibleValuesInHelp, + + /// Deprecated, this is now the default + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "This is now the default") + )] + #[doc(hidden)] + UnifiedHelp, + + /// If the cmd is already built, used for caching. + #[doc(hidden)] + Built, + + /// If the cmd's bin name is already built, used for caching. + #[doc(hidden)] + BinNameBuilt, +} + +bitflags! { + struct Flags: u64 { + const SC_NEGATE_REQS = 1; + const SC_REQUIRED = 1 << 1; + const ARG_REQUIRED_ELSE_HELP = 1 << 2; + const PROPAGATE_VERSION = 1 << 3; + const DISABLE_VERSION_FOR_SC = 1 << 4; + const WAIT_ON_ERROR = 1 << 6; + const SC_REQUIRED_ELSE_HELP = 1 << 7; + const NO_AUTO_HELP = 1 << 8; + const NO_AUTO_VERSION = 1 << 9; + const DISABLE_VERSION_FLAG = 1 << 10; + const HIDDEN = 1 << 11; + const TRAILING_VARARG = 1 << 12; + const NO_BIN_NAME = 1 << 13; + const ALLOW_UNK_SC = 1 << 14; + const SC_UTF8_NONE = 1 << 15; + const LEADING_HYPHEN = 1 << 16; + const NO_POS_VALUES = 1 << 17; + const NEXT_LINE_HELP = 1 << 18; + const DERIVE_DISP_ORDER = 1 << 19; + const DISABLE_COLORED_HELP = 1 << 20; + const COLOR_ALWAYS = 1 << 21; + const COLOR_AUTO = 1 << 22; + const COLOR_NEVER = 1 << 23; + const DONT_DELIM_TRAIL = 1 << 24; + const ALLOW_NEG_NUMS = 1 << 25; + const DISABLE_HELP_SC = 1 << 27; + const DONT_COLLAPSE_ARGS = 1 << 28; + const ARGS_NEGATE_SCS = 1 << 29; + const PROPAGATE_VALS_DOWN = 1 << 30; + const ALLOW_MISSING_POS = 1 << 31; + const TRAILING_VALUES = 1 << 32; + const BUILT = 1 << 33; + const BIN_NAME_BUILT = 1 << 34; + const VALID_ARG_FOUND = 1 << 35; + const INFER_SUBCOMMANDS = 1 << 36; + const CONTAINS_LAST = 1 << 37; + const ARGS_OVERRIDE_SELF = 1 << 38; + const HELP_REQUIRED = 1 << 39; + const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40; + const DISABLE_HELP_FLAG = 1 << 41; + const USE_LONG_FORMAT_FOR_HELP_SC = 1 << 42; + const INFER_LONG_ARGS = 1 << 43; + const IGNORE_ERRORS = 1 << 44; + const MULTICALL = 1 << 45; + const NO_OP = 0; + } +} + +impl_settings! { AppSettings, AppFlags, + ArgRequiredElseHelp + => Flags::ARG_REQUIRED_ELSE_HELP, + SubcommandPrecedenceOverArg + => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG, + ArgsNegateSubcommands + => Flags::ARGS_NEGATE_SCS, + AllowExternalSubcommands + => Flags::ALLOW_UNK_SC, + StrictUtf8 + => Flags::NO_OP, + AllowInvalidUtf8ForExternalSubcommands + => Flags::SC_UTF8_NONE, + AllowHyphenValues + => Flags::LEADING_HYPHEN, + AllowLeadingHyphen + => Flags::LEADING_HYPHEN, + AllowNegativeNumbers + => Flags::ALLOW_NEG_NUMS, + AllowMissingPositional + => Flags::ALLOW_MISSING_POS, + UnifiedHelpMessage + => Flags::NO_OP, + ColoredHelp + => Flags::NO_OP, + ColorAlways + => Flags::COLOR_ALWAYS, + ColorAuto + => Flags::COLOR_AUTO, + ColorNever + => Flags::COLOR_NEVER, + DontDelimitTrailingValues + => Flags::DONT_DELIM_TRAIL, + DontCollapseArgsInUsage + => Flags::DONT_COLLAPSE_ARGS, + DeriveDisplayOrder + => Flags::DERIVE_DISP_ORDER, + DisableColoredHelp + => Flags::DISABLE_COLORED_HELP, + DisableHelpSubcommand + => Flags::DISABLE_HELP_SC, + DisableHelpFlag + => Flags::DISABLE_HELP_FLAG, + DisableHelpFlags + => Flags::DISABLE_HELP_FLAG, + DisableVersionFlag + => Flags::DISABLE_VERSION_FLAG, + DisableVersion + => Flags::DISABLE_VERSION_FLAG, + PropagateVersion + => Flags::PROPAGATE_VERSION, + GlobalVersion + => Flags::PROPAGATE_VERSION, + HidePossibleValues + => Flags::NO_POS_VALUES, + HidePossibleValuesInHelp + => Flags::NO_POS_VALUES, + HelpExpected + => Flags::HELP_REQUIRED, + Hidden + => Flags::HIDDEN, + Multicall + => Flags::MULTICALL, + NoAutoHelp + => Flags::NO_AUTO_HELP, + NoAutoVersion + => Flags::NO_AUTO_VERSION, + NoBinaryName + => Flags::NO_BIN_NAME, + SubcommandsNegateReqs + => Flags::SC_NEGATE_REQS, + SubcommandRequired + => Flags::SC_REQUIRED, + SubcommandRequiredElseHelp + => Flags::SC_REQUIRED_ELSE_HELP, + UseLongFormatForHelpSubcommand + => Flags::USE_LONG_FORMAT_FOR_HELP_SC, + TrailingVarArg + => Flags::TRAILING_VARARG, + UnifiedHelp => Flags::NO_OP, + NextLineHelp + => Flags::NEXT_LINE_HELP, + IgnoreErrors + => Flags::IGNORE_ERRORS, + WaitOnError + => Flags::WAIT_ON_ERROR, + Built + => Flags::BUILT, + BinNameBuilt + => Flags::BIN_NAME_BUILT, + InferSubcommands + => Flags::INFER_SUBCOMMANDS, + AllArgsOverrideSelf + => Flags::ARGS_OVERRIDE_SELF, + InferLongArgs + => Flags::INFER_LONG_ARGS +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl FromStr for AppSettings { + type Err = String; + fn from_str(s: &str) -> Result::Err> { + #[allow(deprecated)] + #[allow(unreachable_patterns)] + match &*s.to_ascii_lowercase() { + "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), + "subcommandprecedenceoverarg" => Ok(AppSettings::SubcommandPrecedenceOverArg), + "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), + "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), + "strictutf8" => Ok(AppSettings::StrictUtf8), + "allowinvalidutf8forexternalsubcommands" => { + Ok(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + "allowhyphenvalues" => Ok(AppSettings::AllowHyphenValues), + "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), + "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), + "allowmissingpositional" => Ok(AppSettings::AllowMissingPositional), + "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), + "coloredhelp" => Ok(AppSettings::ColoredHelp), + "coloralways" => Ok(AppSettings::ColorAlways), + "colorauto" => Ok(AppSettings::ColorAuto), + "colornever" => Ok(AppSettings::ColorNever), + "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), + "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), + "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), + "disablecoloredhelp" => Ok(AppSettings::DisableColoredHelp), + "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), + "disablehelpflag" => Ok(AppSettings::DisableHelpFlag), + "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), + "disableversionflag" => Ok(AppSettings::DisableVersionFlag), + "disableversion" => Ok(AppSettings::DisableVersion), + "propagateversion" => Ok(AppSettings::PropagateVersion), + "propagateversion" => Ok(AppSettings::GlobalVersion), + "hidepossiblevalues" => Ok(AppSettings::HidePossibleValues), + "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), + "helpexpected" => Ok(AppSettings::HelpExpected), + "hidden" => Ok(AppSettings::Hidden), + "noautohelp" => Ok(AppSettings::NoAutoHelp), + "noautoversion" => Ok(AppSettings::NoAutoVersion), + "nobinaryname" => Ok(AppSettings::NoBinaryName), + "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), + "subcommandrequired" => Ok(AppSettings::SubcommandRequired), + "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), + "uselongformatforhelpsubcommand" => Ok(AppSettings::UseLongFormatForHelpSubcommand), + "trailingvararg" => Ok(AppSettings::TrailingVarArg), + "unifiedhelp" => Ok(AppSettings::UnifiedHelp), + "nextlinehelp" => Ok(AppSettings::NextLineHelp), + "ignoreerrors" => Ok(AppSettings::IgnoreErrors), + "waitonerror" => Ok(AppSettings::WaitOnError), + "built" => Ok(AppSettings::Built), + "binnamebuilt" => Ok(AppSettings::BinNameBuilt), + "infersubcommands" => Ok(AppSettings::InferSubcommands), + "allargsoverrideself" => Ok(AppSettings::AllArgsOverrideSelf), + "inferlongargs" => Ok(AppSettings::InferLongArgs), + _ => Err(format!("unknown AppSetting: `{}`", s)), + } + } +} + +#[cfg(test)] +mod test { + #[allow(clippy::cognitive_complexity)] + #[test] + #[cfg(feature = "yaml")] + fn app_settings_fromstr() { + use super::AppSettings; + + assert_eq!( + "disablehelpflag".parse::().unwrap(), + AppSettings::DisableHelpFlag + ); + assert_eq!( + "argsnegatesubcommands".parse::().unwrap(), + AppSettings::ArgsNegateSubcommands + ); + assert_eq!( + "argrequiredelsehelp".parse::().unwrap(), + AppSettings::ArgRequiredElseHelp + ); + assert_eq!( + "subcommandprecedenceoverarg" + .parse::() + .unwrap(), + AppSettings::SubcommandPrecedenceOverArg + ); + assert_eq!( + "allowexternalsubcommands".parse::().unwrap(), + AppSettings::AllowExternalSubcommands + ); + assert_eq!( + "allowinvalidutf8forexternalsubcommands" + .parse::() + .unwrap(), + AppSettings::AllowInvalidUtf8ForExternalSubcommands + ); + assert_eq!( + "allowhyphenvalues".parse::().unwrap(), + AppSettings::AllowHyphenValues + ); + assert_eq!( + "allownegativenumbers".parse::().unwrap(), + AppSettings::AllowNegativeNumbers + ); + assert_eq!( + "disablehelpsubcommand".parse::().unwrap(), + AppSettings::DisableHelpSubcommand + ); + assert_eq!( + "disableversionflag".parse::().unwrap(), + AppSettings::DisableVersionFlag + ); + assert_eq!( + "dontcollapseargsinusage".parse::().unwrap(), + AppSettings::DontCollapseArgsInUsage + ); + assert_eq!( + "dontdelimittrailingvalues".parse::().unwrap(), + AppSettings::DontDelimitTrailingValues + ); + assert_eq!( + "derivedisplayorder".parse::().unwrap(), + AppSettings::DeriveDisplayOrder + ); + assert_eq!( + "disablecoloredhelp".parse::().unwrap(), + AppSettings::DisableColoredHelp + ); + assert_eq!( + "propagateversion".parse::().unwrap(), + AppSettings::PropagateVersion + ); + assert_eq!( + "hidden".parse::().unwrap(), + AppSettings::Hidden + ); + assert_eq!( + "hidepossiblevalues".parse::().unwrap(), + AppSettings::HidePossibleValues + ); + assert_eq!( + "helpexpected".parse::().unwrap(), + AppSettings::HelpExpected + ); + assert_eq!( + "nobinaryname".parse::().unwrap(), + AppSettings::NoBinaryName + ); + assert_eq!( + "nextlinehelp".parse::().unwrap(), + AppSettings::NextLineHelp + ); + assert_eq!( + "subcommandsnegatereqs".parse::().unwrap(), + AppSettings::SubcommandsNegateReqs + ); + assert_eq!( + "subcommandrequired".parse::().unwrap(), + AppSettings::SubcommandRequired + ); + assert_eq!( + "subcommandrequiredelsehelp".parse::().unwrap(), + AppSettings::SubcommandRequiredElseHelp + ); + assert_eq!( + "uselongformatforhelpsubcommand" + .parse::() + .unwrap(), + AppSettings::UseLongFormatForHelpSubcommand + ); + assert_eq!( + "trailingvararg".parse::().unwrap(), + AppSettings::TrailingVarArg + ); + assert_eq!( + "waitonerror".parse::().unwrap(), + AppSettings::WaitOnError + ); + assert_eq!("built".parse::().unwrap(), AppSettings::Built); + assert_eq!( + "binnamebuilt".parse::().unwrap(), + AppSettings::BinNameBuilt + ); + assert_eq!( + "infersubcommands".parse::().unwrap(), + AppSettings::InferSubcommands + ); + assert!("hahahaha".parse::().is_err()); + } +} diff --git a/vendor/clap-3.2.20/src/builder/arg.rs b/vendor/clap-3.2.20/src/builder/arg.rs new file mode 100644 index 000000000..e9403d0b7 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/arg.rs @@ -0,0 +1,5494 @@ +#![allow(deprecated)] + +// Std +use std::{ + borrow::Cow, + cmp::{Ord, Ordering}, + error::Error, + ffi::OsStr, + fmt::{self, Display, Formatter}, + str, + sync::{Arc, Mutex}, +}; +#[cfg(feature = "env")] +use std::{env, ffi::OsString}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::builder::usage_parser::UsageParser; +use crate::builder::ArgPredicate; +use crate::util::{Id, Key}; +use crate::ArgAction; +use crate::PossibleValue; +use crate::ValueHint; +use crate::INTERNAL_ERROR_MSG; +use crate::{ArgFlags, ArgSettings}; + +#[cfg(feature = "regex")] +use crate::builder::RegexRef; + +/// The abstract representation of a command line argument. Used to set all the options and +/// relationships that define a valid argument for the program. +/// +/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options +/// manually, or using a usage string which is far less verbose but has fewer options. You can also +/// use a combination of the two methods to achieve the best of both worlds. +/// +/// - [Basic API][crate::Arg#basic-api] +/// - [Value Handling][crate::Arg#value-handling] +/// - [Help][crate::Arg#help-1] +/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] +/// - [Reflection][crate::Arg#reflection] +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, arg}; +/// // Using the traditional builder pattern and setting each option manually +/// let cfg = Arg::new("config") +/// .short('c') +/// .long("config") +/// .takes_value(true) +/// .value_name("FILE") +/// .help("Provides a config file to myprog"); +/// // Using a usage string (setting a similar argument to the one above) +/// let input = arg!(-i --input "Provides an input file to the program"); +/// ``` +#[allow(missing_debug_implementations)] +#[derive(Default, Clone)] +pub struct Arg<'help> { + pub(crate) id: Id, + pub(crate) provider: ArgProvider, + pub(crate) name: &'help str, + pub(crate) help: Option<&'help str>, + pub(crate) long_help: Option<&'help str>, + pub(crate) action: Option, + pub(crate) value_parser: Option, + pub(crate) blacklist: Vec, + pub(crate) settings: ArgFlags, + pub(crate) overrides: Vec, + pub(crate) groups: Vec, + pub(crate) requires: Vec<(ArgPredicate<'help>, Id)>, + pub(crate) r_ifs: Vec<(Id, &'help str)>, + pub(crate) r_ifs_all: Vec<(Id, &'help str)>, + pub(crate) r_unless: Vec, + pub(crate) r_unless_all: Vec, + pub(crate) short: Option, + pub(crate) long: Option<&'help str>, + pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible) + pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) + pub(crate) disp_ord: DisplayOrder, + pub(crate) possible_vals: Vec>, + pub(crate) val_names: Vec<&'help str>, + pub(crate) num_vals: Option, + pub(crate) max_occurs: Option, + pub(crate) max_vals: Option, + pub(crate) min_vals: Option, + pub(crate) validator: Option>>>, + pub(crate) validator_os: Option>>>, + pub(crate) val_delim: Option, + pub(crate) default_vals: Vec<&'help OsStr>, + pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate<'help>, Option<&'help OsStr>)>, + pub(crate) default_missing_vals: Vec<&'help OsStr>, + #[cfg(feature = "env")] + pub(crate) env: Option<(&'help OsStr, Option)>, + pub(crate) terminator: Option<&'help str>, + pub(crate) index: Option, + pub(crate) help_heading: Option>, + pub(crate) value_hint: Option, +} + +/// # Basic API +impl<'help> Arg<'help> { + /// Create a new [`Arg`] with a unique name. + /// + /// The name is used to check whether or not the argument was used at + /// runtime, get values, set relationships with other args, etc.. + /// + /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) + /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also + /// be displayed when the user prints the usage/help information of the program. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// # ; + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + pub fn new>(n: S) -> Self { + Arg::default().name(n) + } + + /// Set the identifier used for referencing this argument in the clap API. + /// + /// See [`Arg::new`] for more details. + #[must_use] + pub fn id>(mut self, n: S) -> Self { + let name = n.into(); + self.id = Id::from(&*name); + self.name = name; + self + } + + /// Deprecated, replaced with [`Arg::id`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::id`") + )] + pub fn name>(self, n: S) -> Self { + self.id(n) + } + + /// Sets the short version of the argument without the preceding `-`. + /// + /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, + /// respectively. You may use the uppercase `V` or lowercase `h` for your own arguments, in + /// which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// # Examples + /// + /// When calling `short`, use a single valid UTF-8 character which will allow using the + /// argument via a single hyphen (`-`) such as `-c`: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-c", "file.toml" + /// ]); + /// + /// assert_eq!(m.get_one::("config").map(String::as_str), Some("file.toml")); + /// ``` + #[inline] + #[must_use] + pub fn short(mut self, s: char) -> Self { + assert!(s != '-', "short option name cannot be `-`"); + + self.short = Some(s); + self + } + + /// Sets the long version of the argument without the preceding `--`. + /// + /// By default `version` and `help` are used by the auto-generated `version` and `help` + /// arguments, respectively. You may use the word `version` or `help` for the long form of your + /// own arguments, in which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// **NOTE:** Any leading `-` characters will be stripped + /// + /// # Examples + /// + /// To set `long` use a word containing valid UTF-8. If you supply a double leading + /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, + /// will *not* be stripped (i.e. `config-file` is allowed). + /// + /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--config", "file.toml" + /// ]); + /// + /// assert_eq!(m.get_one::("cfg").map(String::as_str), Some("file.toml")); + /// ``` + #[inline] + #[must_use] + pub fn long(mut self, l: &'help str) -> Self { + #[cfg(feature = "unstable-v4")] + { + self.long = Some(l); + } + #[cfg(not(feature = "unstable-v4"))] + { + self.long = Some(l.trim_start_matches(|c| c == '-')); + } + self + } + + /// Add an alias, which functions as a hidden long flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .alias("alias") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--alias", "cool" + /// ]); + /// assert!(m.contains_id("test")); + /// assert_eq!(m.value_of("test"), Some("cool")); + /// ``` + #[must_use] + pub fn alias>(mut self, name: S) -> Self { + self.aliases.push((name.into(), false)); + self + } + + /// Add an alias, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_alias('e') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-e", "cool" + /// ]); + /// assert!(m.contains_id("test")); + /// assert_eq!(m.value_of("test"), Some("cool")); + /// ``` + #[must_use] + pub fn short_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + + self.short_aliases.push((name, false)); + self + } + + /// Add aliases, which function as hidden long flags. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .aliases(&["do-stuff", "do-tests", "tests"]) + /// .action(ArgAction::SetTrue) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "--do-tests" + /// ]); + /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); + /// ``` + #[must_use] + pub fn aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|&x| (x, false))); + self + } + + /// Add aliases, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_aliases(&['e', 's']) + /// .action(ArgAction::SetTrue) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "-s" + /// ]); + /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); + /// ``` + #[must_use] + pub fn short_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_aliases.push((*s, false)); + } + self + } + + /// Add an alias, which functions as a visible long flag. + /// + /// Like [`Arg::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .visible_alias("something-awesome") + /// .long("test") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--something-awesome", "coffee" + /// ]); + /// assert!(m.contains_id("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + /// [`Command::alias`]: Arg::alias() + #[must_use] + pub fn visible_alias>(mut self, name: S) -> Self { + self.aliases.push((name.into(), true)); + self + } + + /// Add an alias, which functions as a visible short flag. + /// + /// Like [`Arg::short_alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_alias('t') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-t", "coffee" + /// ]); + /// assert!(m.contains_id("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + #[must_use] + pub fn visible_short_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + + self.short_aliases.push((name, true)); + self + } + + /// Add aliases, which function as visible long flags. + /// + /// Like [`Arg::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .action(ArgAction::SetTrue) + /// .visible_aliases(&["something", "awesome", "cool"])) + /// .get_matches_from(vec![ + /// "prog", "--awesome" + /// ]); + /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); + /// ``` + /// [`Command::aliases`]: Arg::aliases() + #[must_use] + pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, true))); + self + } + + /// Add aliases, which function as visible short flags. + /// + /// Like [`Arg::short_aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .action(ArgAction::SetTrue) + /// .visible_short_aliases(&['t', 'e'])) + /// .get_matches_from(vec![ + /// "prog", "-t" + /// ]); + /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); + /// ``` + #[must_use] + pub fn visible_short_aliases(mut self, names: &[char]) -> Self { + for n in names { + assert!(n != &'-', "short alias name cannot be `-`"); + self.short_aliases.push((*n, true)); + } + self + } + + /// Specifies the index of a positional argument **starting at** 1. + /// + /// **NOTE:** The index refers to position according to **other positional argument**. It does + /// not define position in the argument list as a whole. + /// + /// **NOTE:** You can optionally leave off the `index` method, and the index will be + /// assigned in order of evaluation. Utilizing the `index` method allows for setting + /// indexes out of order + /// + /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used + /// with [`Arg::short`] or [`Arg::long`]. + /// + /// **NOTE:** When utilized with [`Arg::multiple_values(true)`], only the **last** positional argument + /// may be defined as multiple (i.e. with the highest index) + /// + /// # Panics + /// + /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` + /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest + /// index + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// .index(1) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .index(1)) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .get_matches_from(vec![ + /// "prog", "--debug", "fast" + /// ]); + /// + /// assert!(m.contains_id("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" + /// // *not* first argument + /// ``` + /// [`Arg::short`]: Arg::short() + /// [`Arg::long`]: Arg::long() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn index(mut self, idx: usize) -> Self { + self.index = Some(idx); + self + } + + /// This arg is the last, or final, positional argument (i.e. has the highest + /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- + /// last_arg`). + /// + /// Even, if no other arguments are left to parse, if the user omits the `--` syntax + /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also + /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with + /// the `--` syntax is otherwise not possible. + /// + /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- ]` if + /// `ARG` is marked as `.last(true)`. + /// + /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing + /// to set this can make the usage string very confusing. + /// + /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **CAUTION:** Using this setting *and* having child subcommands is not + /// recommended with the exception of *also* using + /// [`crate::Command::args_conflicts_with_subcommands`] + /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also + /// marked [`Arg::required`]) + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("args") + /// .takes_value(true) + /// .last(true) + /// # ; + /// ``` + /// + /// Setting `last` ensures the arg has the highest [index] of all positional args + /// and requires that the `--` syntax be used to access it early. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .takes_value(true) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "--", "three" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("third"), Some("three")); + /// assert!(m.value_of("second").is_none()); + /// ``` + /// + /// Even if the positional argument marked `Last` is the only argument left to parse, + /// failing to use the `--` syntax results in an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .takes_value(true) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "two", "three" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [index]: Arg::index() + /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument + #[inline] + #[must_use] + pub fn last(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Last) + } else { + self.unset_setting(ArgSettings::Last) + } + } + + /// Specifies that the argument must be present. + /// + /// Required by default means it is required, when no other conflicting rules or overrides have + /// been evaluated. Conflicting rules take precedence over being required. + /// + /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be + /// required by default. This is because if a flag were to be required, it should simply be + /// implied. No additional information is required from user. Flags by their very nature are + /// simply boolean on/off switches. The only time a user *should* be required to use a flag + /// is if the operation is destructive in nature, and the user is essentially proving to you, + /// "Yes, I know what I'm doing." + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required(true) + /// # ; + /// ``` + /// + /// Setting required requires that the argument be used at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting required and then *not* supplying that argument at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + #[inline] + #[must_use] + pub fn required(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Required) + } else { + self.unset_setting(ArgSettings::Required) + } + } + + /// Sets an argument that is required when this one is present + /// + /// i.e. when using this argument, the following argument *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires("input") + /// # ; + /// ``` + /// + /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the + /// defining argument is used. If the defining argument isn't used, the other argument isn't + /// required + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required + /// ``` + /// + /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires(mut self, arg_id: T) -> Self { + self.requires.push((ArgPredicate::IsPresent, arg_id.into())); + self + } + + /// This argument must be passed alone; it conflicts with all other arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .exclusive(true) + /// # ; + /// ``` + /// + /// Setting an exclusive argument and having any other arguments present at runtime + /// is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("exclusive") + /// .takes_value(true) + /// .exclusive(true) + /// .long("exclusive")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--exclusive", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + #[inline] + #[must_use] + pub fn exclusive(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Exclusive) + } else { + self.unset_setting(ArgSettings::Exclusive) + } + } + + /// Specifies that an argument can be matched to all child [`Subcommand`]s. + /// + /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however + /// their values once a user uses them will be propagated back up to parents. In effect, this + /// means one should *define* all global arguments at the top level, however it doesn't matter + /// where the user *uses* the global argument. + /// + /// # Examples + /// + /// Assume an application with two subcommands, and you'd like to define a + /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't + /// want to clutter the source with three duplicate [`Arg`] definitions. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("verb") + /// .long("verbose") + /// .short('v') + /// .action(ArgAction::SetTrue) + /// .global(true)) + /// .subcommand(Command::new("test")) + /// .subcommand(Command::new("do-stuff")) + /// .get_matches_from(vec![ + /// "prog", "do-stuff", "--verbose" + /// ]); + /// + /// assert_eq!(m.subcommand_name(), Some("do-stuff")); + /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); + /// assert_eq!(*sub_m.get_one::("verb").expect("defaulted by clap"), true); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + #[inline] + #[must_use] + pub fn global(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Global) + } else { + self.unset_setting(ArgSettings::Global) + } + } + + /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::action` (Issue #3772)") + )] + pub fn multiple_occurrences(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::MultipleOccurrences) + } else { + self.unset_setting(ArgSettings::MultipleOccurrences) + } + } + + /// Deprecated, for flags this is replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))` + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "For flags, replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`" + ) + )] + pub fn max_occurrences(mut self, qty: usize) -> Self { + self.max_occurs = Some(qty); + if qty > 1 { + self.multiple_occurrences(true) + } else { + self + } + } + + /// Check if the [`ArgSettings`] variant is currently set on the argument. + /// + /// [`ArgSettings`]: crate::ArgSettings + #[inline] + pub fn is_set(&self, s: ArgSettings) -> bool { + self.settings.is_set(s) + } + + /// Apply a setting to the argument. + /// + /// See [`ArgSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .setting(ArgSettings::Required) + /// .setting(ArgSettings::TakesValue) + /// # ; + /// ``` + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .setting(ArgSettings::Required | ArgSettings::TakesValue) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + /// Remove a setting from the argument. + /// + /// See [`ArgSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .unset_setting(ArgSettings::Required) + /// .unset_setting(ArgSettings::TakesValue) + /// # ; + /// ``` + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.remove(setting.into()); + self + } +} + +/// # Value Handling +impl<'help> Arg<'help> { + /// Specifies that the argument takes a value at run time. + /// + /// **NOTE:** values for arguments may be specified in any of the following methods + /// + /// - Using a space such as `-o value` or `--option value` + /// - Using an equals and no space such as `-o=value` or `--option=value` + /// - Use a short and no space such as `-ovalue` + /// + /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning + /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to + /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], + /// alternatively you can turn delimiting values **OFF** by using + /// [`Arg::use_value_delimiter(false)`][Arg::use_value_delimiter] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// + /// assert!(m.contains_id("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter() + /// [multiple values]: Arg::multiple_values + #[inline] + #[must_use] + pub fn takes_value(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::TakesValue) + } else { + self.unset_setting(ArgSettings::TakesValue) + } + } + + /// Specify the behavior when parsing an argument + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Set) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!(matches.occurrences_of("flag"), 0); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value"] + /// ); + /// ``` + #[inline] + #[must_use] + pub fn action(mut self, action: ArgAction) -> Self { + self.action = Some(action); + self + } + + /// Specify the type of the argument. + /// + /// This allows parsing and validating a value before storing it into + /// [`ArgMatches`][crate::ArgMatches]. + /// + /// See also + /// - [`value_parser!`][crate::value_parser!] for auto-selecting a value parser for a given type + /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations + /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings + /// - [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] and [`RangedU64ValueParser`][crate::builder::RangedU64ValueParser] for numeric ranges + /// - [`EnumValueParser`][crate::builder::EnumValueParser] and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values + /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation + /// + /// ```rust + /// let mut cmd = clap::Command::new("raw") + /// .arg( + /// clap::Arg::new("color") + /// .long("color") + /// .value_parser(["always", "auto", "never"]) + /// .default_value("auto") + /// ) + /// .arg( + /// clap::Arg::new("hostname") + /// .long("hostname") + /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) + /// .takes_value(true) + /// .required(true) + /// ) + /// .arg( + /// clap::Arg::new("port") + /// .long("port") + /// .value_parser(clap::value_parser!(u16).range(3000..)) + /// .takes_value(true) + /// .required(true) + /// ); + /// + /// let m = cmd.try_get_matches_from_mut( + /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] + /// ).unwrap(); + /// + /// let color: &String = m.get_one("color") + /// .expect("default"); + /// assert_eq!(color, "auto"); + /// + /// let hostname: &String = m.get_one("hostname") + /// .expect("required"); + /// assert_eq!(hostname, "rust-lang.org"); + /// + /// let port: u16 = *m.get_one("port") + /// .expect("required"); + /// assert_eq!(port, 3001); + /// ``` + pub fn value_parser(mut self, parser: impl Into) -> Self { + self.value_parser = Some(parser.into()); + self + } + + /// Specifies that the argument may have an unknown number of values + /// + /// Without any other settings, this argument may appear only *once*. + /// + /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`]. + /// + /// **WARNING:** + /// + /// Setting `multiple_values` for an argument that takes a value, but with no other details can + /// be dangerous in some circumstances. Because multiple values are allowed, + /// `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI where + /// positional arguments are *also* expected as `clap` will continue parsing *values* until one + /// of the following happens: + /// + /// - It reaches the [maximum number of values] + /// - It reaches a [specific number of values] + /// - It finds another flag or option (i.e. something that starts with a `-`) + /// - It reaches a [value terminator][Arg::value_terminator] is reached + /// + /// Alternatively, [require a delimiter between values][Arg::require_delimiter]. + /// + /// **WARNING:** + /// + /// When using args with `multiple_values` and [`subcommands`], one needs to consider the + /// possibility of an argument value being the same as a valid subcommand. By default `clap` will + /// parse the argument in question as a value *only if* a value is possible at that moment. + /// Otherwise it will be parsed as a subcommand. In effect, this means using `multiple_values` with no + /// additional parameters and a value that coincides with a subcommand name, the subcommand + /// cannot be called unless another argument is passed between them. + /// + /// As an example, consider a CLI with an option `--ui-paths=...` and subcommand `signer` + /// + /// The following would be parsed as values to `--ui-paths`. + /// + /// ```text + /// $ program --ui-paths path1 path2 signer + /// ``` + /// + /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values + /// until another argument is reached and it knows `--ui-paths` is done parsing. + /// + /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding + /// [`Arg::number_of_values(1)`] or using *only* [`ArgAction::Append`]. The following are all + /// valid, and `signer` is parsed as a subcommand in the first case, but a value in the second + /// case. + /// + /// ```text + /// $ program --ui-paths path1 signer + /// $ program --ui-paths path1 --ui-paths signer signer + /// ``` + /// + /// # Examples + /// + /// An example with options + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(m.contains_id("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// Although `multiple_values` has been specified, we cannot use the argument more than once. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage) + /// ``` + /// + /// A common mistake is to define an option which allows multiple values, and a positional + /// argument. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(m.contains_id("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! + /// assert!(!m.contains_id("word")); // but we clearly used word! + /// ``` + /// + /// The problem is `clap` doesn't know when to stop parsing values for "files". This is further + /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would + /// appear to only fail sometimes...not good! + /// + /// A solution for the example above is to limit how many values with a [maximum], or [specific] + /// number, or to say [`ArgAction::Append`] is ok, but multiple values is not. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .action(ArgAction::Append) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + /// ]); + /// + /// assert!(m.contains_id("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert!(m.contains_id("word")); + /// assert_eq!(m.value_of("word"), Some("word")); + /// ``` + /// + /// As a final example, let's fix the above error and get a pretty message to the user :) + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .action(ArgAction::Append) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::number_of_values(1)`]: Arg::number_of_values() + /// [maximum number of values]: Arg::max_values() + /// [specific number of values]: Arg::number_of_values() + /// [maximum]: Arg::max_values() + /// [specific]: Arg::number_of_values() + #[inline] + #[must_use] + pub fn multiple_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::MultipleValues) + } else { + self.unset_setting(ArgSettings::MultipleValues) + } + } + + /// The number of values allowed for this argument. + /// + /// For example, if you had a + /// `-f ` argument where you wanted exactly 3 'files' you would set + /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided + /// 3 and only 3 values. + /// + /// **NOTE:** Does *not* require [`Arg::multiple_occurrences(true)`] to be set. Setting + /// [`Arg::multiple_occurrences(true)`] would allow `-f -f ` where + /// as *not* setting it would only allow one occurrence of this argument. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .number_of_values(3); + /// ``` + /// + /// Not supplying the correct number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .number_of_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn number_of_values(mut self, qty: usize) -> Self { + self.num_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// The *maximum* number of values are for this argument. + /// + /// For example, if you had a + /// `-f ` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and + /// this argument would be satisfied if the user provided, 1, 2, or 3 values. + /// + /// **NOTE:** This does *not* implicitly set [`Arg::multiple_occurrences(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .max_values(3); + /// ``` + /// + /// Supplying less than the maximum number of values is allowed + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .max_values(3) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2"]); + /// ``` + /// + /// Supplying more than the maximum number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .max_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn max_values(mut self, qty: usize) -> Self { + self.max_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// The *minimum* number of values for this argument. + /// + /// For example, if you had a + /// `-f ` argument where you wanted at least 2 'files' you would set + /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more + /// values. + /// + /// **NOTE:** This does not implicitly set [`Arg::multiple_occurrences(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// **NOTE:** Passing a non-zero value is not the same as specifying [`Arg::required(true)`]. + /// This is due to min and max validation only being performed for present arguments, + /// marking them as required will thus perform validation and a min value of 1 + /// is unnecessary, ignored if not required. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .min_values(3); + /// ``` + /// + /// Supplying more than the minimum number of values is allowed + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .min_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// Supplying less than the minimum number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .min_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + /// [`Arg::required(true)`]: Arg::required() + #[inline] + #[must_use] + pub fn min_values(mut self, qty: usize) -> Self { + self.min_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// Placeholder for the argument's value in the help message / usage. + /// + /// This name is cosmetic only; the name is **not** used to access arguments. + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("cfg") + /// .long("config") + /// .value_name("FILE") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .long("config") + /// .value_name("FILE") + /// .help("Some help text")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// USAGE: + /// valnames [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [option]: Arg::takes_value() + /// [positional]: Arg::index() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + #[inline] + #[must_use] + pub fn value_name(self, name: &'help str) -> Self { + self.value_names(&[name]) + } + + /// Placeholders for the argument's values in the help message / usage. + /// + /// These names are cosmetic only, used for help and usage strings only. The names are **not** + /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. + /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will + /// be the second). + /// + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or + /// multiple value names in order to not throw off the help text alignment of all options. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("speed") + /// .short('s') + /// .value_names(&["fast", "slow"]); + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("io") + /// .long("io-files") + /// .value_names(&["INFILE", "OUTFILE"])) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// USAGE: + /// valnames [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// --io-files Some help text + /// -V, --version Print version information + /// ``` + /// [`Arg::next_line_help(true)`]: Arg::next_line_help() + /// [`Arg::number_of_values`]: Arg::number_of_values() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + #[must_use] + pub fn value_names(mut self, names: &[&'help str]) -> Self { + self.val_names = names.to_vec(); + self.takes_value(true) + } + + /// Provide the shell a hint about how to complete this argument. + /// + /// See [`ValueHint`][crate::ValueHint] for more information. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]. + /// + /// For example, to take a username as argument: + /// + /// ``` + /// # use clap::{Arg, ValueHint}; + /// Arg::new("user") + /// .short('u') + /// .long("user") + /// .value_hint(ValueHint::Username); + /// ``` + /// + /// To take a full command line and its arguments (for example, when writing a command wrapper): + /// + /// ``` + /// # use clap::{Command, Arg, ValueHint}; + /// Command::new("prog") + /// .trailing_var_arg(true) + /// .arg( + /// Arg::new("command") + /// .takes_value(true) + /// .multiple_values(true) + /// .value_hint(ValueHint::CommandWithArguments) + /// ); + /// ``` + #[must_use] + pub fn value_hint(mut self, value_hint: ValueHint) -> Self { + self.value_hint = Some(value_hint); + self.takes_value(true) + } + + /// Deprecated, replaced with [`Arg::value_parser(...)`] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`") + )] + pub fn validator(mut self, mut f: F) -> Self + where + F: FnMut(&str) -> Result + Send + 'help, + E: Into>, + { + self.validator = Some(Arc::new(Mutex::new(move |s: &str| { + f(s).map(|_| ()).map_err(|e| e.into()) + }))); + self + } + + /// Deprecated, replaced with [`Arg::value_parser(...)`] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`") + )] + pub fn validator_os(mut self, mut f: F) -> Self + where + F: FnMut(&OsStr) -> Result + Send + 'help, + E: Into>, + { + self.validator_os = Some(Arc::new(Mutex::new(move |s: &OsStr| { + f(s).map(|_| ()).map_err(|e| e.into()) + }))); + self + } + + /// Deprecated in [Issue #3743](https://github.com/clap-rs/clap/issues/3743), replaced with [`Arg::value_parser(...)`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Deprecated in Issue #3743; eplaced with `Arg::value_parser(...)`" + ) + )] + #[cfg(feature = "regex")] + #[must_use] + pub fn validator_regex( + self, + regex: impl Into>, + err_message: &'help str, + ) -> Self { + let regex = regex.into(); + self.validator(move |s: &str| { + if regex.is_match(s) { + Ok(()) + } else { + Err(err_message) + } + }) + } + + /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`" + ) + )] + #[must_use] + pub fn possible_value(mut self, value: T) -> Self + where + T: Into>, + { + self.possible_vals.push(value.into()); + self.takes_value(true) + } + + /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`" + ) + )] + #[must_use] + pub fn possible_values(mut self, values: I) -> Self + where + I: IntoIterator, + T: Into>, + { + self.possible_vals + .extend(values.into_iter().map(|value| value.into())); + self.takes_value(true) + } + + /// Match values against [`Arg::possible_values`] without matching case. + /// + /// When other arguments are conditionally required based on the + /// value of a case-insensitive argument, the equality check done + /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or + /// [`Arg::required_if_eq_all`] is case-insensitive. + /// + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .long("option") + /// .takes_value(true) + /// .ignore_case(true) + /// .value_parser(["test123"])) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", + /// ]); + /// + /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); + /// ``` + /// + /// This setting also works when multiple values can be defined: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .short('o') + /// .long("option") + /// .takes_value(true) + /// .ignore_case(true) + /// .multiple_values(true) + /// .value_parser(["test123", "test321"])) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", "teST123", "tESt321" + /// ]); + /// + /// let matched_vals = m.values_of("option").unwrap().collect::>(); + /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); + /// ``` + #[inline] + #[must_use] + pub fn ignore_case(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::IgnoreCase) + } else { + self.unset_setting(ArgSettings::IgnoreCase) + } + } + + /// Allows values which start with a leading hyphen (`-`) + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **WARNING**: Take caution when using this setting combined with + /// [`Arg::multiple_values`], as this becomes ambiguous `$ prog --arg -- -- val`. All + /// three `--, --, val` will be values when the user may have thought the second `--` would + /// constitute the normal, "Only positional args follow" idiom. To fix this, consider using + /// [`Arg::multiple_occurrences`] which only allows a single value at a time. + /// + /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and + /// the user passing in a value that matches a valid short. For example, `prog -opt -F` where + /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. + /// Care should be taken when designing these args. This is compounded by the ability to "stack" + /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid + /// shorts. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("pat") + /// .takes_value(true) + /// .allow_hyphen_values(true) + /// .long("pattern")) + /// .get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert_eq!(m.value_of("pat"), Some("-file")); + /// ``` + /// + /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a + /// hyphen is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("pat") + /// .takes_value(true) + /// .long("pattern")) + /// .try_get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::number_of_values(1)`]: Arg::number_of_values() + #[inline] + #[must_use] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowHyphenValues) + } else { + self.unset_setting(ArgSettings::AllowHyphenValues) + } + } + + /// Deprecated, replaced with [`Arg::value_parser(...)`] with either [`ValueParser::os_string()`][crate::builder::ValueParser::os_string] + /// or [`ValueParser::path_buf()`][crate::builder::ValueParser::path_buf] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `Arg::value_parser(...)` with either `ValueParser::os_string()` or `ValueParser::path_buf()`" + ) + )] + pub fn allow_invalid_utf8(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowInvalidUtf8) + } else { + self.unset_setting(ArgSettings::AllowInvalidUtf8) + } + } + + /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`" + ) + )] + pub fn forbid_empty_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::ForbidEmptyValues) + } else { + self.unset_setting(ArgSettings::ForbidEmptyValues) + } + } + + /// Requires that options use the `--option=val` syntax + /// + /// i.e. an equals between the option and associated value. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + /// Setting `require_equals` requires that the option have an equals sign between + /// it and the associated value. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config=file.conf" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `require_equals` and *not* supplying the equals will cause an + /// error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); + /// ``` + #[inline] + #[must_use] + pub fn require_equals(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireEquals) + } else { + self.unset_setting(ArgSettings::RequireEquals) + } + } + + /// Specifies that an argument should allow grouping of multiple values via a + /// delimiter. + /// + /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, + /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the + /// value delimiter for all arguments that accept values (options and positional arguments) + /// + /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`] + /// to the comma `,`. + /// + /// **NOTE:** Implicitly sets [`Arg::takes_value`] + /// + /// # Examples + /// + /// The following example shows the default behavior. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .use_value_delimiter(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(delims.contains_id("option")); + /// assert_eq!(delims.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + /// The next example shows the difference when turning delimiters off. This is the default + /// behavior + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let nodelims = Command::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(nodelims.contains_id("option")); + /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); + /// ``` + /// [`Arg::value_delimiter`]: Arg::value_delimiter() + #[inline] + #[must_use] + pub fn use_value_delimiter(mut self, yes: bool) -> Self { + if yes { + if self.val_delim.is_none() { + self.val_delim = Some(','); + } + self.takes_value(true) + .setting(ArgSettings::UseValueDelimiter) + } else { + self.val_delim = None; + self.unset_setting(ArgSettings::UseValueDelimiter) + } + } + + /// Deprecated, replaced with [`Arg::use_value_delimiter`] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::use_value_delimiter`") + )] + pub fn use_delimiter(self, yes: bool) -> Self { + self.use_value_delimiter(yes) + } + + /// Separator between the arguments values, defaults to `,` (comma). + /// + /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`] + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c') + /// .long("config") + /// .value_delimiter(';')) + /// .get_matches_from(vec![ + /// "prog", "--config=val1;val2;val3" + /// ]); + /// + /// assert_eq!(m.values_of("config").unwrap().collect::>(), ["val1", "val2", "val3"]) + /// ``` + /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + #[inline] + #[must_use] + pub fn value_delimiter(mut self, d: char) -> Self { + self.val_delim = Some(d); + self.takes_value(true).use_value_delimiter(true) + } + + /// Specifies that *multiple values* may only be set using the delimiter. + /// + /// This means if an option is encountered, and no delimiter is found, it is assumed that no + /// additional values for that option follow. This is unlike the default, where it is generally + /// assumed that more values will follow regardless of whether or not a delimiter is used. + /// + /// **NOTE:** The default is `false`. + /// + /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and + /// [`Arg::takes_value`] + /// + /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either + /// through help text or other means. + /// + /// # Examples + /// + /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice + /// everything works in this first example, as we use a delimiter, as expected. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_value_delimiter(true) + /// .require_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1,val2,val3", + /// ]); + /// + /// assert!(delims.contains_id("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + /// + /// In this next example, we will *not* use a delimiter. Notice it's now an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_value_delimiter(true) + /// .require_delimiter(true)) + /// .try_get_matches_from(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(res.is_err()); + /// let err = res.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none + /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no + /// positional arguments have been defined, it's an error of an unexpected argument. + /// + /// In this final example, we contrast the above with `clap`'s default behavior where the above + /// is *not* an error. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(delims.contains_id("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + #[inline] + #[must_use] + pub fn require_value_delimiter(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireDelimiter) + } else { + self.unset_setting(ArgSettings::RequireDelimiter) + } + } + + /// Deprecated, replaced with [`Arg::require_value_delimiter`] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::require_value_delimiter`") + )] + pub fn require_delimiter(self, yes: bool) -> Self { + self.require_value_delimiter(yes) + } + + /// Sentinel to **stop** parsing multiple values of a give argument. + /// + /// By default when + /// one sets [`multiple_values(true)`] on an argument, clap will continue parsing values for that + /// argument until it reaches another valid argument, or one of the other more specific settings + /// for multiple values is used (such as [`min_values`], [`max_values`] or + /// [`number_of_values`]). + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one + /// of the values + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("vals") + /// .takes_value(true) + /// .multiple_values(true) + /// .value_terminator(";") + /// # ; + /// ``` + /// + /// The following example uses two arguments, a sequence of commands, and the location in which + /// to perform them + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cmds") + /// .takes_value(true) + /// .multiple_values(true) + /// .allow_hyphen_values(true) + /// .value_terminator(";")) + /// .arg(Arg::new("location")) + /// .get_matches_from(vec![ + /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" + /// ]); + /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); + /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); + /// assert_eq!(m.value_of("location"), Some("/home/clap")); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + /// [`multiple_values(true)`]: Arg::multiple_values() + /// [`min_values`]: Arg::min_values() + /// [`number_of_values`]: Arg::number_of_values() + /// [`max_values`]: Arg::max_values() + #[inline] + #[must_use] + pub fn value_terminator(mut self, term: &'help str) -> Self { + self.terminator = Some(term); + self.takes_value(true) + } + + /// Consume all following arguments. + /// + /// Do not be parse them individually, but rather pass them in entirety. + /// + /// It is worth noting that setting this requires all values to come after a `--` to indicate + /// they should all be captured. For example: + /// + /// ```text + /// --foo something -- -v -v -v -b -b -b --baz -q -u -x + /// ``` + /// + /// Will result in everything after `--` to be considered one raw argument. This behavior + /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`] + /// may be more appropriate. + /// + /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] [`Arg::multiple_values(true)`], + /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. + /// + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() + /// [`Arg::last(true)`]: Arg::last() + #[inline] + #[must_use] + pub fn raw(self, yes: bool) -> Self { + self.takes_value(yes) + .multiple_values(yes) + .allow_hyphen_values(yes) + .last(yes) + } + + /// Value for the argument when not present. + /// + /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] + /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. + /// + /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will + /// still return `true`. If you wish to determine whether the argument was used at runtime or + /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided + /// a value at runtime **and** these other conditions are met as well. If you have set + /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg + /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` + /// will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// # Examples + /// + /// First we use the default value without providing any value at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg, ValueSource}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("myval")); + /// assert!(m.contains_id("opt")); + /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); + /// ``` + /// + /// Next we provide a value at runtime to override the default. + /// + /// ```rust + /// # use clap::{Command, Arg, ValueSource}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog", "--myopt=non_default" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("non_default")); + /// assert!(m.contains_id("opt")); + /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); + /// ``` + /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[inline] + #[must_use] + pub fn default_value(self, val: &'help str) -> Self { + self.default_values_os(&[OsStr::new(val)]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_value`]. + /// + /// [`Arg::default_value`]: Arg::default_value() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_value_os(self, val: &'help OsStr) -> Self { + self.default_values_os(&[val]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_value`]. + /// + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_values(self, vals: &[&'help str]) -> Self { + let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); + self.default_values_os(&vals_vec[..]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_values`]. + /// + /// [`Arg::default_values`]: Arg::default_values() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_values_os(mut self, vals: &[&'help OsStr]) -> Self { + self.default_vals = vals.to_vec(); + self.takes_value(true) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// This configuration option is often used to give the user a shortcut and allow them to + /// efficiently specify an option argument without requiring an explicitly value. The `--color` + /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, + /// the user can quickly just add `--color` to the command line to produce the desired color output. + /// + /// **NOTE:** using this configuration option requires the use of the `.min_values(0)` and the + /// `.require_equals(true)` configuration option. These are required in order to unambiguously + /// determine what, if any, value was supplied for the argument. + /// + /// # Examples + /// + /// For POSIX style `--color`: + /// ```rust + /// # use clap::{Command, Arg, ValueSource}; + /// fn cli() -> Command<'static> { + /// Command::new("prog") + /// .arg(Arg::new("color").long("color") + /// .value_name("WHEN") + /// .value_parser(["always", "auto", "never"]) + /// .default_value("auto") + /// .min_values(0) + /// .require_equals(true) + /// .default_missing_value("always") + /// .help("Specify WHEN to colorize output.") + /// ) + /// } + /// + /// // first, we'll provide no arguments + /// let m = cli().get_matches_from(vec![ + /// "prog" + /// ]); + /// assert_eq!(m.value_of("color"), Some("auto")); + /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// let m = cli().get_matches_from(vec![ + /// "prog", "--color=never" + /// ]); + /// assert_eq!(m.value_of("color"), Some("never")); + /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// let m = cli().get_matches_from(vec![ + /// "prog", "--color" + /// ]); + /// assert_eq!(m.value_of("color"), Some("always")); + /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// For bool literals: + /// ```rust + /// # use clap::{Command, Arg, ValueSource, value_parser}; + /// fn cli() -> Command<'static> { + /// Command::new("prog") + /// .arg(Arg::new("create").long("create") + /// .value_name("BOOL") + /// .value_parser(value_parser!(bool)) + /// .min_values(0) + /// .require_equals(true) + /// .default_missing_value("true") + /// ) + /// } + /// + /// // first, we'll provide no arguments + /// let m = cli().get_matches_from(vec![ + /// "prog" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), None); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// let m = cli().get_matches_from(vec![ + /// "prog", "--create=false" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), Some(false)); + /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// let m = cli().get_matches_from(vec![ + /// "prog", "--create" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), Some(true)); + /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// [`ArgMatches::value_of`]: ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_missing_value(self, val: &'help str) -> Self { + self.default_missing_values_os(&[OsStr::new(val)]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_value_os(self, val: &'help OsStr) -> Self { + self.default_missing_values_os(&[val]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + #[inline] + #[must_use] + pub fn default_missing_values(self, vals: &[&'help str]) -> Self { + let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); + self.default_missing_values_os(&vals_vec[..]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_values`]. + /// + /// [`Arg::default_missing_values`]: Arg::default_missing_values() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_values_os(mut self, vals: &[&'help OsStr]) -> Self { + self.default_missing_vals = vals.to_vec(); + self.takes_value(true) + } + + /// Read from `name` environment variable when argument is not present. + /// + /// If it is not present in the environment, then default + /// rules will apply. + /// + /// If user sets the argument in the environment: + /// - When [`Arg::takes_value(true)`] is not set, the flag is considered raised. + /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will + /// return value of the environment variable. + /// + /// If user doesn't set the argument in the environment: + /// - When [`Arg::takes_value(true)`] is not set, the flag is considered off. + /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will + /// return the default specified. + /// + /// # Examples + /// + /// In this example, we show the variable coming from the environment: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, because [`Arg::takes_value(false)`] (by default), + /// `prog` is a flag that accepts an optional, case-insensitive boolean literal. + /// A `false` literal is `n`, `no`, `f`, `false`, `off` or `0`. + /// An absent environment variable will also be considered as `false`. + /// Anything else will considered as `true`. + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("TRUE_FLAG", "true"); + /// env::set_var("FALSE_FLAG", "0"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("true_flag") + /// .long("true_flag") + /// .env("TRUE_FLAG")) + /// .arg(Arg::new("false_flag") + /// .long("false_flag") + /// .env("FALSE_FLAG")) + /// .arg(Arg::new("absent_flag") + /// .long("absent_flag") + /// .env("ABSENT_FLAG")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(m.is_present("true_flag")); + /// assert_eq!(m.value_of("true_flag"), None); + /// assert!(!m.is_present("false_flag")); + /// assert!(!m.is_present("absent_flag")); + /// ``` + /// + /// In this example, we show the variable coming from an option on the CLI: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--flag", "opt" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("opt")); + /// ``` + /// + /// In this example, we show the variable coming from the environment even with the + /// presence of a default: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true) + /// .default_value("default")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, we show the use of multiple values in a single environment variable: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG_MULTI", "env1,env2"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG_MULTI") + /// .takes_value(true) + /// .multiple_values(true) + /// .use_value_delimiter(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.values_of("flag").unwrap().collect::>(), vec!["env1", "env2"]); + /// ``` + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn env(self, name: &'help str) -> Self { + self.env_os(OsStr::new(name)) + } + + /// Read from `name` environment variable when argument is not present. + /// + /// See [`Arg::env`]. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn env_os(mut self, name: &'help OsStr) -> Self { + self.env = Some((name, env::var_os(name))); + self + } +} + +/// # Help +impl<'help> Arg<'help> { + /// Sets the description of the argument for short help (`-h`). + /// + /// Typically, this is a short (one line) description of the arg. + /// + /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [`Arg::long_help`]: Arg::long_help() + #[inline] + #[must_use] + pub fn help(mut self, h: impl Into>) -> Self { + self.help = h.into(); + self + } + + /// Sets the description of the argument for long help (`--help`). + /// + /// Typically this a more detailed (multi-line) message + /// that describes the arg. + /// + /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .long_help( + /// "The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now.")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// prog + /// + /// USAGE: + /// prog [OPTIONS] + /// + /// OPTIONS: + /// --config + /// The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now. + /// + /// -h, --help + /// Print help information + /// + /// -V, --version + /// Print version information + /// ``` + /// [`Arg::help`]: Arg::help() + #[inline] + #[must_use] + pub fn long_help(mut self, h: impl Into>) -> Self { + self.long_help = h.into(); + self + } + + /// Allows custom ordering of args within the help message. + /// + /// Args with a lower value will be displayed first in the help message. This is helpful when + /// one would like to emphasise frequently used args, or prioritize those towards the top of + /// the list. Args with duplicate display orders will be displayed in alphabetical order. + /// + /// **NOTE:** The default is 999 for all arguments. + /// + /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in + /// [index] order. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name. + /// // Args without a display_order have a value of 999 and are + /// // displayed alphabetically with all other 999 valued args. + /// .long("long-option") + /// .short('o') + /// .takes_value(true) + /// .help("Some help and text")) + /// .arg(Arg::new("b") + /// .long("other-option") + /// .short('O') + /// .takes_value(true) + /// .display_order(1) // In order to force this arg to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other args with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .help("I should be first!")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// -O, --other-option I should be first! + /// -o, --long-option Some help and text + /// ``` + /// [positional arguments]: Arg::index() + /// [index]: Arg::index() + #[inline] + #[must_use] + pub fn display_order(mut self, ord: usize) -> Self { + self.disp_ord.set_explicit(ord); + self + } + + /// Override the [current] help section. + /// + /// [current]: crate::Command::help_heading + #[inline] + #[must_use] + pub fn help_heading(mut self, heading: O) -> Self + where + O: Into>, + { + self.help_heading = Some(heading.into()); + self + } + + /// Render the [help][Arg::help] on the line after the argument. + /// + /// This can be helpful for arguments with very long or complex help messages. + /// This can also be helpful for arguments with very long flag names, or many/long value names. + /// + /// **NOTE:** To apply this setting to all arguments and subcommands, consider using + /// [`crate::Command::next_line_help`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("long-option-flag") + /// .short('o') + /// .takes_value(true) + /// .next_line_help(true) + /// .value_names(&["value1", "value2"]) + /// .help("Some really long help and complex\n\ + /// help that makes more sense to be\n\ + /// on a line after the option")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// nlh + /// + /// USAGE: + /// nlh [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// -o, --long-option-flag + /// Some really long help and complex + /// help that makes more sense to be + /// on a line after the option + /// ``` + #[inline] + #[must_use] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::NextLineHelp) + } else { + self.unset_setting(ArgSettings::NextLineHelp) + } + } + + /// Do not display the argument in help message. + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// # Examples + /// + /// Setting `Hidden` will hide the argument when displaying help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Hidden) + } else { + self.unset_setting(ArgSettings::Hidden) + } + } + + /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. + /// + /// This is useful for args with many values, or ones which are explained elsewhere in the + /// help text. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// To set this for all arguments, see + /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .value_parser(["fast", "slow"]) + /// .takes_value(true) + /// .hide_possible_values(true)); + /// ``` + /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HidePossibleValues) + } else { + self.unset_setting(ArgSettings::HidePossibleValues) + } + } + + /// Do not display the default value of the argument in the help message. + /// + /// This is useful when default behavior of an arg is explained elsewhere in the help text. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .default_value("localhost") + /// .takes_value(true) + /// .hide_default_value(true)); + /// + /// ``` + /// + /// If we were to run the above program with `--help` the `[default: localhost]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_default_value(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideDefaultValue) + } else { + self.unset_setting(ArgSettings::HideDefaultValue) + } + } + + /// Do not display in help the environment variable name. + /// + /// This is useful when the variable option is explained elsewhere in the help text. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .env("MODE") + /// .takes_value(true) + /// .hide_env(true)); + /// ``` + /// + /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help + /// text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnv) + } else { + self.unset_setting(ArgSettings::HideEnv) + } + } + + /// Do not display in help any values inside the associated ENV variables for the argument. + /// + /// This is useful when ENV vars contain sensitive values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .env("CONNECT") + /// .takes_value(true) + /// .hide_env_values(true)); + /// + /// ``` + /// + /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the + /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnvValues) + } else { + self.unset_setting(ArgSettings::HideEnvValues) + } + } + + /// Hides an argument from short help (`-h`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .hide_short_help(true); + /// ``` + /// + /// Setting `hide_short_help(true)` will hide the argument when displaying short help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when --help is called + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_short_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenShortHelp) + } else { + self.unset_setting(ArgSettings::HiddenShortHelp) + } + } + + /// Hides an argument from long help (`--help`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// Setting `hide_long_help(true)` will hide the argument when displaying long help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when -h is called + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_long_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenLongHelp) + } else { + self.unset_setting(ArgSettings::HiddenLongHelp) + } + } +} + +/// # Advanced Argument Relations +impl<'help> Arg<'help> { + /// The name of the [`ArgGroup`] the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .long("debug") + /// .group("mode") + /// # ; + /// ``` + /// + /// Multiple arguments can be a member of a single group and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .group("mode")) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .group("mode")) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.contains_id("mode")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn group(mut self, group_id: T) -> Self { + self.groups.push(group_id.into()); + self + } + + /// The names of [`ArgGroup`]'s the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"]) + /// # ; + /// ``` + /// + /// Arguments can be members of multiple groups and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"])) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .groups(&["mode", "verbosity"])) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.contains_id("mode")); + /// assert!(m.contains_id("verbosity")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn groups(mut self, group_ids: &[T]) -> Self { + self.groups.extend(group_ids.iter().map(Id::from)); + self + } + + /// Specifies the value of the argument if `arg` has been used at runtime. + /// + /// If `val` is set to `None`, `arg` only needs to be present. If `val` is set to `"some-val"` + /// then `arg` must be present at runtime **and** have the value `val`. + /// + /// If `default` is set to `None`, `default_value` will be removed. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. This setting however only takes effect when the user has not provided a value at + /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` + /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were + /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", None, Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", None, Some("default"))) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// Now lets only use the default value if `--opt` contains the value `special`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "special" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// We can run the same test and provide any value *other than* `special` and we won't get a + /// default value. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "hahaha" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// If we want to unset the default value for an Arg based on the presence or + /// value of some other Arg. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value("default") + /// .default_value_if("flag", None, None)) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::default_value`]: Arg::default_value() + #[must_use] + pub fn default_value_if( + self, + arg_id: T, + val: Option<&'help str>, + default: Option<&'help str>, + ) -> Self { + self.default_value_if_os(arg_id, val.map(OsStr::new), default.map(OsStr::new)) + } + + /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] + /// only using [`OsStr`]s instead. + /// + /// [`Arg::default_value_if`]: Arg::default_value_if() + /// [`OsStr`]: std::ffi::OsStr + #[must_use] + pub fn default_value_if_os( + mut self, + arg_id: T, + val: Option<&'help OsStr>, + default: Option<&'help OsStr>, + ) -> Self { + self.default_vals_ifs + .push((arg_id.into(), val.into(), default)); + self.takes_value(true) + } + + /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. + /// + /// The method takes a slice of tuples in the `(arg, Option, default)` format. + /// + /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first + /// if multiple conditions are true, the first one found will be applied and the ultimate value. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("chan")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// We can also see that these values are applied in order, and if more than one condition is + /// true, only the first evaluated "wins" + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[must_use] + pub fn default_value_ifs( + mut self, + ifs: &[(T, Option<&'help str>, Option<&'help str>)], + ) -> Self { + for (arg, val, default) in ifs { + self = self.default_value_if_os(arg, val.map(OsStr::new), default.map(OsStr::new)); + } + self + } + + /// Provides multiple conditional default values in the exact same manner as + /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. + /// + /// [`Arg::default_value_ifs`]: Arg::default_value_ifs() + /// [`OsStr`]: std::ffi::OsStr + #[must_use] + pub fn default_value_ifs_os( + mut self, + ifs: &[(T, Option<&'help OsStr>, Option<&'help OsStr>)], + ) -> Self { + for (arg, val, default) in ifs { + self = self.default_value_if_os(arg, *val, *default); + } + self + } + + /// Set this arg as [required] as long as the specified argument is not present at runtime. + /// + /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not + /// mandatory to also set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present("debug") + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, + /// but it's not an error because the `unless` arg has been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_unless_present(mut self, arg_id: T) -> Self { + self.r_unless.push(arg_id.into()); + self + } + + /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *all* of the `names` arguments. + /// + /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are + /// present see [`Arg::required_unless_present_any`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_all(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, but it's not an error + /// because *all* of the `names` args have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "-i", "file" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying + /// either *all* of `unless` args or the `self` arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_all(mut self, names: I) -> Self + where + I: IntoIterator, + T: Key, + { + self.r_unless_all.extend(names.into_iter().map(Id::from)); + self + } + + /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *one or more* of the `unless` arguments. + /// + /// **NOTE:** If you wish for this argument to be required unless *all of* these args are + /// present see [`Arg::required_unless_present_all`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_any(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime + /// *unless* *at least one of* the args in `names` are present. In the following example, the + /// required argument is *not* provided, but it's not an error because one the `unless` args + /// have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` + /// or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_any(mut self, names: I) -> Self + where + I: IntoIterator, + T: Key, + { + self.r_unless.extend(names.into_iter().map(Id::from)); + self + } + + /// This argument is [required] only if the specified `arg` is present at runtime and its value + /// equals `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq("other_arg", "value") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "not-special" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "special" + /// ]); + /// + /// // We did use --other=special so "cfg" had become required but was missing. + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // By default, the comparison is case-sensitive, so "cfg" wasn't required + /// assert!(res.is_ok()); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .ignore_case(true) + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq(mut self, arg_id: T, val: &'help str) -> Self { + self.r_ifs.push((arg_id.into(), val)); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_any(&[(arg, val)])` makes this arg required if any of the `arg`s + /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "other" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_any(&[(arg, val)])` and having any of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_any(mut self, ifs: &[(T, &'help str)]) -> Self { + self.r_ifs + .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if every one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_all(&[(arg, val)])` makes this arg required if all of the `arg`s + /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_all(&[(arg, val)])` and having all of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--extra", "val", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_all(mut self, ifs: &[(T, &'help str)]) -> Self { + self.r_ifs_all + .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); + self + } + + /// Require another argument if this arg was present at runtime and its value equals to `val`. + /// + /// This method takes `value, another_arg` pair. At runtime, clap will check + /// if this arg (`self`) is present and its value equals to `val`. + /// If it does, `another_arg` will be marked as required. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_if("val", "arg") + /// # ; + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument is anything other than + /// `val`, the other argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "other") + /// .long("config")) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "some.cfg" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying + /// `arg` is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "my.cfg" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_if(mut self, val: &'help str, arg_id: T) -> Self { + self.requires + .push((ArgPredicate::Equals(OsStr::new(val)), arg_id.into())); + self + } + + /// Allows multiple conditional requirements. + /// + /// The requirement will only become valid if this arg's value equals `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_ifs(&[ + /// ("val", "arg"), + /// ("other_val", "arg2"), + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::requires_ifs(&["val", "arg"])` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument's value is anything other + /// than `val`, `arg` isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_ifs(&[ + /// ("special.conf", "opt"), + /// ("other.conf", "other"), + /// ]) + /// .long("config")) + /// .arg(Arg::new("opt") + /// .long("option") + /// .takes_value(true)) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "special.conf" + /// ]); + /// + /// assert!(res.is_err()); // We used --config=special.conf so --option is required + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_ifs(mut self, ifs: &[(&'help str, T)]) -> Self { + self.requires.extend( + ifs.iter() + .map(|(val, arg)| (ArgPredicate::Equals(OsStr::new(*val)), Id::from(arg))), + ); + self + } + + /// Require these arguments names when this one is presen + /// + /// i.e. when using this argument, the following arguments *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// by default. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_all(&["input", "output"]) + /// # ; + /// ``` + /// + /// Setting `Arg::requires_all(&[arg, arg2])` requires that all the arguments be used at + /// runtime if the defining argument is used. If the defining argument isn't used, the other + /// argument isn't required + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .arg(Arg::new("output")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required + /// ``` + /// + /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an + /// error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_all(&["input", "output"]) + /// .long("config")) + /// .arg(Arg::new("input")) + /// .arg(Arg::new("output")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "in.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// // We didn't use output + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_all(mut self, names: &[T]) -> Self { + self.requires + .extend(names.iter().map(|s| (ArgPredicate::IsPresent, s.into()))); + self + } + + /// This argument is mutually exclusive with the specified argument. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. + /// + /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with("debug") + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having both arguments present at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .conflicts_with("debug") + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with(mut self, arg_id: T) -> Self { + self.blacklist.push(arg_id.into()); + self + } + + /// This argument is mutually exclusive with the specified arguments. + /// + /// See [`Arg::conflicts_with`]. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with_all(&["debug", "input"]) + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having any of the arguments present at runtime with a + /// conflicting argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .conflicts_with_all(&["debug", "input"]) + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [`Arg::conflicts_with`]: Arg::conflicts_with() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with_all(mut self, names: &[&str]) -> Self { + self.blacklist.extend(names.iter().copied().map(Id::from)); + self + } + + /// Sets an overridable argument. + /// + /// i.e. this argument and the following argument + /// will override each other in POSIX style (whichever argument was specified at runtime + /// **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. + /// + /// **WARNING:** Positional arguments and options which accept + /// [`Arg::multiple_occurrences`] cannot override themselves (or we + /// would never be able to advance to the next positional). If a positional + /// argument or option with one of the [`Arg::multiple_occurrences`] + /// settings lists itself as an override, it is simply ignored. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("debug")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with("flag")) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color + /// + /// assert!(m.is_present("color")); + /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag + /// // was never used because it was overridden with color + /// assert!(!m.is_present("flag")); + /// ``` + /// Care must be taken when using this setting, and having an arg override with itself. This + /// is common practice when supporting things like shell aliases, config files, etc. + /// However, when combined with multiple values, it can get dicy. + /// Here is how clap handles such situations: + /// + /// When a flag overrides itself, it's as if the flag was only ever used once (essentially + /// preventing a "Unexpected multiple usage" error): + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--flag "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["posix", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// ``` + /// + /// Making an arg [`Arg::multiple_occurrences`] and override itself + /// is essentially meaningless. Therefore clap ignores an override of self + /// if it's a flag and it already accepts multiple occurrences. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--flag ... "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// ``` + /// + /// Now notice with options (which *do not* set + /// [`Arg::multiple_occurrences`]), it's as if only the last + /// occurrence happened. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--opt "some option").overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.value_of("opt"), Some("other")); + /// ``` + /// + /// This will also work when [`Arg::multiple_values`] is enabled: + /// + /// ``` + /// # use clap::{Command, Arg}; + /// let m = Command::new("posix") + /// .arg( + /// Arg::new("opt") + /// .long("opt") + /// .takes_value(true) + /// .multiple_values(true) + /// .overrides_with("opt") + /// ) + /// .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["3", "4", "5"]); + /// ``` + /// + /// Just like flags, options with [`Arg::multiple_occurrences`] set + /// will ignore the "override self" setting. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--opt ... "some option") + /// .multiple_values(true) + /// .overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "over", "other", "val"]); + /// ``` + #[must_use] + pub fn overrides_with(mut self, arg_id: T) -> Self { + self.overrides.push(arg_id.into()); + self + } + + /// Sets multiple mutually overridable arguments by name. + /// + /// i.e. this argument and the following argument will override each other in POSIX style + /// (whichever argument was specified at runtime **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("color")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with_all(&["flag", "debug"])) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color + /// + /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag + /// // and debug were never used because they were overridden + /// // with color + /// assert!(!m.is_present("debug")); + /// assert!(!m.is_present("flag")); + /// ``` + #[must_use] + pub fn overrides_with_all(mut self, names: &[T]) -> Self { + self.overrides.extend(names.iter().map(Id::from)); + self + } +} + +/// # Reflection +impl<'help> Arg<'help> { + /// Get the name of the argument + #[inline] + pub fn get_id(&self) -> &'help str { + self.name + } + + /// Deprecated, replaced with [`Arg::get_id`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::get_id`") + )] + pub fn get_name(&self) -> &'help str { + self.get_id() + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&'help str> { + self.help + } + + /// Get the long help specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").long_help("long help"); + /// assert_eq!(Some("long help"), arg.get_long_help()); + /// ``` + /// + #[inline] + pub fn get_long_help(&self) -> Option<&'help str> { + self.long_help + } + + /// Get the help heading specified for this argument, if any + #[inline] + pub fn get_help_heading(&self) -> Option<&'help str> { + self.help_heading.unwrap_or_default() + } + + /// Get the short option name for this argument, if any + #[inline] + pub fn get_short(&self) -> Option { + self.short + } + + /// Get visible short aliases for this argument, if any + #[inline] + pub fn get_visible_short_aliases(&self) -> Option> { + if self.short_aliases.is_empty() { + None + } else { + Some( + self.short_aliases + .iter() + .filter_map(|(c, v)| if *v { Some(c) } else { None }) + .copied() + .collect(), + ) + } + } + + /// Get *all* short aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_short_aliases(&self) -> Option> { + if self.short_aliases.is_empty() { + None + } else { + Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) + } + } + + /// Get the short option name and its visible aliases, if any + #[inline] + pub fn get_short_and_visible_aliases(&self) -> Option> { + let mut shorts = match self.short { + Some(short) => vec![short], + None => return None, + }; + if let Some(aliases) = self.get_visible_short_aliases() { + shorts.extend(aliases); + } + Some(shorts) + } + + /// Get the long option name for this argument, if any + #[inline] + pub fn get_long(&self) -> Option<&'help str> { + self.long + } + + /// Get visible aliases for this argument, if any + #[inline] + pub fn get_visible_aliases(&self) -> Option> { + if self.aliases.is_empty() { + None + } else { + Some( + self.aliases + .iter() + .filter_map(|(s, v)| if *v { Some(s) } else { None }) + .copied() + .collect(), + ) + } + } + + /// Get *all* aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> Option> { + if self.aliases.is_empty() { + None + } else { + Some(self.aliases.iter().map(|(s, _)| s).copied().collect()) + } + } + + /// Get the long option name and its visible aliases, if any + #[inline] + pub fn get_long_and_visible_aliases(&self) -> Option> { + let mut longs = match self.long { + Some(long) => vec![long], + None => return None, + }; + if let Some(aliases) = self.get_visible_aliases() { + longs.extend(aliases); + } + Some(longs) + } + + /// Deprecated, replaced with [`Arg::get_value_parser().possible_values()`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with `Arg::get_value_parser().possible_values()`" + ) + )] + pub fn get_possible_values(&self) -> Option<&[PossibleValue<'help>]> { + if self.possible_vals.is_empty() { + None + } else { + Some(&self.possible_vals) + } + } + + pub(crate) fn get_possible_values2(&self) -> Vec> { + #![allow(deprecated)] + if !self.is_takes_value_set() { + vec![] + } else if let Some(pvs) = self.get_possible_values() { + // Check old first in case the user explicitly set possible values and the derive inferred + // a `ValueParser` with some. + pvs.to_vec() + } else { + self.get_value_parser() + .possible_values() + .map(|pvs| pvs.collect()) + .unwrap_or_default() + } + } + + /// Get the names of values for this argument. + #[inline] + pub fn get_value_names(&self) -> Option<&[&'help str]> { + if self.val_names.is_empty() { + None + } else { + Some(&self.val_names) + } + } + + /// Get the number of values for this argument. + #[inline] + pub fn get_num_vals(&self) -> Option { + self.num_vals + } + + /// Get the delimiter between multiple values + #[inline] + pub fn get_value_delimiter(&self) -> Option { + self.val_delim + } + + /// Get the index of this argument, if any + #[inline] + pub fn get_index(&self) -> Option { + self.index + } + + /// Get the value hint of this argument + pub fn get_value_hint(&self) -> ValueHint { + self.value_hint.unwrap_or_else(|| { + if self.is_takes_value_set() { + let type_id = self.get_value_parser().type_id(); + if type_id == crate::parser::AnyValueId::of::() { + ValueHint::AnyPath + } else { + ValueHint::default() + } + } else { + ValueHint::default() + } + }) + } + + /// Deprecated, replaced with [`Arg::is_global_set`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::is_global_set`") + )] + pub fn get_global(&self) -> bool { + self.is_global_set() + } + + /// Get the environment variable name specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use std::ffi::OsStr; + /// # use clap::Arg; + /// let arg = Arg::new("foo").env("ENVIRONMENT"); + /// assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env()); + /// ``` + #[cfg(feature = "env")] + pub fn get_env(&self) -> Option<&OsStr> { + self.env.as_ref().map(|x| x.0) + } + + /// Get the default values specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").default_value("default value"); + /// assert_eq!(&["default value"], arg.get_default_values()); + /// ``` + pub fn get_default_values(&self) -> &[&OsStr] { + &self.default_vals + } + + /// Checks whether this argument is a positional or not. + /// + /// # Examples + /// + /// ``` + /// # use clap::Arg; + /// let arg = Arg::new("foo"); + /// assert_eq!(true, arg.is_positional()); + /// + /// let arg = Arg::new("foo").long("foo"); + /// assert_eq!(false, arg.is_positional()); + /// ``` + pub fn is_positional(&self) -> bool { + self.long.is_none() && self.short.is_none() + } + + /// Reports whether [`Arg::required`] is set + pub fn is_required_set(&self) -> bool { + self.is_set(ArgSettings::Required) + } + + /// Report whether [`Arg::multiple_values`] is set + pub fn is_multiple_values_set(&self) -> bool { + self.is_set(ArgSettings::MultipleValues) + } + + /// [`Arg::multiple_occurrences`] is going away ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "`multiple_occurrences` away (Issue #3772)") + )] + pub fn is_multiple_occurrences_set(&self) -> bool { + self.is_set(ArgSettings::MultipleOccurrences) + } + + /// Report whether [`Arg::is_takes_value_set`] is set + pub fn is_takes_value_set(&self) -> bool { + self.is_set(ArgSettings::TakesValue) + } + + /// Report whether [`Arg::allow_hyphen_values`] is set + pub fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(ArgSettings::AllowHyphenValues) + } + + /// Deprecated, replaced with [`Arg::get_value_parser()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`") + )] + pub fn is_forbid_empty_values_set(&self) -> bool { + self.is_set(ArgSettings::ForbidEmptyValues) + } + + /// Deprecated, replaced with [`Arg::get_value_parser()` + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`") + )] + pub fn is_allow_invalid_utf8_set(&self) -> bool { + self.is_set(ArgSettings::AllowInvalidUtf8) + } + + /// Behavior when parsing the argument + pub fn get_action(&self) -> &super::ArgAction { + const DEFAULT: super::ArgAction = super::ArgAction::StoreValue; + self.action.as_ref().unwrap_or(&DEFAULT) + } + + /// Configured parser for argument values + /// + /// # Example + /// + /// ```rust + /// let cmd = clap::Command::new("raw") + /// .arg( + /// clap::Arg::new("port") + /// .value_parser(clap::value_parser!(usize)) + /// ); + /// let value_parser = cmd.get_arguments() + /// .find(|a| a.get_id() == "port").unwrap() + /// .get_value_parser(); + /// println!("{:?}", value_parser); + /// ``` + pub fn get_value_parser(&self) -> &super::ValueParser { + if let Some(value_parser) = self.value_parser.as_ref() { + value_parser + } else if self.is_allow_invalid_utf8_set() { + static DEFAULT: super::ValueParser = super::ValueParser::os_string(); + &DEFAULT + } else { + static DEFAULT: super::ValueParser = super::ValueParser::string(); + &DEFAULT + } + } + + /// Report whether [`Arg::global`] is set + pub fn is_global_set(&self) -> bool { + self.is_set(ArgSettings::Global) + } + + /// Report whether [`Arg::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(ArgSettings::NextLineHelp) + } + + /// Report whether [`Arg::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(ArgSettings::Hidden) + } + + /// Report whether [`Arg::hide_default_value`] is set + pub fn is_hide_default_value_set(&self) -> bool { + self.is_set(ArgSettings::HideDefaultValue) + } + + /// Report whether [`Arg::hide_possible_values`] is set + pub fn is_hide_possible_values_set(&self) -> bool { + self.is_set(ArgSettings::HidePossibleValues) + } + + /// Report whether [`Arg::hide_env`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_set(&self) -> bool { + self.is_set(ArgSettings::HideEnv) + } + + /// Report whether [`Arg::hide_env_values`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_values_set(&self) -> bool { + self.is_set(ArgSettings::HideEnvValues) + } + + /// Report whether [`Arg::hide_short_help`] is set + pub fn is_hide_short_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenShortHelp) + } + + /// Report whether [`Arg::hide_long_help`] is set + pub fn is_hide_long_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenLongHelp) + } + + /// Report whether [`Arg::use_value_delimiter`] is set + pub fn is_use_value_delimiter_set(&self) -> bool { + self.is_set(ArgSettings::UseValueDelimiter) + } + + /// Report whether [`Arg::require_value_delimiter`] is set + pub fn is_require_value_delimiter_set(&self) -> bool { + self.is_set(ArgSettings::RequireDelimiter) + } + + /// Report whether [`Arg::require_equals`] is set + pub fn is_require_equals_set(&self) -> bool { + self.is_set(ArgSettings::RequireEquals) + } + + /// Reports whether [`Arg::exclusive`] is set + pub fn is_exclusive_set(&self) -> bool { + self.is_set(ArgSettings::Exclusive) + } + + /// Reports whether [`Arg::last`] is set + pub fn is_last_set(&self) -> bool { + self.is_set(ArgSettings::Last) + } + + /// Reports whether [`Arg::ignore_case`] is set + pub fn is_ignore_case_set(&self) -> bool { + self.is_set(ArgSettings::IgnoreCase) + } +} + +/// # Deprecated +impl<'help> Arg<'help> { + /// Deprecated, replaced with [`Arg::new`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::new`") + )] + #[doc(hidden)] + pub fn with_name>(n: S) -> Self { + Self::new(n) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + ) + )] + #[doc(hidden)] + pub fn from_yaml(y: &'help Yaml) -> Self { + #![allow(deprecated)] + let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); + // We WANT this to panic on error...so expect() is good. + let (name_yaml, yaml) = yaml_file_hash + .iter() + .next() + .expect("There must be one arg in the YAML file"); + let name_str = name_yaml.as_str().expect("Arg name must be a string"); + let mut a = Arg::new(name_str); + + for (k, v) in yaml.as_hash().expect("Arg must be a hash") { + a = match k.as_str().expect("Arg fields must be strings") { + "short" => yaml_to_char!(a, v, short), + "long" => yaml_to_str!(a, v, long), + "aliases" => yaml_vec_or_str!(a, v, alias), + "help" => yaml_to_str!(a, v, help), + "long_help" => yaml_to_str!(a, v, long_help), + "required" => yaml_to_bool!(a, v, required), + "required_if" => yaml_tuple2!(a, v, required_if_eq), + "required_ifs" => yaml_tuple2!(a, v, required_if_eq), + "takes_value" => yaml_to_bool!(a, v, takes_value), + "index" => yaml_to_usize!(a, v, index), + "global" => yaml_to_bool!(a, v, global), + "multiple" => yaml_to_bool!(a, v, multiple), + "hidden" => yaml_to_bool!(a, v, hide), + "next_line_help" => yaml_to_bool!(a, v, next_line_help), + "group" => yaml_to_str!(a, v, group), + "number_of_values" => yaml_to_usize!(a, v, number_of_values), + "max_values" => yaml_to_usize!(a, v, max_values), + "min_values" => yaml_to_usize!(a, v, min_values), + "value_name" => yaml_to_str!(a, v, value_name), + "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), + "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), + "last" => yaml_to_bool!(a, v, last), + "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), + "value_delimiter" => yaml_to_char!(a, v, value_delimiter), + "required_unless" => yaml_to_str!(a, v, required_unless_present), + "display_order" => yaml_to_usize!(a, v, display_order), + "default_value" => yaml_to_str!(a, v, default_value), + "default_value_if" => yaml_tuple3!(a, v, default_value_if), + "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), + #[cfg(feature = "env")] + "env" => yaml_to_str!(a, v, env), + "value_names" => yaml_vec_or_str!(a, v, value_name), + "groups" => yaml_vec_or_str!(a, v, group), + "requires" => yaml_vec_or_str!(a, v, requires), + "requires_if" => yaml_tuple2!(a, v, requires_if), + "requires_ifs" => yaml_tuple2!(a, v, requires_if), + "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), + "overrides_with" => yaml_to_str!(a, v, overrides_with), + "possible_values" => yaml_vec_or_str!(a, v, possible_value), + "case_insensitive" => yaml_to_bool!(a, v, ignore_case), + "required_unless_one" => yaml_vec!(a, v, required_unless_present_any), + "required_unless_all" => yaml_vec!(a, v, required_unless_present_all), + s => { + panic!( + "Unknown setting '{}' in YAML file for arg '{}'", + s, name_str + ) + } + } + } + + a + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") + )] + #[doc(hidden)] + pub fn from_usage(u: &'help str) -> Self { + UsageParser::from_usage(u).parse() + } + + /// Deprecated, replaced with [`Arg::required_unless_present`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`") + )] + #[doc(hidden)] + #[must_use] + pub fn required_unless(self, arg_id: T) -> Self { + self.required_unless_present(arg_id) + } + + /// Deprecated, replaced with [`Arg::required_unless_present_all`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_all`" + ) + )] + #[doc(hidden)] + #[must_use] + pub fn required_unless_all(self, names: I) -> Self + where + I: IntoIterator, + T: Key, + { + self.required_unless_present_all(names) + } + + /// Deprecated, replaced with [`Arg::required_unless_present_any`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_any`" + ) + )] + #[doc(hidden)] + #[must_use] + pub fn required_unless_one(self, names: I) -> Self + where + I: IntoIterator, + T: Key, + { + self.required_unless_present_any(names) + } + + /// Deprecated, replaced with [`Arg::required_if_eq`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`") + )] + #[doc(hidden)] + #[must_use] + pub fn required_if(self, arg_id: T, val: &'help str) -> Self { + self.required_if_eq(arg_id, val) + } + + /// Deprecated, replaced with [`Arg::required_if_eq_any`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`") + )] + #[doc(hidden)] + #[must_use] + pub fn required_ifs(self, ifs: &[(T, &'help str)]) -> Self { + self.required_if_eq_any(ifs) + } + + /// Deprecated, replaced with [`Arg::hide`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`") + )] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden(self, yes: bool) -> Self { + self.hide(yes) + } + + /// Deprecated, replaced with [`Arg::ignore_case`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`") + )] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn case_insensitive(self, yes: bool) -> Self { + self.ignore_case(yes) + } + + /// Deprecated, replaced with [`Arg::forbid_empty_values`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`") + )] + #[doc(hidden)] + #[must_use] + pub fn empty_values(self, yes: bool) -> Self { + self.forbid_empty_values(!yes) + } + + /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and + /// [`Arg::multiple_values`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" + ) + )] + #[doc(hidden)] + #[must_use] + pub fn multiple(self, yes: bool) -> Self { + self.multiple_occurrences(yes).multiple_values(yes) + } + + /// Deprecated, replaced with [`Arg::hide_short_help`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`") + )] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden_short_help(self, yes: bool) -> Self { + self.hide_short_help(yes) + } + + /// Deprecated, replaced with [`Arg::hide_long_help`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`") + )] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden_long_help(self, yes: bool) -> Self { + self.hide_long_help(yes) + } + + /// Deprecated, replaced with [`Arg::setting`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`") + )] + #[doc(hidden)] + #[must_use] + pub fn set(self, s: ArgSettings) -> Self { + self.setting(s) + } + + /// Deprecated, replaced with [`Arg::unset_setting`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`") + )] + #[doc(hidden)] + #[must_use] + pub fn unset(self, s: ArgSettings) -> Self { + self.unset_setting(s) + } +} + +/// # Internally used only +impl<'help> Arg<'help> { + pub(crate) fn _build(&mut self) { + if self.is_positional() { + self.settings.set(ArgSettings::TakesValue); + } + if let Some(action) = self.action.as_ref() { + if let Some(default_value) = action.default_value() { + if self.default_vals.is_empty() { + self.default_vals = vec![default_value]; + } + } + if action.takes_values() { + self.settings.set(ArgSettings::TakesValue); + } else { + self.settings.unset(ArgSettings::TakesValue); + } + match action { + ArgAction::StoreValue + | ArgAction::IncOccurrence + | ArgAction::Help + | ArgAction::Version => {} + ArgAction::Set + | ArgAction::Append + | ArgAction::SetTrue + | ArgAction::SetFalse + | ArgAction::Count => { + if !self.is_positional() { + self.settings.set(ArgSettings::MultipleOccurrences); + } + } + } + } + + if self.value_parser.is_none() { + if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { + self.value_parser = Some(default); + } else if self.is_allow_invalid_utf8_set() { + self.value_parser = Some(super::ValueParser::os_string()); + } else { + self.value_parser = Some(super::ValueParser::string()); + } + } + + if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set()) + && self.val_delim.is_none() + { + self.val_delim = Some(','); + } + + let val_names_len = self.val_names.len(); + + if val_names_len > 1 { + self.settings.set(ArgSettings::MultipleValues); + + if self.num_vals.is_none() { + self.num_vals = Some(val_names_len); + } + } + + let self_id = self.id.clone(); + if self.is_positional() || self.is_multiple_occurrences_set() { + // Remove self-overrides where they don't make sense. + // + // We can evaluate switching this to a debug assert at a later time (though it will + // require changing propagation of `AllArgsOverrideSelf`). Being conservative for now + // due to where we are at in the release. + self.overrides.retain(|e| *e != self_id); + } + } + + pub(crate) fn generated(mut self) -> Self { + self.provider = ArgProvider::Generated; + self + } + + pub(crate) fn longest_filter(&self) -> bool { + self.is_takes_value_set() || self.long.is_some() || self.short.is_none() + } + + // Used for positionals when printing + pub(crate) fn multiple_str(&self) -> &str { + let mult_vals = self.val_names.len() > 1; + if (self.is_multiple_values_set() || self.is_multiple_occurrences_set()) && !mult_vals { + "..." + } else { + "" + } + } + + // Used for positionals when printing + pub(crate) fn name_no_brackets(&self) -> Cow { + debug!("Arg::name_no_brackets:{}", self.name); + let delim = if self.is_require_value_delimiter_set() { + self.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + } + .to_string(); + if !self.val_names.is_empty() { + debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); + + if self.val_names.len() > 1 { + Cow::Owned( + self.val_names + .iter() + .map(|n| format!("<{}>", n)) + .collect::>() + .join(&*delim), + ) + } else { + Cow::Borrowed(self.val_names.get(0).expect(INTERNAL_ERROR_MSG)) + } + } else { + debug!("Arg::name_no_brackets: just name"); + Cow::Borrowed(self.name) + } + } + + /// Either multiple values or occurrences + pub(crate) fn is_multiple(&self) -> bool { + self.is_multiple_values_set() | self.is_multiple_occurrences_set() + } + + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.get_explicit() + } +} + +impl<'help> From<&'_ Arg<'help>> for Arg<'help> { + fn from(a: &Arg<'help>) -> Self { + a.clone() + } +} + +impl<'help> PartialEq for Arg<'help> { + fn eq(&self, other: &Arg<'help>) -> bool { + self.name == other.name + } +} + +impl<'help> PartialOrd for Arg<'help> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl<'help> Ord for Arg<'help> { + fn cmp(&self, other: &Arg) -> Ordering { + self.name.cmp(other.name) + } +} + +impl<'help> Eq for Arg<'help> {} + +impl<'help> Display for Arg<'help> { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // Write the name such --long or -l + if let Some(l) = self.long { + write!(f, "--{}", l)?; + } else if let Some(s) = self.short { + write!(f, "-{}", s)?; + } + let mut need_closing_bracket = false; + if !self.is_positional() && self.is_takes_value_set() { + let is_optional_val = self.min_vals == Some(0); + let sep = if self.is_require_equals_set() { + if is_optional_val { + need_closing_bracket = true; + "[=" + } else { + "=" + } + } else if is_optional_val { + need_closing_bracket = true; + " [" + } else { + " " + }; + f.write_str(sep)?; + } + if self.is_takes_value_set() || self.is_positional() { + display_arg_val(self, |s, _| f.write_str(s))?; + } + if need_closing_bracket { + f.write_str("]")?; + } + + Ok(()) + } +} + +impl<'help> fmt::Debug for Arg<'help> { + fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { + let mut ds = f.debug_struct("Arg"); + + #[allow(unused_mut)] + let mut ds = ds + .field("id", &self.id) + .field("provider", &self.provider) + .field("name", &self.name) + .field("help", &self.help) + .field("long_help", &self.long_help) + .field("action", &self.action) + .field("value_parser", &self.value_parser) + .field("blacklist", &self.blacklist) + .field("settings", &self.settings) + .field("overrides", &self.overrides) + .field("groups", &self.groups) + .field("requires", &self.requires) + .field("r_ifs", &self.r_ifs) + .field("r_unless", &self.r_unless) + .field("short", &self.short) + .field("long", &self.long) + .field("aliases", &self.aliases) + .field("short_aliases", &self.short_aliases) + .field("disp_ord", &self.disp_ord) + .field("possible_vals", &self.possible_vals) + .field("val_names", &self.val_names) + .field("num_vals", &self.num_vals) + .field("max_vals", &self.max_vals) + .field("min_vals", &self.min_vals) + .field( + "validator", + &self.validator.as_ref().map_or("None", |_| "Some(FnMut)"), + ) + .field( + "validator_os", + &self.validator_os.as_ref().map_or("None", |_| "Some(FnMut)"), + ) + .field("val_delim", &self.val_delim) + .field("default_vals", &self.default_vals) + .field("default_vals_ifs", &self.default_vals_ifs) + .field("terminator", &self.terminator) + .field("index", &self.index) + .field("help_heading", &self.help_heading) + .field("value_hint", &self.value_hint) + .field("default_missing_vals", &self.default_missing_vals); + + #[cfg(feature = "env")] + { + ds = ds.field("env", &self.env); + } + + ds.finish() + } +} + +type Validator<'a> = dyn FnMut(&str) -> Result<(), Box> + Send + 'a; +type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box> + Send + 'a; + +#[derive(Debug, Clone, Eq, PartialEq)] +pub(crate) enum ArgProvider { + Generated, + GeneratedMutated, + User, +} + +impl Default for ArgProvider { + fn default() -> Self { + ArgProvider::User + } +} + +/// Write the values such as +pub(crate) fn display_arg_val(arg: &Arg, mut write: F) -> Result<(), E> +where + F: FnMut(&str, bool) -> Result, +{ + let mult_val = arg.is_multiple_values_set(); + let mult_occ = arg.is_multiple_occurrences_set(); + let delim = if arg.is_require_value_delimiter_set() { + arg.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + } + .to_string(); + if !arg.val_names.is_empty() { + // If have val_name. + match (arg.val_names.len(), arg.num_vals) { + (1, Some(num_vals)) => { + // If single value name with multiple num_of_vals, display all + // the values with the single value name. + let arg_name = format!("<{}>", arg.val_names.get(0).unwrap()); + for n in 1..=num_vals { + write(&arg_name, true)?; + if n != num_vals { + write(&delim, false)?; + } + } + } + (num_val_names, _) => { + // If multiple value names, display them sequentially(ignore num of vals). + let mut it = arg.val_names.iter().peekable(); + while let Some(val) = it.next() { + write(&format!("<{}>", val), true)?; + if it.peek().is_some() { + write(&delim, false)?; + } + } + if (num_val_names == 1 && mult_val) + || (arg.is_positional() && mult_occ) + || num_val_names < arg.num_vals.unwrap_or(0) + { + write("...", true)?; + } + } + } + } else if let Some(num_vals) = arg.num_vals { + // If number_of_values is specified, display the value multiple times. + let arg_name = format!("<{}>", arg.name); + for n in 1..=num_vals { + write(&arg_name, true)?; + if n != num_vals { + write(&delim, false)?; + } + } + } else if arg.is_positional() { + // Value of positional argument with no num_vals and val_names. + write(&format!("<{}>", arg.name), true)?; + + if mult_val || mult_occ { + write("...", true)?; + } + } else { + // value of flag argument with no num_vals and val_names. + write(&format!("<{}>", arg.name), true)?; + if mult_val { + write("...", true)?; + } + } + Ok(()) +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum DisplayOrder { + None, + Implicit(usize), + Explicit(usize), +} + +impl DisplayOrder { + pub(crate) fn set_explicit(&mut self, explicit: usize) { + *self = Self::Explicit(explicit) + } + + pub(crate) fn set_implicit(&mut self, implicit: usize) { + *self = (*self).max(Self::Implicit(implicit)) + } + + pub(crate) fn make_explicit(&mut self) { + match *self { + Self::None | Self::Explicit(_) => {} + Self::Implicit(disp) => self.set_explicit(disp), + } + } + + pub(crate) fn get_explicit(self) -> usize { + match self { + Self::None | Self::Implicit(_) => 999, + Self::Explicit(disp) => disp, + } + } +} + +impl Default for DisplayOrder { + fn default() -> Self { + Self::None + } +} + +// Flags +#[cfg(test)] +mod test { + use super::Arg; + + #[test] + fn flag_display() { + let mut f = Arg::new("flg").multiple_occurrences(true); + f.long = Some("flag"); + + assert_eq!(f.to_string(), "--flag"); + + let mut f2 = Arg::new("flg"); + f2.short = Some('f'); + + assert_eq!(f2.to_string(), "-f"); + } + + #[test] + fn flag_display_single_alias() { + let mut f = Arg::new("flg"); + f.long = Some("flag"); + f.aliases = vec![("als", true)]; + + assert_eq!(f.to_string(), "--flag") + } + + #[test] + fn flag_display_multiple_aliases() { + let mut f = Arg::new("flg"); + f.short = Some('f'); + f.aliases = vec![ + ("alias_not_visible", false), + ("f2", true), + ("f3", true), + ("f4", true), + ]; + assert_eq!(f.to_string(), "-f"); + } + + #[test] + fn flag_display_single_short_alias() { + let mut f = Arg::new("flg"); + f.short = Some('a'); + f.short_aliases = vec![('b', true)]; + + assert_eq!(f.to_string(), "-a") + } + + #[test] + fn flag_display_multiple_short_aliases() { + let mut f = Arg::new("flg"); + f.short = Some('a'); + f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; + assert_eq!(f.to_string(), "-a"); + } + + // Options + + #[test] + fn option_display_multiple_occurrences() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_multiple_values() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_values(true); + + assert_eq!(o.to_string(), "--option ..."); + } + + #[test] + fn option_display2() { + let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]); + + assert_eq!(o2.to_string(), "-o "); + } + + #[test] + fn option_display3() { + let o2 = Arg::new("opt") + .short('o') + .takes_value(true) + .multiple_values(true) + .value_names(&["file", "name"]); + + assert_eq!(o2.to_string(), "-o "); + } + + #[test] + fn option_display_single_alias() { + let o = Arg::new("opt") + .takes_value(true) + .long("option") + .visible_alias("als"); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_multiple_aliases() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .visible_aliases(&["als2", "als3", "als4"]) + .alias("als_not_visible"); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_single_short_alias() { + let o = Arg::new("opt") + .takes_value(true) + .short('a') + .visible_short_alias('b'); + + assert_eq!(o.to_string(), "-a "); + } + + #[test] + fn option_display_multiple_short_aliases() { + let o = Arg::new("opt") + .short('a') + .takes_value(true) + .visible_short_aliases(&['b', 'c', 'd']) + .short_alias('e'); + + assert_eq!(o.to_string(), "-a "); + } + + // Positionals + + #[test] + fn positional_display_multiple_values() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_values(true); + + assert_eq!(p.to_string(), "..."); + } + + #[test] + fn positional_display_multiple_occurrences() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(p.to_string(), "..."); + } + + #[test] + fn positional_display_required() { + let p2 = Arg::new("pos").index(1).required(true); + + assert_eq!(p2.to_string(), ""); + } + + #[test] + fn positional_display_val_names() { + let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]); + + assert_eq!(p2.to_string(), " "); + } + + #[test] + fn positional_display_val_names_req() { + let p2 = Arg::new("pos") + .index(1) + .required(true) + .value_names(&["file1", "file2"]); + + assert_eq!(p2.to_string(), " "); + } +} diff --git a/vendor/clap-3.2.20/src/builder/arg_group.rs b/vendor/clap-3.2.20/src/builder/arg_group.rs new file mode 100644 index 000000000..0fe317109 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/arg_group.rs @@ -0,0 +1,633 @@ +// Internal +use crate::util::{Id, Key}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +/// Family of related [arguments]. +/// +/// By placing arguments in a logical group, you can create easier requirement and +/// exclusion rules instead of having to list each argument individually, or when you want a rule +/// to apply "any but not all" arguments. +/// +/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is +/// set, this means that at least one argument from that group must be present. If +/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. +/// +/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for +/// another argument, meaning any of the arguments that belong to that group will cause a failure +/// if present, or must be present respectively. +/// +/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be +/// present out of a given set. Imagine that you had multiple arguments, and you want one of them +/// to be required, but making all of them required isn't feasible because perhaps they conflict +/// with each other. For example, lets say that you were building an application where one could +/// set a given version number by supplying a string with an option argument, i.e. +/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number +/// and simply incrementing one of the three numbers. So you create three flags `--major`, +/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to +/// specify that *at least one* of them is used. For this, you can create a group. +/// +/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care +/// exactly which argument was actually used at runtime. +/// +/// # Examples +/// +/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of +/// the arguments from the specified group is present at runtime. +/// +/// ```rust +/// # use clap::{Command, arg, ArgGroup, ErrorKind}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" "set the version manually").required(false)) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(&["set-ver", "major", "minor", "patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); +/// // Because we used two args in the group it's an error +/// assert!(result.is_err()); +/// let err = result.unwrap_err(); +/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); +/// ``` +/// This next example shows a passing parse of the same scenario +/// +/// ```rust +/// # use clap::{Command, arg, ArgGroup}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" "set the version manually").required(false)) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(&["set-ver", "major", "minor","patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major"]); +/// assert!(result.is_ok()); +/// let matches = result.unwrap(); +/// // We may not know which of the args was used, so we can test for the group... +/// assert!(matches.contains_id("vers")); +/// // we could also alternatively check each arg individually (not shown here) +/// ``` +/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() +/// +/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() +/// [arguments]: crate::Arg +/// [conflict]: crate::Arg::conflicts_with() +/// [requirement]: crate::Arg::requires() +#[derive(Default, Debug, PartialEq, Eq)] +pub struct ArgGroup<'help> { + pub(crate) id: Id, + pub(crate) name: &'help str, + pub(crate) args: Vec, + pub(crate) required: bool, + pub(crate) requires: Vec, + pub(crate) conflicts: Vec, + pub(crate) multiple: bool, +} + +impl<'help> ArgGroup<'help> { + pub(crate) fn with_id(id: Id) -> Self { + ArgGroup { + id, + ..ArgGroup::default() + } + } + + /// Create a `ArgGroup` using a unique name. + /// + /// The name will be used to get values from the group or refer to the group inside of conflict + /// and requirement rules. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::new("config") + /// # ; + /// ``` + pub fn new>(n: S) -> Self { + ArgGroup::default().id(n) + } + + /// Sets the group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::default().name("config") + /// # ; + /// ``` + #[must_use] + pub fn id>(mut self, n: S) -> Self { + self.name = n.into(); + self.id = Id::from(self.name); + self + } + + /// Deprecated, replaced with [`ArgGroup::id`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `ArgGroup::id`") + )] + pub fn name>(self, n: S) -> Self { + self.id(n) + } + + /// Adds an [argument] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .arg("flag") + /// .arg("color")) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.contains_id("flag")); + /// ``` + /// [argument]: crate::Arg + #[must_use] + pub fn arg(mut self, arg_id: T) -> Self { + self.args.push(arg_id.into()); + self + } + + /// Adds multiple [arguments] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"])) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.contains_id("flag")); + /// ``` + /// [arguments]: crate::Arg + #[must_use] + pub fn args(mut self, ns: &[T]) -> Self { + for n in ns { + self = self.arg(n); + } + self + } + + /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) + /// + /// # Examples + /// + /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the + /// group + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .multiple(true)) + /// .get_matches_from(vec!["myprog", "-f", "-c"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// ``` + /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw + /// an error if more than one of the args in the group was used. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"])) + /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); + /// // Because we used both args in the group it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg`]: crate::Arg + #[inline] + #[must_use] + pub fn multiple(mut self, yes: bool) -> Self { + self.multiple = yes; + self + } + + /// Require an argument from the group to be present when parsing. + /// + /// This is unless conflicting with another argument. A required group will be displayed in + /// the usage string of the application in the format ``. + /// + /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not + /// globally. + /// + /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with + /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. + /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which + /// states, '*At least* one arg from this group must be used. Using multiple is OK." + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .required(true)) + /// .try_get_matches_from(vec!["myprog"]); + /// // Because we didn't use any of the args in the group, it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgGroup::multiple`]: ArgGroup::multiple() + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn required(mut self, yes: bool) -> Self { + self.required = yes; + self + } + + /// Specify an argument or group that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when any one of the arguments from this group is used. + /// + /// **NOTE:** The name provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .requires("debug")) + /// .try_get_matches_from(vec!["myprog", "-c"]); + /// // because we used an arg from the group, and the group requires "-d" to be used, it's an + /// // error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires() + #[must_use] + pub fn requires(mut self, id: T) -> Self { + self.requires.push(id.into()); + self + } + + /// Specify arguments or groups that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when one of the arguments from this group is used. + /// + /// **NOTE:** The names provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .arg(Arg::new("verb") + /// .short('v')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .requires_all(&["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, + /// // yet we only used "-d" it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires_all() + #[must_use] + pub fn requires_all(mut self, ns: &[&'help str]) -> Self { + for n in ns { + self = self.requires(n); + } + self + } + + /// Specify an argument or group that must **not** be present when this group is. + /// + /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name + /// other arguments or groups that must *not* be present when one of the arguments from this + /// group are used. + /// + /// **NOTE:** The name provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with("debug")) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group conflicts with "-d", it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [argument exclusion rules]: crate::Arg::conflicts_with() + #[must_use] + pub fn conflicts_with(mut self, id: T) -> Self { + self.conflicts.push(id.into()); + self + } + + /// Specify arguments or groups that must **not** be present when this group is. + /// + /// Exclusion rules function just like [argument exclusion rules], you can name other arguments + /// or groups that must *not* be present when one of the arguments from this group are used. + /// + /// **NOTE:** The names provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .arg(Arg::new("verb") + /// .short('v')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with_all(&["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); + /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" + /// // it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [argument exclusion rules]: crate::Arg::conflicts_with_all() + #[must_use] + pub fn conflicts_with_all(mut self, ns: &[&'help str]) -> Self { + for n in ns { + self = self.conflicts_with(n); + } + self + } + + /// Deprecated, replaced with [`ArgGroup::new`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ArgGroup::new`") + )] + #[doc(hidden)] + pub fn with_name>(n: S) -> Self { + Self::new(n) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Maybe clap::Parser would fit your use case? (Issue #3087)" + ) + )] + #[doc(hidden)] + pub fn from_yaml(yaml: &'help Yaml) -> Self { + Self::from(yaml) + } +} + +impl<'help> From<&'_ ArgGroup<'help>> for ArgGroup<'help> { + fn from(g: &ArgGroup<'help>) -> Self { + ArgGroup { + id: g.id.clone(), + name: g.name, + required: g.required, + args: g.args.clone(), + requires: g.requires.clone(), + conflicts: g.conflicts.clone(), + multiple: g.multiple, + } + } +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl<'help> From<&'help Yaml> for ArgGroup<'help> { + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + fn from(y: &'help Yaml) -> Self { + let b = y.as_hash().expect("ArgGroup::from:: expects a table"); + // We WANT this to panic on error...so expect() is good. + let mut a = ArgGroup::default(); + let group_settings = if b.len() == 1 { + let name_yaml = b.keys().next().expect("failed to get name"); + let name_str = name_yaml + .as_str() + .expect("failed to convert arg YAML name to str"); + a.name = name_str; + a.id = Id::from(&a.name); + b.get(name_yaml) + .expect("failed to get name_str") + .as_hash() + .expect("failed to convert to a hash") + } else { + b + }; + + for (k, v) in group_settings { + a = match k.as_str().unwrap() { + "required" => a.required(v.as_bool().unwrap()), + "multiple" => a.multiple(v.as_bool().unwrap()), + "args" => yaml_vec_or_str!(a, v, arg), + "arg" => { + if let Some(ys) = v.as_str() { + a = a.arg(ys); + } + a + } + "requires" => yaml_vec_or_str!(a, v, requires), + "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), + "name" => { + if let Some(ys) = v.as_str() { + a = a.id(ys); + } + a + } + s => panic!( + "Unknown ArgGroup setting '{}' in YAML file for \ + ArgGroup '{}'", + s, a.name + ), + } + } + + a + } +} + +#[cfg(test)] +mod test { + use super::ArgGroup; + #[cfg(feature = "yaml")] + use yaml_rust::YamlLoader; + + #[test] + fn groups() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + assert_eq!(g.args, args); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); + } + + #[test] + fn test_from() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + let g2 = ArgGroup::from(&g); + assert_eq!(g2.args, args); + assert_eq!(g2.requires, reqs); + assert_eq!(g2.conflicts, confs); + } + + #[cfg(feature = "yaml")] + #[test] + fn test_yaml() { + let g_yaml = "name: test +args: +- a1 +- a4 +- a2 +- a3 +conflicts_with: +- c1 +- c2 +- c3 +- c4 +requires: +- r1 +- r2 +- r3 +- r4"; + let yaml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; + let g = ArgGroup::from(yaml); + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + assert_eq!(g.args, args); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); + } + + // This test will *fail to compile* if ArgGroup is not Send + Sync + #[test] + fn arg_group_send_sync() { + fn foo(_: T) {} + foo(ArgGroup::new("test")) + } +} + +impl Clone for ArgGroup<'_> { + fn clone(&self) -> Self { + ArgGroup { + id: self.id.clone(), + name: self.name, + required: self.required, + args: self.args.clone(), + requires: self.requires.clone(), + conflicts: self.conflicts.clone(), + multiple: self.multiple, + } + } +} diff --git a/vendor/clap-3.2.20/src/builder/arg_predicate.rs b/vendor/clap-3.2.20/src/builder/arg_predicate.rs new file mode 100644 index 000000000..58eb5494c --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/arg_predicate.rs @@ -0,0 +1,14 @@ +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum ArgPredicate<'help> { + IsPresent, + Equals(&'help std::ffi::OsStr), +} + +impl<'help> From> for ArgPredicate<'help> { + fn from(other: Option<&'help std::ffi::OsStr>) -> Self { + match other { + Some(other) => Self::Equals(other), + None => Self::IsPresent, + } + } +} diff --git a/vendor/clap-3.2.20/src/builder/arg_settings.rs b/vendor/clap-3.2.20/src/builder/arg_settings.rs new file mode 100644 index 000000000..ecc064caa --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/arg_settings.rs @@ -0,0 +1,456 @@ +#![allow(deprecated)] + +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +// Third party +use bitflags::bitflags; + +#[allow(unused)] +use crate::Arg; + +#[doc(hidden)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ArgFlags(Flags); + +impl Default for ArgFlags { + fn default() -> Self { + Self::empty() + } +} + +/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter +/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the +/// [`Arg`] methods which accept a `bool` use internally. +/// +/// [`Arg`]: crate::Arg +/// [`Arg::setting`]: crate::Arg::setting() +/// [`Arg::unset_setting`]: crate::Arg::unset_setting() +/// [`Arg::is_set`]: crate::Arg::is_set() +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum ArgSettings { + /// Deprecated, replaced with [`Arg::required`] and [`Arg::is_required_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::required` and `Arg::is_required_set`" + ) + )] + Required, + /// Deprecated, replaced with [`Arg::multiple_values`] and [`Arg::is_multiple_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::multiple_values` and `Arg::`is_multiple_values_set`" + ) + )] + MultipleValues, + /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Arg::action` (Issue #3772)") + )] + MultipleOccurrences, + /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and + /// [`ArgSettings::MultipleValues`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" + ) + )] + #[doc(hidden)] + Multiple, + /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`" + ) + )] + ForbidEmptyValues, + /// Deprecated, replaced with [`Arg::global`] and [`Arg::is_global_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::global` and `Arg::is_global_set`" + ) + )] + Global, + /// Deprecated, replaced with [`Arg::hide`] and [`Arg::is_hide_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide` and `Arg::is_hide_set`" + ) + )] + Hidden, + /// Deprecated, replaced with [`Arg::takes_value`] and [`Arg::is_takes_value_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::takes_value` and `Arg::is_takes_value_set`" + ) + )] + TakesValue, + /// Deprecated, replaced with [`Arg::use_value_delimiter`] and + /// [`Arg::is_use_value_delimiter_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::use_value_delimiter` and `Arg::is_use_value_delimiter_set`" + ) + )] + UseValueDelimiter, + /// Deprecated, replaced with [`Arg::next_line_help`] and [`Arg::is_next_line_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::next_line_help` and `Arg::is_next_line_help_set`" + ) + )] + NextLineHelp, + /// Deprecated, replaced with [`Arg::require_value_delimiter`] and + /// [`Arg::is_require_value_delimiter_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::require_value_delimiter` and `Arg::is_require_value_delimiter_set`" + ) + )] + RequireDelimiter, + /// Deprecated, replaced with [`Arg::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_possible_values` and `Arg::is_hide_possible_values_set`" + ) + )] + HidePossibleValues, + /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" + ) + )] + AllowHyphenValues, + /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" + ) + )] + #[doc(hidden)] + AllowLeadingHyphen, + /// Deprecated, replaced with [`Arg::require_equals`] and [`Arg::is_require_equals_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::require_equals` and `Arg::is_require_equals_set`" + ) + )] + RequireEquals, + /// Deprecated, replaced with [`Arg::last`] and [`Arg::is_last_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::last` and `Arg::is_last_set`" + ) + )] + Last, + /// Deprecated, replaced with [`Arg::hide_default_value`] and [`Arg::is_hide_default_value_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_default_value` and `Arg::is_hide_default_value_set`" + ) + )] + HideDefaultValue, + /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`" + ) + )] + IgnoreCase, + /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`" + ) + )] + #[doc(hidden)] + CaseInsensitive, + /// Deprecated, replaced with [`Arg::hide_env`] and [`Arg::is_hide_env_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_env` and `Arg::is_hide_env_set`" + ) + )] + #[cfg(feature = "env")] + HideEnv, + /// Deprecated, replaced with [`Arg::hide_env_values`] and [`Arg::is_hide_env_values_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_env_values` and `Arg::is_hide_env_values_set`" + ) + )] + #[cfg(feature = "env")] + HideEnvValues, + /// Deprecated, replaced with [`Arg::hide_short_help`] and [`Arg::is_hide_short_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_short_help` and `Arg::is_hide_short_help_set`" + ) + )] + HiddenShortHelp, + /// Deprecated, replaced with [`Arg::hide_long_help`] and [`Arg::is_hide_long_help_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_long_help` and `Arg::is_hide_long_help_set`" + ) + )] + HiddenLongHelp, + /// Deprecated, replaced with [`Arg::allow_invalid_utf8`] and [`Arg::is_allow_invalid_utf8_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::allow_invalid_utf8` and `Arg::is_allow_invalid_utf8_set`" + ) + )] + AllowInvalidUtf8, + /// Deprecated, replaced with [`Arg::exclusive`] and [`Arg::is_exclusive_set`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `Arg::exclusive` and `Arg::is_exclusive_set`" + ) + )] + Exclusive, +} + +bitflags! { + struct Flags: u32 { + const REQUIRED = 1; + const MULTIPLE_OCC = 1 << 1; + const NO_EMPTY_VALS = 1 << 2; + const GLOBAL = 1 << 3; + const HIDDEN = 1 << 4; + const TAKES_VAL = 1 << 5; + const USE_DELIM = 1 << 6; + const NEXT_LINE_HELP = 1 << 7; + const REQ_DELIM = 1 << 9; + const DELIM_NOT_SET = 1 << 10; + const HIDE_POS_VALS = 1 << 11; + const ALLOW_TAC_VALS = 1 << 12; + const REQUIRE_EQUALS = 1 << 13; + const LAST = 1 << 14; + const HIDE_DEFAULT_VAL = 1 << 15; + const CASE_INSENSITIVE = 1 << 16; + #[cfg(feature = "env")] + const HIDE_ENV_VALS = 1 << 17; + const HIDDEN_SHORT_H = 1 << 18; + const HIDDEN_LONG_H = 1 << 19; + const MULTIPLE_VALS = 1 << 20; + const MULTIPLE = Self::MULTIPLE_OCC.bits | Self::MULTIPLE_VALS.bits; + #[cfg(feature = "env")] + const HIDE_ENV = 1 << 21; + const UTF8_NONE = 1 << 22; + const EXCLUSIVE = 1 << 23; + const NO_OP = 0; + } +} + +impl_settings! { ArgSettings, ArgFlags, + Required => Flags::REQUIRED, + MultipleOccurrences => Flags::MULTIPLE_OCC, + MultipleValues => Flags::MULTIPLE_VALS, + Multiple => Flags::MULTIPLE, + ForbidEmptyValues => Flags::NO_EMPTY_VALS, + Global => Flags::GLOBAL, + Hidden => Flags::HIDDEN, + TakesValue => Flags::TAKES_VAL, + UseValueDelimiter => Flags::USE_DELIM, + NextLineHelp => Flags::NEXT_LINE_HELP, + RequireDelimiter => Flags::REQ_DELIM, + HidePossibleValues => Flags::HIDE_POS_VALS, + AllowHyphenValues => Flags::ALLOW_TAC_VALS, + AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, + RequireEquals => Flags::REQUIRE_EQUALS, + Last => Flags::LAST, + IgnoreCase => Flags::CASE_INSENSITIVE, + CaseInsensitive => Flags::CASE_INSENSITIVE, + #[cfg(feature = "env")] + HideEnv => Flags::HIDE_ENV, + #[cfg(feature = "env")] + HideEnvValues => Flags::HIDE_ENV_VALS, + HideDefaultValue => Flags::HIDE_DEFAULT_VAL, + HiddenShortHelp => Flags::HIDDEN_SHORT_H, + HiddenLongHelp => Flags::HIDDEN_LONG_H, + AllowInvalidUtf8 => Flags::UTF8_NONE, + Exclusive => Flags::EXCLUSIVE +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl FromStr for ArgSettings { + type Err = String; + fn from_str(s: &str) -> Result::Err> { + #[allow(deprecated)] + #[allow(unreachable_patterns)] + match &*s.to_ascii_lowercase() { + "required" => Ok(ArgSettings::Required), + "multipleoccurrences" => Ok(ArgSettings::MultipleOccurrences), + "multiplevalues" => Ok(ArgSettings::MultipleValues), + "multiple" => Ok(ArgSettings::Multiple), + "forbidemptyvalues" => Ok(ArgSettings::ForbidEmptyValues), + "global" => Ok(ArgSettings::Global), + "hidden" => Ok(ArgSettings::Hidden), + "takesvalue" => Ok(ArgSettings::TakesValue), + "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), + "nextlinehelp" => Ok(ArgSettings::NextLineHelp), + "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), + "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), + "allowhyphenvalues" => Ok(ArgSettings::AllowHyphenValues), + "allowleadinghypyhen" => Ok(ArgSettings::AllowLeadingHyphen), + "requireequals" => Ok(ArgSettings::RequireEquals), + "last" => Ok(ArgSettings::Last), + "ignorecase" => Ok(ArgSettings::IgnoreCase), + "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), + #[cfg(feature = "env")] + "hideenv" => Ok(ArgSettings::HideEnv), + #[cfg(feature = "env")] + "hideenvvalues" => Ok(ArgSettings::HideEnvValues), + "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), + "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), + "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), + "allowinvalidutf8" => Ok(ArgSettings::AllowInvalidUtf8), + "exclusive" => Ok(ArgSettings::Exclusive), + _ => Err(format!("unknown AppSetting: `{}`", s)), + } + } +} + +#[cfg(test)] +mod test { + #[test] + #[cfg(feature = "yaml")] + fn arg_settings_fromstr() { + use super::ArgSettings; + + assert_eq!( + "allowhyphenvalues".parse::().unwrap(), + ArgSettings::AllowHyphenValues + ); + assert_eq!( + "forbidemptyvalues".parse::().unwrap(), + ArgSettings::ForbidEmptyValues + ); + assert_eq!( + "hidepossiblevalues".parse::().unwrap(), + ArgSettings::HidePossibleValues + ); + assert_eq!( + "hidden".parse::().unwrap(), + ArgSettings::Hidden + ); + assert_eq!( + "nextlinehelp".parse::().unwrap(), + ArgSettings::NextLineHelp + ); + assert_eq!( + "requiredelimiter".parse::().unwrap(), + ArgSettings::RequireDelimiter + ); + assert_eq!( + "required".parse::().unwrap(), + ArgSettings::Required + ); + assert_eq!( + "takesvalue".parse::().unwrap(), + ArgSettings::TakesValue + ); + assert_eq!( + "usevaluedelimiter".parse::().unwrap(), + ArgSettings::UseValueDelimiter + ); + assert_eq!( + "requireequals".parse::().unwrap(), + ArgSettings::RequireEquals + ); + assert_eq!("last".parse::().unwrap(), ArgSettings::Last); + assert_eq!( + "hidedefaultvalue".parse::().unwrap(), + ArgSettings::HideDefaultValue + ); + assert_eq!( + "ignorecase".parse::().unwrap(), + ArgSettings::IgnoreCase + ); + #[cfg(feature = "env")] + assert_eq!( + "hideenv".parse::().unwrap(), + ArgSettings::HideEnv + ); + #[cfg(feature = "env")] + assert_eq!( + "hideenvvalues".parse::().unwrap(), + ArgSettings::HideEnvValues + ); + assert_eq!( + "hiddenshorthelp".parse::().unwrap(), + ArgSettings::HiddenShortHelp + ); + assert_eq!( + "hiddenlonghelp".parse::().unwrap(), + ArgSettings::HiddenLongHelp + ); + assert_eq!( + "allowinvalidutf8".parse::().unwrap(), + ArgSettings::AllowInvalidUtf8 + ); + assert_eq!( + "exclusive".parse::().unwrap(), + ArgSettings::Exclusive + ); + assert!("hahahaha".parse::().is_err()); + } +} diff --git a/vendor/clap-3.2.20/src/builder/command.rs b/vendor/clap-3.2.20/src/builder/command.rs new file mode 100644 index 000000000..de59ad8cd --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/command.rs @@ -0,0 +1,5189 @@ +#![allow(deprecated)] + +// Std +use std::collections::HashMap; +use std::env; +use std::ffi::OsString; +use std::fmt; +use std::io; +use std::ops::Index; +use std::path::Path; + +// Third Party +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::builder::app_settings::{AppFlags, AppSettings}; +use crate::builder::arg_settings::ArgSettings; +use crate::builder::{arg::ArgProvider, Arg, ArgGroup, ArgPredicate}; +use crate::error::ErrorKind; +use crate::error::Result as ClapResult; +use crate::mkeymap::MKeyMap; +use crate::output::fmt::Stream; +use crate::output::{fmt::Colorizer, Help, HelpWriter, Usage}; +use crate::parser::{ArgMatcher, ArgMatches, Parser}; +use crate::util::ChildGraph; +use crate::util::{color::ColorChoice, Id, Key}; +use crate::PossibleValue; +use crate::{Error, INTERNAL_ERROR_MSG}; + +#[cfg(debug_assertions)] +use crate::builder::debug_asserts::assert_app; + +/// Build a command-line interface. +/// +/// This includes defining arguments, subcommands, parser behavior, and help output. +/// Once all configuration is complete, +/// the [`Command::get_matches`] family of methods starts the runtime-parsing +/// process. These methods then return information about the user supplied +/// arguments (or lack thereof). +/// +/// When deriving a [`Parser`][crate::Parser], you can use +/// [`CommandFactory::command`][crate::CommandFactory::command] to access the +/// `Command`. +/// +/// - [Basic API][crate::App#basic-api] +/// - [Application-wide Settings][crate::App#application-wide-settings] +/// - [Command-specific Settings][crate::App#command-specific-settings] +/// - [Subcommand-specific Settings][crate::App#subcommand-specific-settings] +/// - [Reflection][crate::App#reflection] +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{Command, Arg}; +/// let m = Command::new("My Program") +/// .author("Me, me@mail.com") +/// .version("1.0.2") +/// .about("Explains in brief what the program does") +/// .arg( +/// Arg::new("in_file") +/// ) +/// .after_help("Longer explanation to appear after the options when \ +/// displaying the help information from --help or -h") +/// .get_matches(); +/// +/// // Your program logic starts here... +/// ``` +/// [`App::get_matches`]: Command::get_matches() +pub type Command<'help> = App<'help>; + +/// Deprecated, replaced with [`Command`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Command`") +)] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct App<'help> { + id: Id, + name: String, + long_flag: Option<&'help str>, + short_flag: Option, + display_name: Option, + bin_name: Option, + author: Option<&'help str>, + version: Option<&'help str>, + long_version: Option<&'help str>, + about: Option<&'help str>, + long_about: Option<&'help str>, + before_help: Option<&'help str>, + before_long_help: Option<&'help str>, + after_help: Option<&'help str>, + after_long_help: Option<&'help str>, + aliases: Vec<(&'help str, bool)>, // (name, visible) + short_flag_aliases: Vec<(char, bool)>, // (name, visible) + long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible) + usage_str: Option<&'help str>, + usage_name: Option, + help_str: Option<&'help str>, + disp_ord: Option, + term_w: Option, + max_w: Option, + template: Option<&'help str>, + settings: AppFlags, + g_settings: AppFlags, + args: MKeyMap<'help>, + subcommands: Vec>, + replacers: HashMap<&'help str, &'help [&'help str]>, + groups: Vec>, + current_help_heading: Option<&'help str>, + current_disp_ord: Option, + subcommand_value_name: Option<&'help str>, + subcommand_heading: Option<&'help str>, +} + +/// # Basic API +impl<'help> App<'help> { + /// Creates a new instance of an `Command`. + /// + /// It is common, but not required, to use binary name as the `name`. This + /// name will only be displayed to the user when they request to print + /// version or help and usage information. + /// + /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// # ; + /// ``` + pub fn new>(name: S) -> Self { + /// The actual implementation of `new`, non-generic to save code size. + /// + /// If we don't do this rustc will unnecessarily generate multiple versions + /// of this code. + fn new_inner<'help>(name: String) -> App<'help> { + App { + id: Id::from(&*name), + name, + ..Default::default() + } + .arg( + Arg::new("help") + .long("help") + .help("Print help information") + .global(true) + .generated(), + ) + .arg( + Arg::new("version") + .long("version") + .help("Print version information") + .global(true) + .generated(), + ) + } + + new_inner(name.into()) + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// // Adding a single "flag" argument with a short and help text, using Arg::new() + /// .arg( + /// Arg::new("debug") + /// .short('d') + /// .help("turns on debugging mode") + /// ) + /// // Adding a single "option" argument with a short, a long, and help text using the less + /// // verbose Arg::from() + /// .arg( + /// arg!(-c --config "Optionally sets a config file to use") + /// ) + /// # ; + /// ``` + /// [argument]: Arg + #[must_use] + pub fn arg>>(mut self, a: A) -> Self { + let mut arg = a.into(); + if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { + if !arg.is_positional() && arg.provider != ArgProvider::Generated { + let current = *current_disp_ord; + arg.disp_ord.set_implicit(current); + *current_disp_ord = current + 1; + } + } + + arg.help_heading.get_or_insert(self.current_help_heading); + self.args.push(arg); + self + } + + /// Adds multiple [arguments] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// .args(&[ + /// arg!("[debug] -d 'turns on debugging info'"), + /// Arg::new("input").help("the input file to use") + /// ]) + /// # ; + /// ``` + /// [arguments]: Arg + #[must_use] + pub fn args(mut self, args: I) -> Self + where + I: IntoIterator, + T: Into>, + { + let args = args.into_iter(); + let (lower, _) = args.size_hint(); + self.args.reserve(lower); + + for arg in args { + self = self.arg(arg); + } + self + } + + /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. + /// + /// This can be useful for modifying the auto-generated help or version arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// + /// let mut cmd = Command::new("foo") + /// .arg(Arg::new("bar") + /// .short('b')) + /// .mut_arg("bar", |a| a.short('B')); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); + /// + /// // Since we changed `bar`'s short to "B" this should err as there + /// // is no `-b` anymore, only `-B` + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + pub fn mut_arg(mut self, arg_id: T, f: F) -> Self + where + F: FnOnce(Arg<'help>) -> Arg<'help>, + T: Key + Into<&'help str>, + { + let arg_id: &str = arg_id.into(); + let id = Id::from(arg_id); + + let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg { + id, + name: arg_id, + ..Arg::default() + }); + + if a.provider == ArgProvider::Generated { + a.provider = ArgProvider::GeneratedMutated; + } + + self.args.push(f(a)); + self + } + + /// Allows one to mutate a [`Command`] after it's been added as a subcommand. + /// + /// This can be useful for modifying auto-generated arguments of nested subcommands with + /// [`Command::mut_arg`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// + /// let mut cmd = Command::new("foo") + /// .subcommand(Command::new("bar")) + /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); + /// + /// // Since we disabled the help flag on the "bar" subcommand, this should err. + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + pub fn mut_subcommand<'a, T, F>(mut self, subcmd_id: T, f: F) -> Self + where + F: FnOnce(App<'help>) -> App<'help>, + T: Into<&'a str>, + { + let subcmd_id: &str = subcmd_id.into(); + let id = Id::from(subcmd_id); + + let pos = self.subcommands.iter().position(|s| s.id == id); + + let subcmd = if let Some(idx) = pos { + self.subcommands.remove(idx) + } else { + App::new(subcmd_id) + }; + + self.subcommands.push(f(subcmd)); + self + } + + /// Adds an [`ArgGroup`] to the application. + /// + /// [`ArgGroup`]s are a family of related arguments. + /// By placing them in a logical group, you can build easier requirement and exclusion rules. + /// + /// Example use cases: + /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* + /// one) argument from that group must be present at runtime. + /// - Name an [`ArgGroup`] as a conflict to another argument. + /// Meaning any of the arguments that belong to that group will cause a failure if present with + /// the conflicting argument. + /// - Ensure exclusion between arguments. + /// - Extract a value from a group instead of determining exactly which argument was used. + /// + /// # Examples + /// + /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, + /// of the arguments from the specified group is present at runtime. + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .group(ArgGroup::new("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true)) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn group>>(mut self, group: G) -> Self { + self.groups.push(group.into()); + self + } + + /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .arg(arg!("-c [FILE] 'a config file'")) + /// .arg(arg!("-i [IFACE] 'an interface'")) + /// .groups(&[ + /// ArgGroup::new("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true), + /// ArgGroup::new("input") + /// .args(&["c", "i"]) + /// ]) + /// # ; + /// ``` + #[must_use] + pub fn groups(mut self, groups: I) -> Self + where + I: IntoIterator, + T: Into>, + { + for g in groups.into_iter() { + self = self.group(g.into()); + } + self + } + + /// Adds a subcommand to the list of valid possibilities. + /// + /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, + /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get + /// their own auto generated help, version, and usage. + /// + /// A subcommand's [`Command::name`] will be used for: + /// - The argument the user passes in + /// - Programmatically looking up the subcommand + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("config") + /// .about("Controls configuration features") + /// .arg(arg!(" 'Required configuration file to use'"))) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn subcommand>>(mut self, subcmd: S) -> Self { + self.subcommands.push(subcmd.into()); + self + } + + /// Adds multiple subcommands to the list of valid possibilities. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// # Command::new("myprog") + /// .subcommands( vec![ + /// Command::new("config").about("Controls configuration functionality") + /// .arg(Arg::new("config_file")), + /// Command::new("debug").about("Controls debug functionality")]) + /// # ; + /// ``` + /// [`IntoIterator`]: std::iter::IntoIterator + #[must_use] + pub fn subcommands(mut self, subcmds: I) -> Self + where + I: IntoIterator, + T: Into>, + { + for subcmd in subcmds.into_iter() { + self.subcommands.push(subcmd.into()); + } + self + } + + /// Catch problems earlier in the development cycle. + /// + /// Most error states are handled as asserts under the assumption they are programming mistake + /// and not something to handle at runtime. Rather than relying on tests (manual or automated) + /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those + /// asserts in a way convenient for running as a test. + /// + /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive + /// testing of your CLI. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// fn cmd() -> Command<'static> { + /// Command::new("foo") + /// .arg( + /// Arg::new("bar").short('b').action(ArgAction::SetTrue) + /// ) + /// } + /// + /// #[test] + /// fn verify_app() { + /// cmd().debug_assert(); + /// } + /// + /// fn main() { + /// let m = cmd().get_matches_from(vec!["foo", "-b"]); + /// println!("{}", *m.get_one::("bar").expect("defaulted by clap")); + /// } + /// ``` + pub fn debug_assert(mut self) { + self._build_all(); + } + + /// Custom error message for post-parsing validation + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let mut cmd = Command::new("myprog"); + /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); + /// ``` + pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { + Error::raw(kind, message).format(self) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() + #[inline] + pub fn get_matches(self) -> ArgMatches { + self.get_matches_from(&mut env::args_os()) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// Like [`App::get_matches`] but doesn't consume the `Command`. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let mut cmd = Command::new("myprog") + /// // Args and options go here... + /// ; + /// let matches = cmd.get_matches_mut(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::get_matches`]: Command::get_matches() + pub fn get_matches_mut(&mut self) -> ArgMatches { + self.try_get_matches_from_mut(&mut env::args_os()) + .unwrap_or_else(|e| e.exit()) + } + + /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a + /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call + /// [`Error::exit`] or perform a [`std::process::exit`]. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches() + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion + #[inline] + pub fn try_get_matches(self) -> ClapResult { + // Start the parsing + self.try_get_matches_from(&mut env::args_os()) + } + + /// Parse the specified arguments, exiting on failure. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`App::get_matches`]: Command::get_matches() + /// [`clap::Result`]: Result + /// [`Vec`]: std::vec::Vec + pub fn get_matches_from(mut self, itr: I) -> ArgMatches + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { + drop(self); + e.exit() + }) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches_from(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::get_matches_from`]: Command::get_matches_from() + /// [`App::try_get_matches`]: Command::try_get_matches() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Error`]: crate::Error + /// [`Error::exit`]: crate::Error::exit() + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion + /// [`clap::Result`]: Result + pub fn try_get_matches_from(mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from_mut(itr) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// Like [`App::try_get_matches_from`] but doesn't consume the `Command`. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut cmd = Command::new("myprog"); + /// // Args and options go here... + /// let matches = cmd.try_get_matches_from_mut(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::try_get_matches_from`]: Command::try_get_matches_from() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + pub fn try_get_matches_from_mut(&mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); + let mut cursor = raw_args.cursor(); + + if self.settings.is_set(AppSettings::Multicall) { + if let Some(argv0) = raw_args.next_os(&mut cursor) { + let argv0 = Path::new(&argv0); + if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { + // Stop borrowing command so we can get another mut ref to it. + let command = command.to_owned(); + debug!( + "Command::try_get_matches_from_mut: Parsed command {} from argv", + command + ); + + debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); + raw_args.insert(&cursor, &[&command]); + debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); + self.name.clear(); + self.bin_name = None; + return self._do_parse(&mut raw_args, cursor); + } + } + }; + + // Get the name of the program (argument 1 of env::args()) and determine the + // actual file + // that was used to execute the program. This is because a program called + // ./target/release/my_prog -a + // will have two arguments, './target/release/my_prog', '-a' but we don't want + // to display + // the full path when displaying help messages and such + if !self.settings.is_set(AppSettings::NoBinaryName) { + if let Some(name) = raw_args.next_os(&mut cursor) { + let p = Path::new(name); + + if let Some(f) = p.file_name() { + if let Some(s) = f.to_str() { + if self.bin_name.is_none() { + self.bin_name = Some(s.to_owned()); + } + } + } + } + } + + self._do_parse(&mut raw_args, cursor) + } + + /// Prints the short help message (`-h`) to [`io::stdout()`]. + /// + /// See also [`Command::print_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + pub fn print_help(&mut self) -> io::Result<()> { + self._build_self(); + let color = self.color_help(); + + let mut c = Colorizer::new(Stream::Stdout, color); + let usage = Usage::new(self); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, false).write_help()?; + c.print() + } + + /// Prints the long help message (`--help`) to [`io::stdout()`]. + /// + /// See also [`Command::print_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_long_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + /// [`BufWriter`]: std::io::BufWriter + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn print_long_help(&mut self) -> io::Result<()> { + self._build_self(); + let color = self.color_help(); + + let mut c = Colorizer::new(Stream::Stdout, color); + let usage = Usage::new(self); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, true).write_help()?; + c.print() + } + + /// Writes the short help message (`-h`) to a [`io::Write`] object. + /// + /// See also [`Command::write_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// cmd.write_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn write_help(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(); + + let usage = Usage::new(self); + Help::new(HelpWriter::Normal(w), self, &usage, false).write_help()?; + w.flush() + } + + /// Writes the long help message (`--help`) to a [`io::Write`] object. + /// + /// See also [`Command::write_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// cmd.write_long_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn write_long_help(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(); + + let usage = Usage::new(self); + Help::new(HelpWriter::Normal(w), self, &usage, true).write_help()?; + w.flush() + } + + /// Version message rendered as if the user ran `-V`. + /// + /// See also [`Command::render_long_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_version(&self) -> String { + self._render_version(false) + } + + /// Version message rendered as if the user ran `--version`. + /// + /// See also [`Command::render_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_long_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_long_version(&self) -> String { + self._render_version(true) + } + + /// Usage statement + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// println!("{}", cmd.render_usage()); + /// ``` + pub fn render_usage(&mut self) -> String { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self._build_self(); + + Usage::new(self).create_usage_with_title(&[]) + } +} + +/// # Application-wide Settings +/// +/// These settings will apply to the top-level command and all subcommands, by default. Some +/// settings can be overridden in subcommands. +impl<'help> App<'help> { + /// Specifies that the parser should not assume the first argument passed is the binary name. + /// + /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see + /// [`Command::multicall`][App::multicall]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .no_binary_name(true) + /// .arg(arg!( ... "commands to run")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(cmds, ["command", "set"]); + /// ``` + /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() + #[inline] + pub fn no_binary_name(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NoBinaryName) + } else { + self.unset_global_setting(AppSettings::NoBinaryName) + } + } + + /// Try not to fail on parse errors, like missing option values. + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let cmd = Command::new("cmd") + /// .ignore_errors(true) + /// .arg(arg!(-c --config "Sets a custom config file").required(false)) + /// .arg(arg!(-x --stuff "Sets a custom stuff file").required(false)) + /// .arg(arg!(f: -f "Flag")); + /// + /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); + /// + /// assert!(r.is_ok(), "unexpected error: {:?}", r); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of("config"), Some("file")); + /// assert!(m.is_present("f")); + /// assert_eq!(m.value_of("stuff"), None); + /// ``` + #[inline] + pub fn ignore_errors(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::IgnoreErrors) + } else { + self.unset_global_setting(AppSettings::IgnoreErrors) + } + } + + /// Deprecated, replaced with [`ArgAction::Set`][super::ArgAction::Set] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `Arg::action(ArgAction::Set)`") + )] + pub fn args_override_self(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::AllArgsOverrideSelf) + } else { + self.unset_global_setting(AppSettings::AllArgsOverrideSelf) + } + } + + /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] + /// was used. + /// + /// **NOTE:** The same thing can be done manually by setting the final positional argument to + /// [`Arg::use_value_delimiter(false)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .dont_delimit_trailing_values(true) + /// .get_matches(); + /// ``` + /// + /// [`Arg::use_value_delimiter(false)`]: crate::Arg::use_value_delimiter() + #[inline] + pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DontDelimitTrailingValues) + } else { + self.unset_global_setting(AppSettings::DontDelimitTrailingValues) + } + } + + /// Sets when to color output. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Never) + /// .get_matches(); + /// ``` + /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto + #[cfg(feature = "color")] + #[inline] + #[must_use] + pub fn color(self, color: ColorChoice) -> Self { + #![allow(deprecated)] + let cmd = self + .unset_global_setting(AppSettings::ColorAuto) + .unset_global_setting(AppSettings::ColorAlways) + .unset_global_setting(AppSettings::ColorNever); + match color { + ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), + ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), + ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), + } + } + + /// Sets the terminal width at which to wrap help messages. + /// + /// Using `0` will ignore terminal widths and use source formatting. + /// + /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag + /// is disabled or it cannot be determined, the default is 100. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .term_width(80) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn term_width(mut self, width: usize) -> Self { + self.term_w = Some(width); + self + } + + /// Sets the maximum terminal width at which to wrap help messages. + /// + /// This only applies when setting the current terminal width. See [`Command::term_width`] for + /// more details. + /// + /// Using `0` will ignore terminal widths and use source formatting. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .max_term_width(100) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn max_term_width(mut self, w: usize) -> Self { + self.max_w = Some(w); + self + } + + /// Disables `-V` and `--version` flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_version_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_version_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableVersionFlag) + } else { + self.unset_global_setting(AppSettings::DisableVersionFlag) + } + } + + /// Specifies to use the version of the current command for all [`subcommands`]. + /// + /// Defaults to `false`; subcommands have independent version strings from their parents. + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .version("v1.1") + /// .propagate_version(true) + /// .subcommand(Command::new("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + #[inline] + pub fn propagate_version(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::PropagateVersion) + } else { + self.unset_global_setting(AppSettings::PropagateVersion) + } + } + + /// Places the help string for all arguments and subcommands on the line after them. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .next_line_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NextLineHelp) + } else { + self.unset_global_setting(AppSettings::NextLineHelp) + } + } + + /// Disables `-h` and `--help` flag. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_help_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpFlag) + } else { + self.unset_global_setting(AppSettings::DisableHelpFlag) + } + } + + /// Disables the `help` [`subcommand`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_subcommand(true) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn disable_help_subcommand(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpSubcommand) + } else { + self.unset_global_setting(AppSettings::DisableHelpSubcommand) + } + } + + /// Disables colorized help messages. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .disable_colored_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn disable_colored_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableColoredHelp) + } else { + self.unset_global_setting(AppSettings::DisableColoredHelp) + } + } + + /// Panic if help descriptions are omitted. + /// + /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at + /// compile-time with `#![deny(missing_docs)]` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo").help("It does foo stuff") + /// // As required via `help_expected`, a help message was supplied + /// ) + /// # .get_matches(); + /// ``` + /// + /// # Panics + /// + /// ```rust,no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo") + /// // Someone forgot to put .about("...") here + /// // Since the setting `help_expected` is activated, this will lead to + /// // a panic (if you are in debug mode) + /// ) + /// # .get_matches(); + ///``` + #[inline] + pub fn help_expected(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HelpExpected) + } else { + self.unset_global_setting(AppSettings::HelpExpected) + } + } + + /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .dont_collapse_args_in_usage(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn dont_collapse_args_in_usage(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DontCollapseArgsInUsage) + } else { + self.unset_global_setting(AppSettings::DontCollapseArgsInUsage) + } + } + + /// Tells `clap` *not* to print possible values when displaying help information. + /// + /// This can be useful if there are many values, or they are explained elsewhere. + /// + /// To set this per argument, see + /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + #[inline] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HidePossibleValues) + } else { + self.unset_global_setting(AppSettings::HidePossibleValues) + } + } + + /// Allow partial matches of long arguments or their [aliases]. + /// + /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and + /// `--test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match + /// `--te` to `--test` there could not also be another argument or alias `--temp` because both + /// start with `--te` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_long_args(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferLongArgs) + } else { + self.unset_global_setting(AppSettings::InferLongArgs) + } + } + + /// Allow partial matches of [subcommand] names and their [aliases]. + /// + /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and + /// `test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` + /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` + /// + /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when + /// designing CLIs which allow inferred subcommands and have potential positional/free + /// arguments whose values could start with the same characters as subcommands. If this is the + /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in + /// conjunction with this setting. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .infer_subcommands(true) + /// .subcommand(Command::new("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// + /// [subcommand]: crate::Command::subcommand() + /// [positional/free arguments]: crate::Arg::index() + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_subcommands(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferSubcommands) + } else { + self.unset_global_setting(AppSettings::InferSubcommands) + } + } +} + +/// # Command-specific Settings +/// +/// These apply only to the current command and are not inherited by subcommands. +impl<'help> App<'help> { + /// (Re)Sets the program's name. + /// + /// See [`Command::new`] for more details. + /// + /// # Examples + /// + /// ```ignore + /// # use clap::{Command, load_yaml}; + /// let yaml = load_yaml!("cmd.yaml"); + /// let cmd = Command::from(yaml) + /// .name(crate_name!()); + /// + /// // continued logic goes here, such as `cmd.get_matches()` etc. + /// ``` + #[must_use] + pub fn name>(mut self, name: S) -> Self { + self.name = name.into(); + self + } + + /// Overrides the runtime-determined name of the binary for help and error messages. + /// + /// This should only be used when absolutely necessary, such as when the binary name for your + /// application is misleading, or perhaps *not* how the user should invoke your program. + /// + /// **Pro-tip:** When building things such as third party `cargo` + /// subcommands, this setting **should** be used! + /// + /// **NOTE:** This *does not* change or set the name of the binary file on + /// disk. It only changes what clap thinks the name is for the purposes of + /// error or help messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .bin_name("my_binary") + /// # ; + /// ``` + #[must_use] + pub fn bin_name>(mut self, name: S) -> Self { + self.bin_name = Some(name.into()); + self + } + + /// Overrides the runtime-determined display name of the program for help and error messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .display_name("my_program") + /// # ; + /// ``` + #[must_use] + pub fn display_name>(mut self, name: S) -> Self { + self.display_name = Some(name.into()); + self + } + + /// Sets the author(s) for the help message. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to + /// automatically set your application's author(s) to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .author("Me, me@mymain.com") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + #[must_use] + pub fn author>(mut self, author: S) -> Self { + self.author = Some(author.into()); + self + } + + /// Sets the program's description for the short help (`-h`). + /// + /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Command::about` (short format) is used in completion + /// script generation in order to be concise. + /// + /// See also [`crate_description!`](crate::crate_description!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .about("Does really amazing things for great people") + /// # ; + /// ``` + #[must_use] + pub fn about>>(mut self, about: O) -> Self { + self.about = about.into(); + self + } + + /// Sets the program's description for the long help (`--help`). + /// + /// If [`Command::about`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Command::about`] (short format) is used in completion + /// script generation in order to be concise. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_about( + /// "Does really amazing things to great people. Now let's talk a little + /// more in depth about how this subcommand really works. It may take about + /// a few lines of text, but that's ok!") + /// # ; + /// ``` + /// [`App::about`]: Command::about() + #[must_use] + pub fn long_about>>(mut self, long_about: O) -> Self { + self.long_about = long_about.into(); + self + } + + /// Free-form help text for after auto-generated short help (`-h`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_help("Does really amazing things for great people... but be careful with -R!") + /// # ; + /// ``` + /// + #[must_use] + pub fn after_help>(mut self, help: S) -> Self { + self.after_help = Some(help.into()); + self + } + + /// Free-form help text for after auto-generated long help (`--help`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ + /// like, for real, be careful with this!") + /// # ; + /// ``` + #[must_use] + pub fn after_long_help>(mut self, help: S) -> Self { + self.after_long_help = Some(help.into()); + self + } + + /// Free-form help text for before auto-generated short help (`-h`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_help("Some info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_help>(mut self, help: S) -> Self { + self.before_help = Some(help.into()); + self + } + + /// Free-form help text for before auto-generated long help (`--help`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_long_help("Some verbose and long info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_long_help>(mut self, help: S) -> Self { + self.before_long_help = Some(help.into()); + self + } + + /// Sets the version for the short version (`-V`) and help messages. + /// + /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("v0.1.24") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + #[must_use] + pub fn version>(mut self, ver: S) -> Self { + self.version = Some(ver.into()); + self + } + + /// Sets the version for the long version (`--version`) and help messages. + /// + /// If [`Command::version`] is not specified, this message will be displayed for `-V`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_version( + /// "v0.1.24 + /// commit: abcdef89726d + /// revision: 123 + /// release: 2 + /// binary: myprog") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + #[must_use] + pub fn long_version>(mut self, ver: S) -> Self { + self.long_version = Some(ver.into()); + self + } + + /// Overrides the `clap` generated usage string for help and error messages. + /// + /// **NOTE:** Using this setting disables `clap`s "context-aware" usage + /// strings. After this setting is set, this will be *the only* usage string + /// displayed to the user! + /// + /// **NOTE:** Multiple usage lines may be present in the usage argument, but + /// some rules need to be followed to ensure the usage lines are formatted + /// correctly by the default help formatter: + /// + /// - Do not indent the first usage line. + /// - Indent all subsequent usage lines with four spaces. + /// - The last line must not end with a newline. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage("myapp [-clDas] ") + /// # ; + /// ``` + /// + /// Or for multiple usage lines: + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage( + /// "myapp -X [-a] [-b] \n \ + /// myapp -Y [-c] \n \ + /// myapp -Z [-d|-e]" + /// ) + /// # ; + /// ``` + /// + /// [`ArgMatches::usage`]: ArgMatches::usage() + #[must_use] + pub fn override_usage>(mut self, usage: S) -> Self { + self.usage_str = Some(usage.into()); + self + } + + /// Overrides the `clap` generated help message (both `-h` and `--help`). + /// + /// This should only be used when the auto-generated message does not suffice. + /// + /// **NOTE:** This **only** replaces the help message for the current + /// command, meaning if you are using subcommands, those help messages will + /// still be auto-generated unless you specify a [`Command::override_help`] for + /// them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .override_help("myapp v1.0\n\ + /// Does awesome things\n\ + /// (C) me@mail.com\n\n\ + /// + /// USAGE: myapp \n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s Do something with stuff\n\ + /// -v Be verbose\n\n\ + /// + /// Commands:\n\ + /// help Print this message\n\ + /// work Do some work") + /// # ; + /// ``` + #[must_use] + pub fn override_help>(mut self, help: S) -> Self { + self.help_str = Some(help.into()); + self + } + + /// Sets the help template to be used, overriding the default format. + /// + /// **NOTE:** The template system is by design very simple. Therefore, the + /// tags have to be written in the lowercase and without spacing. + /// + /// Tags are given inside curly brackets. + /// + /// Valid tags are: + /// + /// * `{name}` - Display name for the (sub-)command. + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{author-with-newline}` - Author followed by `\n`. + /// * `{author-section}` - Author preceded and followed by `\n`. + /// * `{about}` - General description (from [`Command::about`] or + /// [`Command::long_about`]). + /// * `{about-with-newline}` - About followed by `\n`. + /// * `{about-section}` - About preceded and followed by '\n'. + /// * `{usage-heading}` - Automatically generated usage heading. + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positional + /// arguments, and subcommands) including titles. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positional arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Help from [`App::after_help`] or [`Command::after_long_help`]. + /// * `{before-help}` - Help from [`App::before_help`] or [`Command::before_long_help`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("1.0") + /// .help_template("{bin} ({version}) - {usage}") + /// # ; + /// ``` + /// [`App::about`]: Command::about() + /// [`App::long_about`]: Command::long_about() + /// [`App::after_help`]: Command::after_help() + /// [`App::after_long_help`]: Command::after_long_help() + /// [`App::before_help`]: Command::before_help() + /// [`App::before_long_help`]: Command::before_long_help() + #[must_use] + pub fn help_template>(mut self, s: S) -> Self { + self.template = Some(s.into()); + self + } + + /// Apply a setting for the current command or subcommand. + /// + /// See [`Command::global_setting`] to apply a setting to this command and all subcommands. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + /// Remove a setting for the current command or subcommand. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.remove(setting.into()); + self + } + + /// Apply a setting for the current command and all subcommands. + /// + /// See [`Command::setting`] to apply a setting only to this command. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .global_setting(AppSettings::AllowNegativeNumbers) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn global_setting(mut self, setting: AppSettings) -> Self { + self.settings.set(setting); + self.g_settings.set(setting); + self + } + + /// Remove a setting and stop propagating down to subcommands. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_global_setting(AppSettings::AllowNegativeNumbers) + /// # ; + /// ``` + /// [global]: Command::global_setting() + #[inline] + #[must_use] + pub fn unset_global_setting(mut self, setting: AppSettings) -> Self { + self.settings.unset(setting); + self.g_settings.unset(setting); + self + } + + /// Deprecated, replaced with [`Command::next_help_heading`] + #[inline] + #[must_use] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `App::next_help_heading`") + )] + pub fn help_heading(self, heading: O) -> Self + where + O: Into>, + { + self.next_help_heading(heading) + } + + /// Set the default section heading for future args. + /// + /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. + /// + /// This is useful if the default `OPTIONS` or `ARGS` headings are + /// not specific enough for one's use case. + /// + /// For subcommands, see [`Command::subcommand_help_heading`] + /// + /// [`App::arg`]: Command::arg() + /// [`Arg::help_heading`]: crate::Arg::help_heading() + #[inline] + #[must_use] + pub fn next_help_heading(mut self, heading: O) -> Self + where + O: Into>, + { + self.current_help_heading = heading.into(); + self + } + + /// Change the starting value for assigning future display orders for ags. + /// + /// This will be used for any arg that hasn't had [`Arg::display_order`] called. + #[inline] + #[must_use] + pub fn next_display_order(mut self, disp_ord: impl Into>) -> Self { + self.current_disp_ord = disp_ord.into(); + self + } + + /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. + /// + /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) + /// + /// When this method is used, `name` is removed from the CLI, and `target` + /// is inserted in its place. Parsing continues as if the user typed + /// `target` instead of `name`. + /// + /// This can be used to create "shortcuts" for subcommands, or if a + /// particular argument has the semantic meaning of several other specific + /// arguments and values. + /// + /// # Examples + /// + /// We'll start with the "subcommand short" example. In this example, let's + /// assume we have a program with a subcommand `module` which can be invoked + /// via `cmd module`. Now let's also assume `module` also has a subcommand + /// called `install` which can be invoked `cmd module install`. If for some + /// reason users needed to be able to reach `cmd module install` via the + /// short-hand `cmd install`, we'd have several options. + /// + /// We *could* create another sibling subcommand to `module` called + /// `install`, but then we would need to manage another subcommand and manually + /// dispatch to `cmd module install` handling code. This is error prone and + /// tedious. + /// + /// We could instead use [`Command::replace`] so that, when the user types `cmd + /// install`, `clap` will replace `install` with `module install` which will + /// end up getting parsed as if the user typed the entire incantation. + /// + /// ```rust + /// # use clap::Command; + /// let m = Command::new("cmd") + /// .subcommand(Command::new("module") + /// .subcommand(Command::new("install"))) + /// .replace("install", &["module", "install"]) + /// .get_matches_from(vec!["cmd", "install"]); + /// + /// assert!(m.subcommand_matches("module").is_some()); + /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); + /// ``` + /// + /// Now let's show an argument example! + /// + /// Let's assume we have an application with two flags `--save-context` and + /// `--save-runtime`. But often users end up needing to do *both* at the + /// same time. We can add a third flag `--save-all` which semantically means + /// the same thing as `cmd --save-context --save-runtime`. To implement that, + /// we have several options. + /// + /// We could create this third argument and manually check if that argument + /// and in our own consumer code handle the fact that both `--save-context` + /// and `--save-runtime` *should* have been used. But again this is error + /// prone and tedious. If we had code relying on checking `--save-context` + /// and we forgot to update that code to *also* check `--save-all` it'd mean + /// an error! + /// + /// Luckily we can use [`Command::replace`] so that when the user types + /// `--save-all`, `clap` will replace that argument with `--save-context + /// --save-runtime`, and parsing will continue like normal. Now all our code + /// that was originally checking for things like `--save-context` doesn't + /// need to change! + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime") + /// .action(ArgAction::SetTrue)) + /// .replace("--save-all", &["--save-context", "--save-runtime"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(*m.get_one::("save-context").expect("defaulted by clap")); + /// assert!(*m.get_one::("save-runtime").expect("defaulted by clap")); + /// ``` + /// + /// This can also be used with options, for example if our application with + /// `--save-*` above also had a `--format=TYPE` option. Let's say it + /// accepted `txt` or `json` values. However, when `--save-all` is used, + /// only `--format=json` is allowed, or valid. We could change the example + /// above to enforce this: + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("format") + /// .long("format") + /// .takes_value(true) + /// .value_parser(["txt", "json"])) + /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(*m.get_one::("save-context").expect("defaulted by clap")); + /// assert!(*m.get_one::("save-runtime").expect("defaulted by clap")); + /// assert_eq!(m.value_of("format"), Some("json")); + /// ``` + /// + /// [`App::replace`]: Command::replace() + #[inline] + #[cfg(feature = "unstable-replace")] + #[must_use] + pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self { + self.replacers.insert(name, target); + self + } + + /// Exit gracefully if no arguments are present (e.g. `$ myprog`). + /// + /// **NOTE:** [`subcommands`] count as arguments + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command}; + /// Command::new("myprog") + /// .arg_required_else_help(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::default_value`]: crate::Arg::default_value() + #[inline] + pub fn arg_required_else_help(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgRequiredElseHelp) + } else { + self.unset_setting(AppSettings::ArgRequiredElseHelp) + } + } + + /// Specifies that leading hyphens are allowed in all argument *values* (e.g. `-10`). + /// + /// Otherwise they will be parsed as another flag or option. See also + /// [`Command::allow_negative_numbers`]. + /// + /// **NOTE:** Use this setting with caution as it silences certain circumstances which would + /// otherwise be an error (such as accidentally forgetting to specify a value for leading + /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Arg, Command}; + /// // Imagine you needed to represent negative numbers as well, such as -10 + /// let m = Command::new("nums") + /// .allow_hyphen_values(true) + /// .arg(Arg::new("neg")) + /// .get_matches_from(vec![ + /// "nums", "-20" + /// ]); + /// + /// assert_eq!(m.value_of("neg"), Some("-20")); + /// # ; + /// ``` + /// [`Arg::allow_hyphen_values`]: crate::Arg::allow_hyphen_values() + #[inline] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowHyphenValues) + } else { + self.unset_setting(AppSettings::AllowHyphenValues) + } + } + + /// Allows negative numbers to pass as values. + /// + /// This is similar to [`Command::allow_hyphen_values`] except that it only allows numbers, + /// all other undefined leading hyphens will fail to parse. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("myprog") + /// .allow_negative_numbers(true) + /// .arg(Arg::new("num")) + /// .try_get_matches_from(vec![ + /// "myprog", "-20" + /// ]); + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("num").unwrap(), "-20"); + /// ``` + #[inline] + pub fn allow_negative_numbers(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowNegativeNumbers) + } else { + self.unset_setting(AppSettings::AllowNegativeNumbers) + } + } + + /// Specifies that the final positional argument is a "VarArg" and that `clap` should not + /// attempt to parse any further args. + /// + /// The values of the trailing positional argument will contain all args from itself on. + /// + /// **NOTE:** The final positional argument **must** have [`Arg::multiple_values(true)`] or the usage + /// string equivalent. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .trailing_var_arg(true) + /// .arg(arg!( ... "commands to run")) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(trail, ["arg1", "-r", "val1"]); + /// ``` + /// [`Arg::multiple_values(true)`]: crate::Arg::multiple_values() + pub fn trailing_var_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::TrailingVarArg) + } else { + self.unset_setting(AppSettings::TrailingVarArg) + } + } + + /// Allows one to implement two styles of CLIs where positionals can be used out of order. + /// + /// The first example is a CLI where the second to last positional argument is optional, but + /// the final positional argument is required. Such as `$ prog [optional] ` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] ` + /// * `$ prog ` + /// + /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. + /// + /// **Note:** when using this style of "missing positionals" the final positional *must* be + /// [required] if `--` will not be used to skip to the final positional argument. + /// + /// **Note:** This style also only allows a single positional argument to be "skipped" without + /// the use of `--`. To skip more than one, see the second example. + /// + /// The second example is when one wants to skip multiple optional positional arguments, and use + /// of the `--` operator is OK (but not required if all arguments will be specified anyways). + /// + /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where + /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). + /// + /// With this setting the following invocations are posisble: + /// + /// * `$ prog foo bar baz1 baz2 baz3` + /// * `$ prog foo -- baz1 baz2 baz3` + /// * `$ prog -- baz1 baz2 baz3` + /// + /// # Examples + /// + /// Style number one from above: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), None); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Now the same example, but using a default value for the first optional positional argument + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1") + /// .default_value("something")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), Some("something")); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Style number two from above: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "foo", "bar", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), Some("foo")); + /// assert_eq!(m.value_of("bar"), Some("bar")); + /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "--", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), None); + /// assert_eq!(m.value_of("bar"), None); + /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// [required]: crate::Arg::required() + #[inline] + pub fn allow_missing_positional(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowMissingPositional) + } else { + self.unset_setting(AppSettings::AllowMissingPositional) + } + } +} + +/// # Subcommand-specific Settings +impl<'help> App<'help> { + /// Sets the short version of the subcommand flag without the preceding `-`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::short`]. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, Arg, ArgAction}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").short_flag('S').arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .action(ArgAction::SetTrue) + /// .help("search remote repositories for matching strings"), + /// ), + /// ) + /// .get_matches_from(vec!["pacman", "-Ss"]); + /// + /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); + /// let sync_matches = matches.subcommand_matches("sync").unwrap(); + /// assert!(*sync_matches.get_one::("search").expect("defaulted by clap")); + /// ``` + /// [`Arg::short`]: Arg::short() + #[must_use] + pub fn short_flag(mut self, short: char) -> Self { + self.short_flag = Some(short); + self + } + + /// Sets the long version of the subcommand flag without the preceding `--`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::long`]. + /// + /// **NOTE:** Any leading `-` characters will be stripped. + /// + /// # Examples + /// + /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading + /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, + /// will *not* be stripped (i.e. `sync-file` is allowed). + /// + /// ``` + /// # use clap::{Command, Arg, ArgAction}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").long_flag("sync").arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .action(ArgAction::SetTrue) + /// .help("search remote repositories for matching strings"), + /// ), + /// ) + /// .get_matches_from(vec!["pacman", "--sync", "--search"]); + /// + /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); + /// let sync_matches = matches.subcommand_matches("sync").unwrap(); + /// assert!(*sync_matches.get_one::("search").expect("defaulted by clap")); + /// ``` + /// + /// [`Arg::long`]: Arg::long() + #[must_use] + pub fn long_flag(mut self, long: &'help str) -> Self { + #[cfg(feature = "unstable-v4")] + { + self.long_flag = Some(long); + } + #[cfg(not(feature = "unstable-v4"))] + { + self.long_flag = Some(long.trim_start_matches(|c| c == '-')); + } + self + } + + /// Sets a hidden alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name, or this given + /// alias. This is more efficient and easier than creating multiple hidden subcommands as one + /// only needs to check for the existence of this command, and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If you're looking for aliases that will be displayed in the help + /// message, see [`Command::visible_alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_alias`]: Command::visible_alias() + #[must_use] + pub fn alias>(mut self, name: S) -> Self { + self.aliases.push((name.into(), false)); + self + } + + /// Add an alias, which functions as "hidden" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, false)); + self + } + + /// Add an alias, which functions as a "hidden" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_alias(mut self, name: &'help str) -> Self { + self.long_flag_aliases.push((name, false)); + self + } + + /// Sets multiple hidden aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name or any of the + /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands + /// as one only needs to check for the existence of this command and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If looking for aliases that will be displayed in the help + /// message, see [`Command::visible_aliases`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .aliases(&["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_aliases`]: Command::visible_aliases() + #[must_use] + pub fn aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, false))); + self + } + + /// Add aliases, which function as "hidden" short flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_aliases(&['a', 'b', 'c'])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "-a"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((*s, false)); + } + self + } + + /// Add aliases, which function as "hidden" long flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_aliases(&["testing", "testall", "test_all"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self { + for s in names { + self.long_flag_aliases.push((s, false)); + } + self + } + + /// Sets a visible alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or the given alias. This is more efficient and easier + /// than creating hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: Command::alias() + #[must_use] + pub fn visible_alias>(mut self, name: S) -> Self { + self.aliases.push((name.into(), true)); + self + } + + /// Add an alias, which functions as "visible" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::short_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .visible_short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::short_flag_alias`]: Command::short_flag_alias() + #[must_use] + pub fn visible_short_flag_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, true)); + self + } + + /// Add an alias, which functions as a "visible" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::long_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::long_flag_alias`]: Command::long_flag_alias() + #[must_use] + pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self { + self.long_flag_aliases.push((name, true)); + self + } + + /// Sets multiple visible aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or any of the given aliases. This is more efficient and easier + /// than creating multiple hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases, and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_aliases(&["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: Command::alias() + #[must_use] + pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, true))); + self + } + + /// Add aliases, which function as *visible* short flag subcommands. + /// + /// See [`Command::short_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('b') + /// .visible_short_flag_aliases(&['t'])) + /// .get_matches_from(vec!["myprog", "-t"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::short_flag_aliases`]: Command::short_flag_aliases() + #[must_use] + pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((*s, true)); + } + self + } + + /// Add aliases, which function as *visible* long flag subcommands. + /// + /// See [`Command::long_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_aliases(&["testing", "testall", "test_all"])) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::long_flag_aliases`]: Command::long_flag_aliases() + #[must_use] + pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self { + for s in names { + self.long_flag_aliases.push((s, true)); + } + self + } + + /// Set the placement of this subcommand within the help. + /// + /// Subcommands with a lower value will be displayed first in the help message. Subcommands + /// with duplicate display orders will be displayed in alphabetical order. + /// + /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize + /// those towards the top of the list. + /// + /// **NOTE:** The default is 999 for all subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, }; + /// let m = Command::new("cust-ord") + /// .subcommand(Command::new("alpha") // typically subcommands are grouped + /// // alphabetically by name. Subcommands + /// // without a display_order have a value of + /// // 999 and are displayed alphabetically with + /// // all other 999 subcommands + /// .about("Some help and text")) + /// .subcommand(Command::new("beta") + /// .display_order(1) // In order to force this subcommand to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other subcommands with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .about("I should be first!")) + /// .get_matches_from(vec![ + /// "cust-ord", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// beta I should be first! + /// alpha Some help and text + /// ``` + #[inline] + #[must_use] + pub fn display_order(mut self, ord: usize) -> Self { + self.disp_ord = Some(ord); + self + } + + /// Specifies that this [`subcommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand( + /// Command::new("test").hide(true) + /// ) + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Hidden) + } else { + self.unset_setting(AppSettings::Hidden) + } + } + + /// If no [`subcommand`] is present at runtime, error and exit gracefully. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_required(true) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + pub fn subcommand_required(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandRequired) + } else { + self.unset_setting(AppSettings::SubcommandRequired) + } + } + + /// Assume unexpected positional arguments are a [`subcommand`]. + /// + /// Arguments will be stored in the `""` argument in the [`ArgMatches`] + /// + /// **NOTE:** Use this setting with caution, + /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) + /// will **not** cause an error and instead be treated as a potential subcommand. + /// One should check for such cases manually and inform the user appropriately. + /// + /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with + /// `--`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + /// [`ArgMatches`]: crate::ArgMatches + /// [`ErrorKind::UnknownArgument`]: crate::ErrorKind::UnknownArgument + pub fn allow_external_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowExternalSubcommands) + } else { + self.unset_setting(AppSettings::AllowExternalSubcommands) + } + } + + /// Specifies that external subcommands that are invalid UTF-8 should *not* be treated as an error. + /// + /// **NOTE:** Using external subcommand argument values with invalid UTF-8 requires using + /// [`ArgMatches::values_of_os`] or [`ArgMatches::values_of_lossy`] for those particular + /// arguments which may contain invalid UTF-8 values + /// + /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_invalid_utf8_for_external_subcommands(true) + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os() + /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy() + /// [`subcommands`]: crate::Command::subcommand() + pub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } else { + self.unset_setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + } + + /// Specifies that use of an argument prevents the use of [`subcommands`]. + /// + /// By default `clap` allows arguments between subcommands such + /// as ` [cmd_args] [subcmd_args] [subsubcmd_args]`. + /// + /// This setting disables that functionality and says that arguments can + /// only follow the *final* subcommand. For instance using this setting + /// makes only the following invocations possible: + /// + /// * ` [subsubcmd_args]` + /// * ` [subcmd_args]` + /// * ` [cmd_args]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// Command::new("myprog") + /// .args_conflicts_with_subcommands(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgsNegateSubcommands) + } else { + self.unset_setting(AppSettings::ArgsNegateSubcommands) + } + } + + /// Prevent subcommands from being consumed as an arguments value. + /// + /// By default, if an option taking multiple values is followed by a subcommand, the + /// subcommand will be parsed as another value. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values another value + /// ``` + /// + /// This setting instructs the parser to stop when encountering a subcommand instead of + /// greedily consuming arguments. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values subcommand + /// ``` + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( + /// Arg::new("arg") + /// .long("arg") + /// .multiple_values(true) + /// .takes_value(true), + /// ); + /// + /// let matches = cmd + /// .clone() + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.values_of("arg").unwrap().collect::>(), + /// &["1", "2", "3", "sub"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_none()); + /// + /// let matches = cmd + /// .subcommand_precedence_over_arg(true) + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.values_of("arg").unwrap().collect::>(), + /// &["1", "2", "3"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_some()); + /// ``` + pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandPrecedenceOverArg) + } else { + self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) + } + } + + /// Allows [`subcommands`] to override all requirements of the parent command. + /// + /// For example, if you had a subcommand or top level application with a required argument + /// that is only required as long as there is no subcommand present, + /// using this setting would allow you to set those arguments to [`Arg::required(true)`] + /// and yet receive no error so long as the user uses a valid subcommand instead. + /// + /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) + /// + /// # Examples + /// + /// This first example shows that it is an error to not use a required argument + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog" + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// # ; + /// ``` + /// + /// This next example shows that it is no longer error to not use a required argument if a + /// valid subcommand is used. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let noerr = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// + /// [`Arg::required(true)`]: crate::Arg::required() + /// [`subcommands`]: crate::Command::subcommand() + pub fn subcommand_negates_reqs(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandsNegateReqs) + } else { + self.unset_setting(AppSettings::SubcommandsNegateReqs) + } + } + + /// Multiple-personality program dispatched on the binary name (`argv[0]`) + /// + /// A "multicall" executable is a single executable + /// that contains a variety of applets, + /// and decides which applet to run based on the name of the file. + /// The executable can be called from different names by creating hard links + /// or symbolic links to it. + /// + /// This is desirable for: + /// - Easy distribution, a single binary that can install hardlinks to access the different + /// personalities. + /// - Minimal binary size by sharing common code (e.g. standard library, clap) + /// - Custom shells or REPLs where there isn't a single top-level command + /// + /// Setting `multicall` will cause + /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if + /// [`Command::no_binary_name`][App::no_binary_name] was set. + /// - Help and errors to report subcommands as if they were the top-level command + /// + /// When the subcommand is not present, there are several strategies you may employ, depending + /// on your needs: + /// - Let the error percolate up normally + /// - Print a specialized error message using the + /// [`Error::context`][crate::Error::context] + /// - Print the [help][App::write_help] but this might be ambiguous + /// - Disable `multicall` and re-parse it + /// - Disable `multicall` and re-parse it with a specific subcommand + /// + /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand + /// might report the same error. Enable + /// [`allow_external_subcommands`][App::allow_external_subcommands] if you want to specifically + /// get the unrecognized binary name. + /// + /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret + /// the command name in incompatible ways. + /// + /// **NOTE:** The multicall command cannot have arguments. + /// + /// **NOTE:** Applets are slightly semantically different from subcommands, + /// so it's recommended to use [`Command::subcommand_help_heading`] and + /// [`Command::subcommand_value_name`] to change the descriptive text as above. + /// + /// # Examples + /// + /// `hostname` is an example of a multicall executable. + /// Both `hostname` and `dnsdomainname` are provided by the same executable + /// and which behaviour to use is based on the executable file name. + /// + /// This is desirable when the executable has a primary purpose + /// but there is related functionality that would be convenient to provide + /// and implement it to be in the same executable. + /// + /// The name of the cmd is essentially unused + /// and may be the same as the name of a subcommand. + /// + /// The names of the immediate subcommands of the Command + /// are matched against the basename of the first argument, + /// which is conventionally the path of the executable. + /// + /// This does not allow the subcommand to be passed as the first non-path argument. + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let mut cmd = Command::new("hostname") + /// .multicall(true) + /// .subcommand(Command::new("hostname")) + /// .subcommand(Command::new("dnsdomainname")); + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); + /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); + /// ``` + /// + /// Busybox is another common example of a multicall executable + /// with a subcommmand for each applet that can be run directly, + /// e.g. with the `cat` applet being run by running `busybox cat`, + /// or with `cat` as a link to the `busybox` binary. + /// + /// This is desirable when the launcher program has additional options + /// or it is useful to run the applet without installing a symlink + /// e.g. to test the applet without installing it + /// or there may already be a command of that name installed. + /// + /// To make an applet usable as both a multicall link and a subcommand + /// the subcommands must be defined both in the top-level Command + /// and as subcommands of the "main" applet. + /// + /// ```rust + /// # use clap::Command; + /// fn applet_commands() -> [Command<'static>; 2] { + /// [Command::new("true"), Command::new("false")] + /// } + /// let mut cmd = Command::new("busybox") + /// .multicall(true) + /// .subcommand( + /// Command::new("busybox") + /// .subcommand_value_name("APPLET") + /// .subcommand_help_heading("APPLETS") + /// .subcommands(applet_commands()), + /// ) + /// .subcommands(applet_commands()); + /// // When called from the executable's canonical name + /// // its applets can be matched as subcommands. + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); + /// assert_eq!(m.subcommand_name(), Some("busybox")); + /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); + /// // When called from a link named after an applet that applet is matched. + /// let m = cmd.get_matches_from(&["/usr/bin/true"]); + /// assert_eq!(m.subcommand_name(), Some("true")); + /// ``` + /// + /// [`no_binary_name`]: crate::Command::no_binary_name + /// [`App::subcommand_value_name`]: crate::Command::subcommand_value_name + /// [`App::subcommand_help_heading`]: crate::Command::subcommand_help_heading + #[inline] + pub fn multicall(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Multicall) + } else { + self.unset_setting(AppSettings::Multicall) + } + } + + /// Sets the value name used for subcommands when printing usage and help. + /// + /// By default, this is "SUBCOMMAND". + /// + /// See also [`Command::subcommand_help_heading`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + /// + /// but usage of `subcommand_value_name` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_value_name("THING") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [THING] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + #[must_use] + pub fn subcommand_value_name(mut self, value_name: S) -> Self + where + S: Into<&'help str>, + { + self.subcommand_value_name = Some(value_name.into()); + self + } + + /// Sets the help heading used for subcommands when printing usage and help. + /// + /// By default, this is "SUBCOMMANDS". + /// + /// See also [`Command::subcommand_value_name`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + /// + /// but usage of `subcommand_help_heading` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_help_heading("THINGS") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// THINGS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + #[must_use] + pub fn subcommand_help_heading(mut self, heading: T) -> Self + where + T: Into<&'help str>, + { + self.subcommand_heading = Some(heading.into()); + self + } +} + +/// # Reflection +impl<'help> App<'help> { + #[inline] + pub(crate) fn get_usage_name(&self) -> Option<&str> { + self.usage_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_display_name(&self) -> Option<&str> { + self.display_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_bin_name(&self) -> Option<&str> { + self.bin_name.as_deref() + } + + /// Set binary name. Uses `&mut self` instead of `self`. + pub fn set_bin_name>(&mut self, name: S) { + self.bin_name = Some(name.into()); + } + + /// Get the name of the cmd. + #[inline] + pub fn get_name(&self) -> &str { + &self.name + } + + /// Get the version of the cmd. + #[inline] + pub fn get_version(&self) -> Option<&'help str> { + self.version + } + + /// Get the long version of the cmd. + #[inline] + pub fn get_long_version(&self) -> Option<&'help str> { + self.long_version + } + + /// Get the authors of the cmd. + #[inline] + pub fn get_author(&self) -> Option<&'help str> { + self.author + } + + /// Get the short flag of the subcommand. + #[inline] + pub fn get_short_flag(&self) -> Option { + self.short_flag + } + + /// Get the long flag of the subcommand. + #[inline] + pub fn get_long_flag(&self) -> Option<&'help str> { + self.long_flag + } + + /// Get the help message specified via [`Command::about`]. + /// + /// [`App::about`]: Command::about() + #[inline] + pub fn get_about(&self) -> Option<&'help str> { + self.about + } + + /// Get the help message specified via [`Command::long_about`]. + /// + /// [`App::long_about`]: Command::long_about() + #[inline] + pub fn get_long_about(&self) -> Option<&'help str> { + self.long_about + } + + /// Deprecated, replaced with [`Command::get_next_help_heading`] + #[inline] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `App::get_next_help_heading`") + )] + pub fn get_help_heading(&self) -> Option<&'help str> { + self.get_next_help_heading() + } + + /// Get the custom section heading specified via [`Command::help_heading`]. + /// + /// [`App::help_heading`]: Command::help_heading() + #[inline] + pub fn get_next_help_heading(&self) -> Option<&'help str> { + self.current_help_heading + } + + /// Iterate through the *visible* aliases for this subcommand. + #[inline] + pub fn get_visible_aliases(&self) -> impl Iterator + '_ { + self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0) + } + + /// Iterate through the *visible* short aliases for this subcommand. + #[inline] + pub fn get_visible_short_flag_aliases(&self) -> impl Iterator + '_ { + self.short_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0) + } + + /// Iterate through the *visible* long aliases for this subcommand. + #[inline] + pub fn get_visible_long_flag_aliases(&self) -> impl Iterator + '_ { + self.long_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0) + } + + /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> impl Iterator + '_ { + self.aliases.iter().map(|a| a.0) + } + + /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_short_flag_aliases(&self) -> impl Iterator + '_ { + self.short_flag_aliases.iter().map(|a| a.0) + } + + /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_long_flag_aliases(&self) -> impl Iterator + '_ { + self.long_flag_aliases.iter().map(|a| a.0) + } + + /// Check if the given [`AppSettings`] variant is currently set on the `Command`. + /// + /// This checks both [local] and [global settings]. + /// + /// [local]: Command::setting() + /// [global settings]: Command::global_setting() + #[inline] + pub fn is_set(&self, s: AppSettings) -> bool { + self.settings.is_set(s) || self.g_settings.is_set(s) + } + + /// Should we color the output? + #[inline(never)] + pub fn get_color(&self) -> ColorChoice { + debug!("Command::color: Color setting..."); + + if cfg!(feature = "color") { + #[allow(deprecated)] + if self.is_set(AppSettings::ColorNever) { + debug!("Never"); + ColorChoice::Never + } else if self.is_set(AppSettings::ColorAlways) { + debug!("Always"); + ColorChoice::Always + } else { + debug!("Auto"); + ColorChoice::Auto + } + } else { + ColorChoice::Never + } + } + + /// Iterate through the set of subcommands, getting a reference to each. + #[inline] + pub fn get_subcommands(&self) -> impl Iterator> { + self.subcommands.iter() + } + + /// Iterate through the set of subcommands, getting a mutable reference to each. + #[inline] + pub fn get_subcommands_mut(&mut self) -> impl Iterator> { + self.subcommands.iter_mut() + } + + /// Returns `true` if this `Command` has subcommands. + #[inline] + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_subcommand_help_heading(&self) -> Option<&str> { + self.subcommand_heading + } + + /// Deprecated, replaced with [`App::get_subcommand_help_heading`] + #[inline] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `App::get_subcommand_help_heading`" + ) + )] + pub fn get_subommand_help_heading(&self) -> Option<&str> { + self.get_subcommand_help_heading() + } + + /// Returns the subcommand value name. + #[inline] + pub fn get_subcommand_value_name(&self) -> Option<&str> { + self.subcommand_value_name + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_help(&self) -> Option<&str> { + self.before_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_long_help(&self) -> Option<&str> { + self.before_long_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_help(&self) -> Option<&str> { + self.after_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_long_help(&self) -> Option<&str> { + self.after_long_help + } + + /// Find subcommand such that its name or one of aliases equals `name`. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand(&self, name: &T) -> Option<&App<'help>> + where + T: PartialEq + ?Sized, + { + self.get_subcommands().find(|s| s.aliases_to(name)) + } + + /// Find subcommand such that its name or one of aliases equals `name`, returning + /// a mutable reference to the subcommand. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand_mut(&mut self, name: &T) -> Option<&mut App<'help>> + where + T: PartialEq + ?Sized, + { + self.get_subcommands_mut().find(|s| s.aliases_to(name)) + } + + /// Iterate through the set of groups. + #[inline] + pub fn get_groups(&self) -> impl Iterator> { + self.groups.iter() + } + + /// Iterate through the set of arguments. + #[inline] + pub fn get_arguments(&self) -> impl Iterator> { + self.args.args() + } + + /// Iterate through the *positionals* arguments. + #[inline] + pub fn get_positionals(&self) -> impl Iterator> { + self.get_arguments().filter(|a| a.is_positional()) + } + + /// Iterate through the *options*. + pub fn get_opts(&self) -> impl Iterator> { + self.get_arguments() + .filter(|a| a.is_takes_value_set() && !a.is_positional()) + } + + /// Get a list of all arguments the given argument conflicts with. + /// + /// If the provided argument is declared as global, the conflicts will be determined + /// based on the propagation rules of global arguments. + /// + /// ### Panics + /// + /// If the given arg contains a conflict with an argument that is unknown to + /// this `Command`. + pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator + { + if arg.is_global_set() { + self.get_global_arg_conflicts_with(arg) + } else { + let mut result = Vec::new(); + for id in arg.blacklist.iter() { + if let Some(arg) = self.find(id) { + result.push(arg); + } else if let Some(group) = self.find_group(id) { + result.extend( + self.unroll_args_in_group(&group.id) + .iter() + .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), + ); + } else { + panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); + } + } + result + } + } + + // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. + // + // This behavior follows the propagation rules of global arguments. + // It is useful for finding conflicts for arguments declared as global. + // + // ### Panics + // + // If the given arg contains a conflict with an argument that is unknown to + // this `App`. + fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator + { + arg.blacklist + .iter() + .map(|id| { + self.args + .args() + .chain( + self.get_subcommands_containing(arg) + .iter() + .flat_map(|x| x.args.args()), + ) + .find(|arg| arg.id == *id) + .expect( + "Command::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the cmd", + ) + }) + .collect() + } + + // Get a list of subcommands which contain the provided Argument + // + // This command will only include subcommands in its list for which the subcommands + // parent also contains the Argument. + // + // This search follows the propagation rules of global arguments. + // It is useful to finding subcommands, that have inherited a global argument. + // + // **NOTE:** In this case only Sucommand_1 will be included + // Subcommand_1 (contains Arg) + // Subcommand_1.1 (doesn't contain Arg) + // Subcommand_1.1.1 (contains Arg) + // + fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&App<'help>> { + let mut vec = std::vec::Vec::new(); + for idx in 0..self.subcommands.len() { + if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) { + vec.push(&self.subcommands[idx]); + vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); + } + } + vec + } + + /// Report whether [`Command::no_binary_name`] is set + pub fn is_no_binary_name_set(&self) -> bool { + self.is_set(AppSettings::NoBinaryName) + } + + /// Report whether [`Command::ignore_errors`] is set + pub(crate) fn is_ignore_errors_set(&self) -> bool { + self.is_set(AppSettings::IgnoreErrors) + } + + /// Report whether [`Command::dont_delimit_trailing_values`] is set + pub fn is_dont_delimit_trailing_values_set(&self) -> bool { + self.is_set(AppSettings::DontDelimitTrailingValues) + } + + /// Report whether [`Command::disable_version_flag`] is set + pub fn is_disable_version_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableVersionFlag) + } + + /// Report whether [`Command::propagate_version`] is set + pub fn is_propagate_version_set(&self) -> bool { + self.is_set(AppSettings::PropagateVersion) + } + + /// Report whether [`Command::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(AppSettings::NextLineHelp) + } + + /// Report whether [`Command::disable_help_flag`] is set + pub fn is_disable_help_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpFlag) + } + + /// Report whether [`Command::disable_help_subcommand`] is set + pub fn is_disable_help_subcommand_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpSubcommand) + } + + /// Report whether [`Command::disable_colored_help`] is set + pub fn is_disable_colored_help_set(&self) -> bool { + self.is_set(AppSettings::DisableColoredHelp) + } + + /// Report whether [`Command::help_expected`] is set + #[cfg(debug_assertions)] + pub(crate) fn is_help_expected_set(&self) -> bool { + self.is_set(AppSettings::HelpExpected) + } + + /// Report whether [`Command::dont_collapse_args_in_usage`] is set + pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { + self.is_set(AppSettings::DontCollapseArgsInUsage) + } + + /// Report whether [`Command::infer_long_args`] is set + pub(crate) fn is_infer_long_args_set(&self) -> bool { + self.is_set(AppSettings::InferLongArgs) + } + + /// Report whether [`Command::infer_subcommands`] is set + pub(crate) fn is_infer_subcommands_set(&self) -> bool { + self.is_set(AppSettings::InferSubcommands) + } + + /// Report whether [`Command::arg_required_else_help`] is set + pub fn is_arg_required_else_help_set(&self) -> bool { + self.is_set(AppSettings::ArgRequiredElseHelp) + } + + /// Report whether [`Command::allow_hyphen_values`] is set + pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(AppSettings::AllowHyphenValues) + } + + /// Report whether [`Command::allow_negative_numbers`] is set + pub fn is_allow_negative_numbers_set(&self) -> bool { + self.is_set(AppSettings::AllowNegativeNumbers) + } + + /// Report whether [`Command::trailing_var_arg`] is set + pub fn is_trailing_var_arg_set(&self) -> bool { + self.is_set(AppSettings::TrailingVarArg) + } + + /// Report whether [`Command::allow_missing_positional`] is set + pub fn is_allow_missing_positional_set(&self) -> bool { + self.is_set(AppSettings::AllowMissingPositional) + } + + /// Report whether [`Command::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(AppSettings::Hidden) + } + + /// Report whether [`Command::subcommand_required`] is set + pub fn is_subcommand_required_set(&self) -> bool { + self.is_set(AppSettings::SubcommandRequired) + } + + /// Report whether [`Command::allow_external_subcommands`] is set + pub fn is_allow_external_subcommands_set(&self) -> bool { + self.is_set(AppSettings::AllowExternalSubcommands) + } + + /// Report whether [`Command::allow_invalid_utf8_for_external_subcommands`] is set + pub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool { + self.is_set(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + + /// Configured parser for values passed to an external subcommand + /// + /// # Example + /// + /// ```rust + /// let cmd = clap::Command::new("raw") + /// .allow_external_subcommands(true) + /// .allow_invalid_utf8_for_external_subcommands(true); + /// let value_parser = cmd.get_external_subcommand_value_parser(); + /// println!("{:?}", value_parser); + /// ``` + pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { + if !self.is_allow_external_subcommands_set() { + None + } else if self.is_allow_invalid_utf8_for_external_subcommands_set() { + static DEFAULT: super::ValueParser = super::ValueParser::os_string(); + Some(&DEFAULT) + } else { + static DEFAULT: super::ValueParser = super::ValueParser::string(); + Some(&DEFAULT) + } + } + + /// Report whether [`Command::args_conflicts_with_subcommands`] is set + pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { + self.is_set(AppSettings::ArgsNegateSubcommands) + } + + /// Report whether [`Command::subcommand_precedence_over_arg`] is set + pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { + self.is_set(AppSettings::SubcommandPrecedenceOverArg) + } + + /// Report whether [`Command::subcommand_negates_reqs`] is set + pub fn is_subcommand_negates_reqs_set(&self) -> bool { + self.is_set(AppSettings::SubcommandsNegateReqs) + } + + /// Report whether [`Command::multicall`] is set + pub fn is_multicall_set(&self) -> bool { + self.is_set(AppSettings::Multicall) + } +} + +/// Deprecated +impl<'help> App<'help> { + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + ) + )] + #[doc(hidden)] + pub fn from_yaml(y: &'help Yaml) -> Self { + #![allow(deprecated)] + let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); + // We WANT this to panic on error...so expect() is good. + let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() { + (App::new(name), yaml_file_hash, "cmd".into()) + } else { + let (name_yaml, value_yaml) = yaml_file_hash + .iter() + .next() + .expect("There must be one subcommand in the YAML file"); + let name_str = name_yaml + .as_str() + .expect("Subcommand name must be a string"); + + ( + App::new(name_str), + value_yaml.as_hash().expect("Subcommand must be a hash"), + format!("subcommand '{}'", name_str), + ) + }; + + for (k, v) in yaml { + a = match k.as_str().expect("App fields must be strings") { + "version" => yaml_to_str!(a, v, version), + "long_version" => yaml_to_str!(a, v, long_version), + "author" => yaml_to_str!(a, v, author), + "bin_name" => yaml_to_str!(a, v, bin_name), + "about" => yaml_to_str!(a, v, about), + "long_about" => yaml_to_str!(a, v, long_about), + "before_help" => yaml_to_str!(a, v, before_help), + "after_help" => yaml_to_str!(a, v, after_help), + "template" => yaml_to_str!(a, v, help_template), + "usage" => yaml_to_str!(a, v, override_usage), + "help" => yaml_to_str!(a, v, override_help), + "help_message" => yaml_to_str!(a, v, help_message), + "version_message" => yaml_to_str!(a, v, version_message), + "alias" => yaml_to_str!(a, v, alias), + "aliases" => yaml_vec_or_str!(a, v, alias), + "visible_alias" => yaml_to_str!(a, v, visible_alias), + "visible_aliases" => yaml_vec_or_str!(a, v, visible_alias), + "display_order" => yaml_to_usize!(a, v, display_order), + "args" => { + if let Some(vec) = v.as_vec() { + for arg_yaml in vec { + a = a.arg(Arg::from_yaml(arg_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "subcommands" => { + if let Some(vec) = v.as_vec() { + for sc_yaml in vec { + a = a.subcommand(App::from_yaml(sc_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "groups" => { + if let Some(vec) = v.as_vec() { + for ag_yaml in vec { + a = a.group(ArgGroup::from(ag_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "setting" | "settings" => { + yaml_to_setting!(a, v, setting, AppSettings, "AppSetting", err) + } + "global_setting" | "global_settings" => { + yaml_to_setting!(a, v, global_setting, AppSettings, "AppSetting", err) + } + _ => a, + } + } + + a + } + + /// Deprecated, replaced with [`Command::override_usage`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::override_usage`") + )] + #[doc(hidden)] + #[must_use] + pub fn usage>(self, usage: S) -> Self { + self.override_usage(usage) + } + + /// Deprecated, replaced with [`Command::override_help`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::override_help`") + )] + #[doc(hidden)] + #[must_use] + pub fn help>(self, help: S) -> Self { + self.override_help(help) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") + )] + #[doc(hidden)] + #[must_use] + pub fn help_short(self, c: char) -> Self { + self.mut_arg("help", |a| a.short(c)) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") + )] + #[doc(hidden)] + #[must_use] + pub fn version_short(self, c: char) -> Self { + self.mut_arg("version", |a| a.short(c)) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") + )] + #[doc(hidden)] + #[must_use] + pub fn help_message(self, s: impl Into<&'help str>) -> Self { + self.mut_arg("help", |a| a.help(s.into())) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") + )] + #[doc(hidden)] + #[must_use] + pub fn version_message(self, s: impl Into<&'help str>) -> Self { + self.mut_arg("version", |a| a.help(s.into())) + } + + /// Deprecated, replaced with [`Command::help_template`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::help_template`") + )] + #[doc(hidden)] + #[must_use] + pub fn template>(self, s: S) -> Self { + self.help_template(s) + } + + /// Deprecated, replaced with [`Command::setting(a| b)`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::setting(a | b)`") + )] + #[doc(hidden)] + #[must_use] + pub fn settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.insert((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::unset_setting(a| b)`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::unset_setting(a | b)`") + )] + #[doc(hidden)] + #[must_use] + pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.remove((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::global_setting(a| b)`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::global_setting(a | b)`") + )] + #[doc(hidden)] + #[must_use] + pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.insert((*s).into()); + self.g_settings.insert((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::term_width`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::term_width`") + )] + #[doc(hidden)] + #[must_use] + pub fn set_term_width(self, width: usize) -> Self { + self.term_width(width) + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") + )] + #[doc(hidden)] + #[must_use] + pub fn arg_from_usage(self, usage: &'help str) -> Self { + #![allow(deprecated)] + self.arg(Arg::from_usage(usage)) + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") + )] + #[doc(hidden)] + #[must_use] + pub fn args_from_usage(mut self, usage: &'help str) -> Self { + #![allow(deprecated)] + for line in usage.lines() { + let l = line.trim(); + if l.is_empty() { + continue; + } + self = self.arg(Arg::from_usage(l)); + } + self + } + + /// Deprecated, replaced with [`Command::render_version`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::render_version`") + )] + #[doc(hidden)] + pub fn write_version(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`Command::render_long_version`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::render_long_version`") + )] + #[doc(hidden)] + pub fn write_long_version(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_long_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`Command::try_get_matches`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches`") + )] + #[doc(hidden)] + pub fn get_matches_safe(self) -> ClapResult { + self.try_get_matches() + } + + /// Deprecated, replaced with [`Command::try_get_matches_from`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches_from`") + )] + #[doc(hidden)] + pub fn get_matches_from_safe(self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from(itr) + } + + /// Deprecated, replaced with [`Command::try_get_matches_from_mut`] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `App::try_get_matches_from_mut`" + ) + )] + #[doc(hidden)] + pub fn get_matches_from_safe_borrow(&mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from_mut(itr) + } +} + +// Internally used only +impl<'help> App<'help> { + pub(crate) fn get_id(&self) -> Id { + self.id.clone() + } + + pub(crate) fn get_override_usage(&self) -> Option<&str> { + self.usage_str + } + + pub(crate) fn get_override_help(&self) -> Option<&str> { + self.help_str + } + + pub(crate) fn get_help_template(&self) -> Option<&str> { + self.template + } + + pub(crate) fn get_term_width(&self) -> Option { + self.term_w + } + + pub(crate) fn get_max_term_width(&self) -> Option { + self.max_w + } + + pub(crate) fn get_replacement(&self, key: &str) -> Option<&[&str]> { + self.replacers.get(key).copied() + } + + pub(crate) fn get_keymap(&self) -> &MKeyMap<'help> { + &self.args + } + + fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec) { + global_arg_vec.extend( + self.args + .args() + .filter(|a| a.is_global_set()) + .map(|ga| ga.id.clone()), + ); + if let Some((id, matches)) = matches.subcommand() { + if let Some(used_sub) = self.find_subcommand(id) { + used_sub.get_used_global_args(matches, global_arg_vec); + } + } + } + + fn _do_parse( + &mut self, + raw_args: &mut clap_lex::RawArgs, + args_cursor: clap_lex::ArgCursor, + ) -> ClapResult { + debug!("Command::_do_parse"); + + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing in case we run into a subcommand + self._build_self(); + + let mut matcher = ArgMatcher::new(self); + + // do the real parsing + let mut parser = Parser::new(self); + if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { + if self.is_set(AppSettings::IgnoreErrors) { + debug!("Command::_do_parse: ignoring error: {}", error); + } else { + return Err(error); + } + } + + let mut global_arg_vec = Default::default(); + self.get_used_global_args(&matcher, &mut global_arg_vec); + + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into_inner()) + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.10", note = "Replaced with `Command::build`") + )] + pub fn _build_all(&mut self) { + self.build(); + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.10", note = "Replaced with `Command::build`") + )] + pub fn _build(&mut self) { + self._build_self() + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.13", note = "Replaced with `Command::build`") + )] + pub fn _build_bin_names(&mut self) { + self._build_bin_names_internal(); + } + + /// Prepare for introspecting on all included [`Command`]s + /// + /// Call this on the top-level [`Command`] when done building and before reading state for + /// cases like completions, custom help output, etc. + pub fn build(&mut self) { + self._build_recursive(); + self._build_bin_names_internal(); + } + + pub(crate) fn _build_recursive(&mut self) { + self._build_self(); + for subcmd in self.get_subcommands_mut() { + subcmd._build_recursive(); + } + } + + pub(crate) fn _build_self(&mut self) { + debug!("Command::_build: name={:?}", self.get_name()); + if !self.settings.is_set(AppSettings::Built) { + // Make sure all the globally set flags apply to us as well + self.settings = self.settings | self.g_settings; + + if self.is_multicall_set() { + self.settings.insert(AppSettings::SubcommandRequired.into()); + self.settings.insert(AppSettings::DisableHelpFlag.into()); + self.settings.insert(AppSettings::DisableVersionFlag.into()); + } + + self._propagate(); + self._check_help_and_version(); + self._propagate_global_args(); + self._derive_display_order(); + + let mut pos_counter = 1; + let self_override = self.is_set(AppSettings::AllArgsOverrideSelf); + let hide_pv = self.is_set(AppSettings::HidePossibleValues); + let auto_help = + !self.is_set(AppSettings::NoAutoHelp) && !self.is_disable_help_flag_set(); + let auto_version = + !self.is_set(AppSettings::NoAutoVersion) && !self.is_disable_version_flag_set(); + for a in self.args.args_mut() { + // Fill in the groups + for g in &a.groups { + if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { + ag.args.push(a.id.clone()); + } else { + let mut ag = ArgGroup::with_id(g.clone()); + ag.args.push(a.id.clone()); + self.groups.push(ag); + } + } + + // Figure out implied settings + if a.is_last_set() { + // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args + // in the usage string don't get confused or left out. + self.settings.set(AppSettings::DontCollapseArgsInUsage); + } + if hide_pv && a.is_takes_value_set() { + a.settings.set(ArgSettings::HidePossibleValues); + } + if self_override { + let self_id = a.id.clone(); + a.overrides.push(self_id); + } + a._build(); + // HACK: Setting up action at this level while auto-help / disable help flag is + // required. Otherwise, most of this won't be needed because when we can break + // compat, actions will reign supreme (default to `Store`) + if a.action.is_none() { + if a.get_id() == "help" && auto_help && !a.is_takes_value_set() { + let action = super::ArgAction::Help; + a.action = Some(action); + } else if a.get_id() == "version" && auto_version && !a.is_takes_value_set() { + let action = super::ArgAction::Version; + a.action = Some(action); + } else if a.is_takes_value_set() { + let action = super::ArgAction::StoreValue; + a.action = Some(action); + } else { + let action = super::ArgAction::IncOccurrence; + a.action = Some(action); + } + } + if a.is_positional() && a.index.is_none() { + a.index = Some(pos_counter); + pos_counter += 1; + } + } + + self.args._build(); + + #[cfg(debug_assertions)] + assert_app(self); + self.settings.set(AppSettings::Built); + } else { + debug!("Command::_build: already built"); + } + } + + pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { + use std::fmt::Write; + + let mut mid_string = String::from(" "); + if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() + { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(s); + mid_string.push(' '); + } + } + let is_multicall_set = self.is_multicall_set(); + + let sc = self.subcommands.iter_mut().find(|s| s.name == name)?; + + // Display subcommand name, short and long in usage + let mut sc_names = sc.name.clone(); + let mut flag_subcmd = false; + if let Some(l) = sc.long_flag { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.short_flag { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = self + .bin_name + .as_ref() + .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) + .unwrap_or(sc_names); + sc.usage_name = Some(usage_name); + + // bin_name should be parent's bin_name + [] + the sc's name separated by + // a space + let bin_name = format!( + "{}{}{}", + self.bin_name.as_ref().unwrap_or(&String::new()), + if self.bin_name.is_some() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } + + // Ensure all args are built and ready to parse + sc._build_self(); + + Some(sc) + } + + fn _build_bin_names_internal(&mut self) { + debug!("Command::_build_bin_names"); + + if !self.is_set(AppSettings::BinNameBuilt) { + let mut mid_string = String::from(" "); + if !self.is_subcommand_negates_reqs_set() + && !self.is_args_conflicts_with_subcommands_set() + { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(s); + mid_string.push(' '); + } + } + let is_multicall_set = self.is_multicall_set(); + + let self_bin_name = if is_multicall_set { + self.bin_name.as_deref().unwrap_or("") + } else { + self.bin_name.as_deref().unwrap_or(&self.name) + } + .to_owned(); + + for mut sc in &mut self.subcommands { + debug!("Command::_build_bin_names:iter: bin_name set..."); + + if sc.usage_name.is_none() { + use std::fmt::Write; + // Display subcommand name, short and long in usage + let mut sc_names = sc.name.clone(); + let mut flag_subcmd = false; + if let Some(l) = sc.long_flag { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.short_flag { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names); + debug!( + "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", + sc.name, usage_name + ); + sc.usage_name = Some(usage_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", + sc.name, sc.usage_name + ); + } + + if sc.bin_name.is_none() { + let bin_name = format!( + "{}{}{}", + self_bin_name, + if !self_bin_name.is_empty() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", + sc.name, sc.bin_name + ); + } + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", + sc.name, sc.display_name + ); + } + + sc._build_bin_names_internal(); + } + self.set(AppSettings::BinNameBuilt); + } else { + debug!("Command::_build_bin_names: already built"); + } + } + + pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { + if self.is_set(AppSettings::HelpExpected) || help_required_globally { + let args_missing_help: Vec = self + .args + .args() + .filter(|arg| arg.help.is_none() && arg.long_help.is_none()) + .map(|arg| String::from(arg.name)) + .collect(); + + assert!(args_missing_help.is_empty(), + "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", + self.name, + args_missing_help.join(", ") + ); + } + + for sub_app in &self.subcommands { + sub_app._panic_on_missing_help(help_required_globally); + } + } + + #[cfg(debug_assertions)] + pub(crate) fn two_args_of(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)> + where + F: Fn(&Arg) -> bool, + { + two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) + } + + // just in case + #[allow(unused)] + fn two_groups_of(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> + where + F: Fn(&ArgGroup) -> bool, + { + two_elements_of(self.groups.iter().filter(|a| condition(a))) + } + + /// Propagate global args + pub(crate) fn _propagate_global_args(&mut self) { + debug!("Command::_propagate_global_args:{}", self.name); + + for sc in &mut self.subcommands { + for a in self.args.args().filter(|a| a.is_global_set()) { + let mut propagate = false; + let is_generated = matches!( + a.provider, + ArgProvider::Generated | ArgProvider::GeneratedMutated + ); + + // Remove generated help and version args in the subcommand + // + // Don't remove if those args are further mutated + if is_generated { + let generated_pos = sc + .args + .args() + .position(|x| x.id == a.id && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_pos { + debug!( + "Command::_propagate removing {}'s {:?}", + sc.get_name(), + a.id + ); + sc.args.remove(index); + propagate = true; + } + } + + if propagate || sc.find(&a.id).is_none() { + debug!( + "Command::_propagate pushing {:?} to {}", + a.id, + sc.get_name(), + ); + sc.args.push(a.clone()); + } + } + } + } + + /// Propagate settings + pub(crate) fn _propagate(&mut self) { + debug!("Command::_propagate:{}", self.name); + let mut subcommands = std::mem::take(&mut self.subcommands); + for sc in &mut subcommands { + self._propagate_subcommand(sc); + } + self.subcommands = subcommands; + } + + fn _propagate_subcommand(&self, sc: &mut Self) { + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + if self.settings.is_set(AppSettings::PropagateVersion) { + if sc.version.is_none() && self.version.is_some() { + sc.version = Some(self.version.unwrap()); + } + if sc.long_version.is_none() && self.long_version.is_some() { + sc.long_version = Some(self.long_version.unwrap()); + } + } + + sc.settings = sc.settings | self.g_settings; + sc.g_settings = sc.g_settings | self.g_settings; + sc.term_w = self.term_w; + sc.max_w = self.max_w; + } + } + + #[allow(clippy::blocks_in_if_conditions)] + pub(crate) fn _check_help_and_version(&mut self) { + debug!("Command::_check_help_and_version: {}", self.name); + + if self.is_set(AppSettings::DisableHelpFlag) + || self.args.args().any(|x| { + x.provider == ArgProvider::User + && (x.long == Some("help") || x.id == Id::help_hash()) + }) + || self + .subcommands + .iter() + .any(|sc| sc.long_flag == Some("help")) + { + debug!("Command::_check_help_and_version: Removing generated help"); + + let generated_help_pos = self + .args + .args() + .position(|x| x.id == Id::help_hash() && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_help_pos { + self.args.remove(index); + } + } else { + let help = self + .args + .args() + .find(|x| x.id == Id::help_hash()) + .expect(INTERNAL_ERROR_MSG); + assert_ne!(help.provider, ArgProvider::User); + + if help.short.is_some() { + if help.short == Some('h') { + if let Some(other_arg) = self + .args + .args() + .find(|x| x.id != Id::help_hash() && x.short == Some('h')) + { + panic!( + "`help`s `-h` conflicts with `{}`. + +To change `help`s short, call `cmd.arg(Arg::new(\"help\")...)`.", + other_arg.name + ); + } + } + } else if !(self.args.args().any(|x| x.short == Some('h')) + || self.subcommands.iter().any(|sc| sc.short_flag == Some('h'))) + { + let help = self + .args + .args_mut() + .find(|x| x.id == Id::help_hash()) + .expect(INTERNAL_ERROR_MSG); + help.short = Some('h'); + } else { + debug!("Command::_check_help_and_version: Removing `-h` from help"); + } + } + + // Determine if we should remove the generated --version flag + // + // Note that if only mut_arg() was used, the first expression will evaluate to `true` + // however inside the condition block, we only check for Generated args, not + // GeneratedMutated args, so the `mut_arg("version", ..) will be skipped and fall through + // to the following condition below (Adding the short `-V`) + if self.settings.is_set(AppSettings::DisableVersionFlag) + || (self.version.is_none() && self.long_version.is_none()) + || self.args.args().any(|x| { + x.provider == ArgProvider::User + && (x.long == Some("version") || x.id == Id::version_hash()) + }) + || self + .subcommands + .iter() + .any(|sc| sc.long_flag == Some("version")) + { + debug!("Command::_check_help_and_version: Removing generated version"); + + // This is the check mentioned above that only checks for Generated, not + // GeneratedMutated args by design. + let generated_version_pos = self + .args + .args() + .position(|x| x.id == Id::version_hash() && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_version_pos { + self.args.remove(index); + } + } + + // If we still have a generated --version flag, determine if we can apply the short `-V` + if self.args.args().any(|x| { + x.id == Id::version_hash() + && matches!( + x.provider, + ArgProvider::Generated | ArgProvider::GeneratedMutated + ) + }) { + let other_arg_has_short = self.args.args().any(|x| x.short == Some('V')); + let version = self + .args + .args_mut() + .find(|x| x.id == Id::version_hash()) + .expect(INTERNAL_ERROR_MSG); + + if !(version.short.is_some() + || other_arg_has_short + || self.subcommands.iter().any(|sc| sc.short_flag == Some('V'))) + { + version.short = Some('V'); + } + } + + if !self.is_set(AppSettings::DisableHelpSubcommand) + && self.has_subcommands() + && !self.subcommands.iter().any(|s| s.id == Id::help_hash()) + { + debug!("Command::_check_help_and_version: Building help subcommand"); + let mut help_subcmd = App::new("help") + .about("Print this message or the help of the given subcommand(s)") + .arg( + Arg::new("subcommand") + .index(1) + .takes_value(true) + .multiple_occurrences(true) + .value_name("SUBCOMMAND") + .help("The subcommand whose help message to display"), + ); + self._propagate_subcommand(&mut help_subcmd); + + // The parser acts like this is set, so let's set it so we don't falsely + // advertise it to the user + help_subcmd.version = None; + help_subcmd.long_version = None; + help_subcmd = help_subcmd + .setting(AppSettings::DisableHelpFlag) + .unset_global_setting(AppSettings::PropagateVersion); + + self.subcommands.push(help_subcmd); + } + } + + pub(crate) fn _derive_display_order(&mut self) { + debug!("Command::_derive_display_order:{}", self.name); + + if self.settings.is_set(AppSettings::DeriveDisplayOrder) { + for a in self + .args + .args_mut() + .filter(|a| !a.is_positional()) + .filter(|a| a.provider != ArgProvider::Generated) + { + a.disp_ord.make_explicit(); + } + for (i, sc) in &mut self.subcommands.iter_mut().enumerate() { + sc.disp_ord.get_or_insert(i); + } + } + for sc in &mut self.subcommands { + sc._derive_display_order(); + } + } + + pub(crate) fn _render_version(&self, use_long: bool) -> String { + debug!("Command::_render_version"); + + let ver = if use_long { + self.long_version.or(self.version).unwrap_or("") + } else { + self.version.or(self.long_version).unwrap_or("") + }; + if let Some(bn) = self.bin_name.as_ref() { + if bn.contains(' ') { + // In case we're dealing with subcommands i.e. git mv is translated to git-mv + format!("{} {}\n", bn.replace(' ', "-"), ver) + } else { + format!("{} {}\n", &self.name[..], ver) + } + } else { + format!("{} {}\n", &self.name[..], ver) + } + } + + pub(crate) fn format_group(&self, g: &Id) -> String { + let g_string = self + .unroll_args_in_group(g) + .iter() + .filter_map(|x| self.find(x)) + .map(|x| { + if x.is_positional() { + // Print val_name for positional arguments. e.g. + x.name_no_brackets().to_string() + } else { + // Print usage string for flags arguments, e.g. <--help> + x.to_string() + } + }) + .collect::>() + .join("|"); + format!("<{}>", &*g_string) + } +} + +/// A workaround: +/// +pub(crate) trait Captures<'a> {} +impl<'a, T> Captures<'a> for T {} + +// Internal Query Methods +impl<'help> App<'help> { + /// Iterate through the *flags* & *options* arguments. + pub(crate) fn get_non_positionals(&self) -> impl Iterator> { + self.get_arguments().filter(|a| !a.is_positional()) + } + + /// Iterate through the *positionals* that don't have custom heading. + pub(crate) fn get_positionals_with_no_heading(&self) -> impl Iterator> { + self.get_positionals() + .filter(|a| a.get_help_heading().is_none()) + } + + /// Iterate through the *flags* & *options* that don't have custom heading. + pub(crate) fn get_non_positionals_with_no_heading(&self) -> impl Iterator> { + self.get_non_positionals() + .filter(|a| a.get_help_heading().is_none()) + } + + pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> { + self.args.args().find(|a| a.id == *arg_id) + } + + #[inline] + pub(crate) fn contains_short(&self, s: char) -> bool { + assert!( + self.is_set(AppSettings::Built), + "If App::_build hasn't been called, manually search through Arg shorts" + ); + + self.args.contains(s) + } + + #[inline] + pub(crate) fn set(&mut self, s: AppSettings) { + self.settings.set(s) + } + + #[inline] + pub(crate) fn has_args(&self) -> bool { + !self.args.is_empty() + } + + pub(crate) fn has_positionals(&self) -> bool { + self.args.keys().any(|x| x.is_position()) + } + + pub(crate) fn has_visible_subcommands(&self) -> bool { + self.subcommands + .iter() + .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this subcommand or is one of its aliases. + #[inline] + pub(crate) fn aliases_to(&self, name: &T) -> bool + where + T: PartialEq + ?Sized, + { + *name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. + #[inline] + pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { + Some(flag) == self.short_flag + || self.get_all_short_flag_aliases().any(|alias| flag == alias) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. + #[inline] + pub(crate) fn long_flag_aliases_to(&self, flag: &T) -> bool + where + T: PartialEq + ?Sized, + { + match self.long_flag { + Some(long_flag) => { + flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias) + } + None => self.get_all_long_flag_aliases().any(|alias| flag == alias), + } + } + + #[cfg(debug_assertions)] + pub(crate) fn id_exists(&self, id: &Id) -> bool { + self.args.args().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id) + } + + /// Iterate through the groups this arg is member of. + pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator + 'a { + debug!("Command::groups_for_arg: id={:?}", arg); + let arg = arg.clone(); + self.groups + .iter() + .filter(move |grp| grp.args.iter().any(|a| a == &arg)) + .map(|grp| grp.id.clone()) + } + + pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup<'help>> { + self.groups.iter().find(|g| g.id == *group_id) + } + + /// Iterate through all the names of all subcommands (not recursively), including aliases. + /// Used for suggestions. + pub(crate) fn all_subcommand_names(&self) -> impl Iterator + Captures<'help> { + self.get_subcommands().flat_map(|sc| { + let name = sc.get_name(); + let aliases = sc.get_all_aliases(); + std::iter::once(name).chain(aliases) + }) + } + + pub(crate) fn required_graph(&self) -> ChildGraph { + let mut reqs = ChildGraph::with_capacity(5); + for a in self.args.args().filter(|a| a.is_required_set()) { + reqs.insert(a.id.clone()); + } + for group in &self.groups { + if group.required { + let idx = reqs.insert(group.id.clone()); + for a in &group.requires { + reqs.insert_child(idx, a.clone()); + } + } + } + + reqs + } + + pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec { + debug!("Command::unroll_args_in_group: group={:?}", group); + let mut g_vec = vec![group]; + let mut args = vec![]; + + while let Some(g) = g_vec.pop() { + for n in self + .groups + .iter() + .find(|grp| grp.id == *g) + .expect(INTERNAL_ERROR_MSG) + .args + .iter() + { + debug!("Command::unroll_args_in_group:iter: entity={:?}", n); + if !args.contains(n) { + if self.find(n).is_some() { + debug!("Command::unroll_args_in_group:iter: this is an arg"); + args.push(n.clone()) + } else { + debug!("Command::unroll_args_in_group:iter: this is a group"); + g_vec.push(n); + } + } + } + } + + args + } + + pub(crate) fn unroll_arg_requires(&self, func: F, arg: &Id) -> Vec + where + F: Fn(&(ArgPredicate<'_>, Id)) -> Option, + { + let mut processed = vec![]; + let mut r_vec = vec![arg]; + let mut args = vec![]; + + while let Some(a) = r_vec.pop() { + if processed.contains(&a) { + continue; + } + + processed.push(a); + + if let Some(arg) = self.find(a) { + for r in arg.requires.iter().filter_map(&func) { + if let Some(req) = self.find(&r) { + if !req.requires.is_empty() { + r_vec.push(&req.id) + } + } + args.push(r); + } + } + } + + args + } + + /// Find a flag subcommand name by short flag or an alias + pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.short_flag_aliases_to(c)) + .map(|sc| sc.get_name()) + } + + /// Find a flag subcommand name by long flag or an alias + pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.long_flag_aliases_to(long)) + .map(|sc| sc.get_name()) + } + + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.unwrap_or(999) + } + + pub(crate) fn write_help_err( + &self, + mut use_long: bool, + stream: Stream, + ) -> ClapResult { + debug!( + "Parser::write_help_err: use_long={:?}, stream={:?}", + use_long && self.use_long_help(), + stream + ); + + use_long = use_long && self.use_long_help(); + let usage = Usage::new(self); + + let mut c = Colorizer::new(stream, self.color_help()); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, use_long).write_help()?; + Ok(c) + } + + pub(crate) fn use_long_help(&self) -> bool { + debug!("Command::use_long_help"); + // In this case, both must be checked. This allows the retention of + // original formatting, but also ensures that the actual -h or --help + // specified by the user is sent through. If hide_short_help is not included, + // then items specified with hidden_short_help will also be hidden. + let should_long = |v: &Arg| { + v.long_help.is_some() + || v.is_hide_long_help_set() + || v.is_hide_short_help_set() + || cfg!(feature = "unstable-v4") + && v.get_possible_values2() + .iter() + .any(PossibleValue::should_show_help) + }; + + // Subcommands aren't checked because we prefer short help for them, deferring to + // `cmd subcmd --help` for more. + self.get_long_about().is_some() + || self.get_before_long_help().is_some() + || self.get_after_long_help().is_some() + || self.get_arguments().any(should_long) + } + + // Should we color the help? + pub(crate) fn color_help(&self) -> ColorChoice { + #[cfg(feature = "color")] + if self.is_disable_colored_help_set() { + return ColorChoice::Never; + } + + self.get_color() + } +} + +impl<'help> Default for App<'help> { + fn default() -> Self { + Self { + id: Default::default(), + name: Default::default(), + long_flag: Default::default(), + short_flag: Default::default(), + display_name: Default::default(), + bin_name: Default::default(), + author: Default::default(), + version: Default::default(), + long_version: Default::default(), + about: Default::default(), + long_about: Default::default(), + before_help: Default::default(), + before_long_help: Default::default(), + after_help: Default::default(), + after_long_help: Default::default(), + aliases: Default::default(), + short_flag_aliases: Default::default(), + long_flag_aliases: Default::default(), + usage_str: Default::default(), + usage_name: Default::default(), + help_str: Default::default(), + disp_ord: Default::default(), + term_w: Default::default(), + max_w: Default::default(), + template: Default::default(), + settings: Default::default(), + g_settings: Default::default(), + args: Default::default(), + subcommands: Default::default(), + replacers: Default::default(), + groups: Default::default(), + current_help_heading: Default::default(), + current_disp_ord: Some(0), + subcommand_value_name: Default::default(), + subcommand_heading: Default::default(), + } + } +} + +impl<'help> Index<&'_ Id> for App<'help> { + type Output = Arg<'help>; + + fn index(&self, key: &Id) -> &Self::Output { + self.find(key).expect(INTERNAL_ERROR_MSG) + } +} + +impl fmt::Display for App<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) + } +} + +fn two_elements_of(mut iter: I) -> Option<(T, T)> +where + I: Iterator, +{ + let first = iter.next(); + let second = iter.next(); + + match (first, second) { + (Some(first), Some(second)) => Some((first, second)), + _ => None, + } +} + +#[test] +fn check_auto_traits() { + static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); +} diff --git a/vendor/clap-3.2.20/src/builder/debug_asserts.rs b/vendor/clap-3.2.20/src/builder/debug_asserts.rs new file mode 100644 index 000000000..864b8b479 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/debug_asserts.rs @@ -0,0 +1,851 @@ +use std::cmp::Ordering; + +use clap_lex::RawOsStr; + +use crate::builder::arg::ArgProvider; +use crate::mkeymap::KeyType; +use crate::ArgAction; +use crate::{Arg, Command, ValueHint}; + +pub(crate) fn assert_app(cmd: &Command) { + debug!("Command::_debug_asserts"); + + let mut short_flags = vec![]; + let mut long_flags = vec![]; + + // Invalid version flag settings + if cmd.get_version().is_none() && cmd.get_long_version().is_none() { + // PropagateVersion is meaningless if there is no version + assert!( + !cmd.is_propagate_version_set(), + "Command {}: No version information via Command::version or Command::long_version to propagate", + cmd.get_name(), + ); + + // Used `Command::mut_arg("version", ..) but did not provide any version information to display + let version_needed = cmd + .get_arguments() + .filter(|x| { + let action_set = matches!(x.get_action(), ArgAction::Version); + #[cfg(not(feature = "unstable-v4"))] + let provider_set = matches!(x.provider, ArgProvider::GeneratedMutated); + #[cfg(feature = "unstable-v4")] + let provider_set = matches!( + x.provider, + ArgProvider::User | ArgProvider::GeneratedMutated + ); + action_set && provider_set + }) + .map(|x| x.get_id()) + .collect::>(); + + assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" + ,cmd.get_name() + ); + } + + for sc in cmd.get_subcommands() { + if let Some(s) = sc.get_short_flag().as_ref() { + short_flags.push(Flag::Command(format!("-{}", s), sc.get_name())); + } + + for short_alias in sc.get_all_short_flag_aliases() { + short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name())); + } + + if let Some(l) = sc.get_long_flag().as_ref() { + #[cfg(feature = "unstable-v4")] + { + assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); + } + long_flags.push(Flag::Command(format!("--{}", l), sc.get_name())); + } + + for long_alias in sc.get_all_long_flag_aliases() { + long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name())); + } + } + + for arg in cmd.get_arguments() { + assert_arg(arg); + + assert!( + !cmd.is_multicall_set(), + "Command {}: Arguments like {} cannot be set on a multicall command", + cmd.get_name(), + arg.name + ); + + if let Some(s) = arg.short.as_ref() { + short_flags.push(Flag::Arg(format!("-{}", s), &*arg.name)); + } + + for (short_alias, _) in &arg.short_aliases { + short_flags.push(Flag::Arg(format!("-{}", short_alias), arg.name)); + } + + if let Some(l) = arg.long.as_ref() { + #[cfg(feature = "unstable-v4")] + { + assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.name, l); + } + long_flags.push(Flag::Arg(format!("--{}", l), &*arg.name)); + } + + for (long_alias, _) in &arg.aliases { + long_flags.push(Flag::Arg(format!("--{}", long_alias), arg.name)); + } + + // Name conflicts + assert!( + cmd.two_args_of(|x| x.id == arg.id).is_none(), + "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group", + cmd.get_name(), + arg.name, + ); + + // Long conflicts + if let Some(l) = arg.long { + if let Some((first, second)) = cmd.two_args_of(|x| x.long == Some(l)) { + panic!( + "Command {}: Long option names must be unique for each argument, \ + but '--{}' is in use by both '{}' and '{}'", + cmd.get_name(), + l, + first.name, + second.name + ) + } + } + + // Short conflicts + if let Some(s) = arg.short { + if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) { + panic!( + "Command {}: Short option names must be unique for each argument, \ + but '-{}' is in use by both '{}' and '{}'", + cmd.get_name(), + s, + first.name, + second.name + ) + } + } + + // Index conflicts + if let Some(idx) = arg.index { + if let Some((first, second)) = + cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx)) + { + panic!( + "Command {}: Argument '{}' has the same index as '{}' \ + and they are both positional arguments\n\n\t \ + Use Arg::multiple_values(true) to allow one \ + positional argument to take multiple values", + cmd.get_name(), + first.name, + second.name + ) + } + } + + // requires, r_if, r_unless + for req in &arg.requires { + assert!( + cmd.id_exists(&req.1), + "Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist", + cmd.get_name(), + req.1, + arg.name, + ); + } + + for req in &arg.r_ifs { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq*`", + arg.name + ); + } + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_ifs_all { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq_all`", + arg.name + ); + } + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_unless { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.name + ); + } + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + for req in &arg.r_unless_all { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.name + ); + } + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + // blacklist + for req in &arg.blacklist { + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + if arg.is_last_set() { + assert!( + arg.long.is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", + cmd.get_name(), + arg.name + ); + assert!( + arg.short.is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", + cmd.get_name(), + arg.name + ); + } + + assert!( + !(arg.is_required_set() && arg.is_global_set()), + "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", + cmd.get_name(), + arg.name + ); + + // validators + assert!( + arg.validator.is_none() || arg.validator_os.is_none(), + "Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed", + cmd.get_name(), + arg.name + ); + + if arg.get_value_hint() == ValueHint::CommandWithArguments { + assert!( + arg.is_positional(), + "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", + cmd.get_name(), + arg.name + ); + + assert!( + cmd.is_trailing_var_arg_set(), + "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.", + cmd.get_name(), + arg.name + ); + } + } + + for group in cmd.get_groups() { + // Name conflicts + assert!( + cmd.get_groups().filter(|x| x.id == group.id).count() < 2, + "Command {}: Argument group name must be unique\n\n\t'{}' is already in use", + cmd.get_name(), + group.name, + ); + + // Groups should not have naming conflicts with Args + assert!( + !cmd.get_arguments().any(|x| x.id == group.id), + "Command {}: Argument group name '{}' must not conflict with argument name", + cmd.get_name(), + group.name, + ); + + for arg in &group.args { + // Args listed inside groups should exist + assert!( + cmd.get_arguments().any(|x| x.id == *arg), + "Command {}: Argument group '{}' contains non-existent argument '{:?}'", + cmd.get_name(), + group.name, + arg + ); + } + } + + // Conflicts between flags and subcommands + + long_flags.sort_unstable(); + short_flags.sort_unstable(); + + detect_duplicate_flags(&long_flags, "long"); + detect_duplicate_flags(&short_flags, "short"); + + _verify_positionals(cmd); + + if let Some(help_template) = cmd.get_help_template() { + assert!( + !help_template.contains("{flags}"), + "Command {}: {}", + cmd.get_name(), + "`{flags}` template variable was removed in clap3, they are now included in `{options}`", + ); + assert!( + !help_template.contains("{unified}"), + "Command {}: {}", + cmd.get_name(), + "`{unified}` template variable was removed in clap3, use `{options}` instead" + ); + } + + cmd._panic_on_missing_help(cmd.is_help_expected_set()); + assert_app_flags(cmd); +} + +#[derive(Eq)] +enum Flag<'a> { + Command(String, &'a str), + Arg(String, &'a str), +} + +impl PartialEq for Flag<'_> { + fn eq(&self, other: &Flag) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl PartialOrd for Flag<'_> { + fn partial_cmp(&self, other: &Flag) -> Option { + use Flag::*; + + match (self, other) { + (Command(s1, _), Command(s2, _)) + | (Arg(s1, _), Arg(s2, _)) + | (Command(s1, _), Arg(s2, _)) + | (Arg(s1, _), Command(s2, _)) => { + if s1 == s2 { + Some(Ordering::Equal) + } else { + s1.partial_cmp(s2) + } + } + } + } +} + +impl Ord for Flag<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.partial_cmp(other).unwrap() + } +} + +fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { + use Flag::*; + + for (one, two) in find_duplicates(flags) { + match (one, two) { + (Command(flag, one), Command(_, another)) if one != another => panic!( + "the '{}' {} flag is specified for both '{}' and '{}' subcommands", + flag, short_or_long, one, another + ), + + (Arg(flag, one), Arg(_, another)) if one != another => panic!( + "{} option names must be unique, but '{}' is in use by both '{}' and '{}'", + short_or_long, flag, one, another + ), + + (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( + "the '{}' {} flag for the '{}' argument conflicts with the short flag \ + for '{}' subcommand", + flag, short_or_long, arg, sub + ), + + _ => {} + } + } +} + +/// Find duplicates in a sorted array. +/// +/// The algorithm is simple: the array is sorted, duplicates +/// must be placed next to each other, we can check only adjacent elements. +fn find_duplicates(slice: &[T]) -> impl Iterator { + slice.windows(2).filter_map(|w| { + if w[0] == w[1] { + Some((&w[0], &w[1])) + } else { + None + } + }) +} + +fn assert_app_flags(cmd: &Command) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if !cmd.$b() { + s.push_str(&format!(" AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("{}", s) + } + } + }; + ($a:ident conflicts $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if cmd.$b() { + s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("{}\n{}", cmd.get_name(), s) + } + } + }; + } + + checker!(is_allow_invalid_utf8_for_external_subcommands_set requires is_allow_external_subcommands_set); + checker!(is_multicall_set conflicts is_no_binary_name_set); +} + +#[cfg(debug_assertions)] +fn _verify_positionals(cmd: &Command) -> bool { + debug!("Command::_verify_positionals"); + // Because you must wait until all arguments have been supplied, this is the first chance + // to make assertions on positional argument indexes + // + // First we verify that the index highest supplied index, is equal to the number of + // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 + // but no 2) + + let highest_idx = cmd + .get_keymap() + .keys() + .filter_map(|x| { + if let KeyType::Position(n) = x { + Some(*n) + } else { + None + } + }) + .max() + .unwrap_or(0); + + let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); + + assert!( + highest_idx == num_p, + "Found positional argument whose index is {} but there \ + are only {} positional arguments defined", + highest_idx, + num_p + ); + + // Next we verify that only the highest index has takes multiple arguments (if any) + let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx); + if cmd.get_positionals().any(only_highest) { + // First we make sure if there is a positional that allows multiple values + // the one before it (second to last) has one of these: + // * a value terminator + // * ArgSettings::Last + // * The last arg is Required + + // We can't pass the closure (it.next()) to the macro directly because each call to + // find() (iterator, not macro) gets called repeatedly. + let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; + let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; + + // Either the final positional is required + // Or the second to last has a terminator or .last(true) set + let ok = last.is_required_set() + || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) + || last.is_last_set(); + assert!( + ok, + "When using a positional argument with .multiple_values(true) that is *not the \ + last* positional argument, the last positional argument (i.e. the one \ + with the highest index) *must* have .required(true) or .last(true) set." + ); + + // We make sure if the second to last is Multiple the last is ArgSettings::Last + let ok = second_to_last.is_multiple() || last.is_last_set(); + assert!( + ok, + "Only the last positional argument, or second to last positional \ + argument may be set to .multiple_values(true)" + ); + + // Next we check how many have both Multiple and not a specific number of values set + let count = cmd + .get_positionals() + .filter(|p| { + #[allow(deprecated)] + { + p.is_multiple_occurrences_set() + || (p.is_multiple_values_set() && p.num_vals.is_none()) + } + }) + .count(); + let ok = count <= 1 + || (last.is_last_set() + && last.is_multiple() + && second_to_last.is_multiple() + && count == 2); + assert!( + ok, + "Only one positional argument with .multiple_values(true) set is allowed per \ + command, unless the second one also has .last(true) set" + ); + } + + let mut found = false; + + if cmd.is_allow_missing_positional_set() { + // Check that if a required positional argument is found, all positions with a lower + // index are also required. + let mut foundx2 = false; + + for p in cmd.get_positionals() { + if foundx2 && !p.is_required_set() { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument by two or more: {:?} \ + index {:?}", + p.name, + p.index + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + if found { + foundx2 = true; + continue; + } + found = true; + continue; + } else { + found = false; + } + } + } else { + // Check that if a required positional argument is found, all positions with a lower + // index are also required + for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { + if found { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument: {:?} index {:?}", + p.name, + p.index + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + found = true; + continue; + } + } + } + assert!( + cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, + "Only one positional argument may have last(true) set. Found two." + ); + if cmd + .get_positionals() + .any(|p| p.is_last_set() && p.is_required_set()) + && cmd.has_subcommands() + && !cmd.is_subcommand_negates_reqs_set() + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true +} + +fn assert_arg(arg: &Arg) { + debug!("Arg::_debug_asserts:{}", arg.name); + + // Self conflict + // TODO: this check should be recursive + assert!( + !arg.blacklist.iter().any(|x| *x == arg.id), + "Argument '{}' cannot conflict with itself", + arg.name, + ); + + assert_eq!( + arg.get_action().takes_values(), + arg.is_takes_value_set(), + "Argument `{}`'s selected action {:?} contradicts `takes_value`", + arg.name, + arg.get_action() + ); + if let Some(action_type_id) = arg.get_action().value_type_id() { + assert_eq!( + action_type_id, + arg.get_value_parser().type_id(), + "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", + arg.name, + arg.get_action(), + arg.get_value_parser() + ); + } + + if arg.get_value_hint() != ValueHint::Unknown { + assert!( + arg.is_takes_value_set(), + "Argument '{}' has value hint but takes no value", + arg.name + ); + + if arg.get_value_hint() == ValueHint::CommandWithArguments { + assert!( + arg.is_multiple_values_set(), + "Argument '{}' uses hint CommandWithArguments and must accept multiple values", + arg.name + ) + } + } + + if arg.index.is_some() { + assert!( + arg.is_positional(), + "Argument '{}' is a positional argument and can't have short or long name versions", + arg.name + ); + assert!( + arg.is_takes_value_set(), + "Argument '{}` is positional, it must take a value", + arg.name + ); + } + + #[cfg(feature = "unstable-v4")] + { + let num_vals = arg.get_num_vals().unwrap_or(usize::MAX); + let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); + if num_vals < num_val_names { + panic!( + "Argument {}: Too many value names ({}) compared to number_of_values ({})", + arg.name, num_val_names, num_vals + ); + } + } + + assert_arg_flags(arg); + + assert_defaults(arg, "default_value", arg.default_vals.iter().copied()); + assert_defaults( + arg, + "default_missing_value", + arg.default_missing_vals.iter().copied(), + ); + assert_defaults( + arg, + "default_value_if", + arg.default_vals_ifs + .iter() + .filter_map(|(_, _, default)| *default), + ); +} + +fn assert_arg_flags(arg: &Arg) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if arg.$a() { + let mut s = String::new(); + + $( + if !arg.$b() { + s.push_str(&format!(" Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("Argument {:?}\n{}", arg.get_id(), s) + } + } + } + } + + checker!(is_require_value_delimiter_set requires is_takes_value_set); + checker!(is_require_value_delimiter_set requires is_use_value_delimiter_set); + checker!(is_hide_possible_values_set requires is_takes_value_set); + checker!(is_allow_hyphen_values_set requires is_takes_value_set); + checker!(is_require_equals_set requires is_takes_value_set); + checker!(is_last_set requires is_takes_value_set); + checker!(is_hide_default_value_set requires is_takes_value_set); + checker!(is_multiple_values_set requires is_takes_value_set); + checker!(is_ignore_case_set requires is_takes_value_set); + { + #![allow(deprecated)] + checker!(is_forbid_empty_values_set requires is_takes_value_set); + checker!(is_allow_invalid_utf8_set requires is_takes_value_set); + } +} + +fn assert_defaults<'d>( + arg: &Arg, + field: &'static str, + defaults: impl IntoIterator, +) { + for default_os in defaults { + if let Some(default_s) = default_os.to_str() { + if !arg.possible_vals.is_empty() { + if let Some(delim) = arg.get_value_delimiter() { + for part in default_s.split(delim) { + assert!( + arg.possible_vals.iter().any(|possible_val| { + possible_val.matches(part, arg.is_ignore_case_set()) + }), + "Argument `{}`'s {}={} doesn't match possible values", + arg.name, + field, + part + ) + } + } else { + assert!( + arg.possible_vals.iter().any(|possible_val| { + possible_val.matches(default_s, arg.is_ignore_case_set()) + }), + "Argument `{}`'s {}={} doesn't match possible values", + arg.name, + field, + default_s + ); + } + } + + if let Some(validator) = arg.validator.as_ref() { + let mut validator = validator.lock().unwrap(); + if let Some(delim) = arg.get_value_delimiter() { + for part in default_s.split(delim) { + if let Err(err) = validator(part) { + panic!( + "Argument `{}`'s {}={} failed validation: {}", + arg.name, field, part, err + ); + } + } + } else if let Err(err) = validator(default_s) { + panic!( + "Argument `{}`'s {}={} failed validation: {}", + arg.name, field, default_s, err + ); + } + } + } + + if let Some(validator) = arg.validator_os.as_ref() { + let mut validator = validator.lock().unwrap(); + if let Some(delim) = arg.get_value_delimiter() { + let default_os = RawOsStr::new(default_os); + for part in default_os.split(delim) { + if let Err(err) = validator(&part.to_os_str()) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, field, part, err + ); + } + } + } else if let Err(err) = validator(default_os) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, field, default_os, err + ); + } + } + + let value_parser = arg.get_value_parser(); + let assert_cmd = Command::new("assert"); + if let Some(delim) = arg.get_value_delimiter() { + let default_os = RawOsStr::new(default_os); + for part in default_os.split(delim) { + if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str()) + { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, + field, + part.to_str_lossy(), + err + ); + } + } + } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, field, default_os, err + ); + } + } +} diff --git a/vendor/clap-3.2.20/src/builder/macros.rs b/vendor/clap-3.2.20/src/builder/macros.rs new file mode 100644 index 000000000..5be4d205e --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/macros.rs @@ -0,0 +1,180 @@ +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple2 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(2, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple3 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(3, tup.len()); + $a = $a.$c( + yaml_str!(tup[0]), + yaml_opt_str!(tup[1]), + yaml_opt_str!(tup[2]), + ); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_vec_or_str { + ($a:ident, $v:ident, $c:ident) => {{ + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { + $a = $a.$c(s); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + } + } else { + if let Some(s) = $v.as_str() { + $a = $a.$c(s); + } else { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $v + ); + } + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_vec { + ($a:ident, $v:ident, $c:ident) => {{ + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + let content = vec.into_iter().map(|ys| { + if let Some(s) = ys.as_str() { + s + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + }); + $a = $a.$c(content) + } else { + panic!("Failed to convert YAML value {:?} to a vec", $v); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_opt_str { + ($v:expr) => {{ + if !$v.is_null() { + Some( + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), + ) + } else { + None + } + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_char { + ($v:expr) => {{ + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + .chars() + .next() + .unwrap_or_else(|| panic!("Expected char")) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_str { + ($v:expr) => {{ + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_char { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c(yaml_char!($v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_str { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c(yaml_str!($v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_bool { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_bool() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_usize { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as usize) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_setting { + ($a:ident, $v:ident, $c:ident, $s:ident, $t:literal, $n:expr) => {{ + if let Some(v) = $v.as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + $a = $a.$c(s.parse::<$s>().unwrap_or_else(|_| { + panic!("Unknown {} '{}' found in YAML file for {}", $t, s, $n) + })); + } else { + panic!( + "Failed to convert YAML {:?} value to an array of strings", + $v + ); + } + } + } else if let Some(v) = $v.as_str() { + $a = $a.$c(v + .parse::<$s>() + .unwrap_or_else(|_| panic!("Unknown {} '{}' found in YAML file for {}", $t, v, $n))) + } else { + panic!("Failed to convert YAML {:?} value to a string", $v); + } + $a + }}; +} diff --git a/vendor/clap-3.2.20/src/builder/mod.rs b/vendor/clap-3.2.20/src/builder/mod.rs new file mode 100644 index 000000000..4f24c74d3 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/mod.rs @@ -0,0 +1,61 @@ +//! Define [`Command`] line [arguments][`Arg`] + +#[macro_use] +mod macros; + +mod action; +mod app_settings; +mod arg; +mod arg_group; +mod arg_predicate; +mod arg_settings; +mod command; +mod possible_value; +mod usage_parser; +mod value_hint; +mod value_parser; + +#[cfg(feature = "regex")] +mod regex; + +#[cfg(debug_assertions)] +mod debug_asserts; + +#[cfg(test)] +mod tests; + +pub use action::ArgAction; +pub use app_settings::{AppFlags, AppSettings}; +pub use arg::Arg; +pub use arg_group::ArgGroup; +pub use arg_settings::{ArgFlags, ArgSettings}; +pub use command::Command; +pub use possible_value::PossibleValue; +pub use value_hint::ValueHint; +pub use value_parser::PossibleValuesParser; +pub use value_parser::RangedI64ValueParser; +pub use value_parser::RangedU64ValueParser; +pub use value_parser::StringValueParser; +pub use value_parser::TypedValueParser; +pub use value_parser::ValueParser; +pub use value_parser::ValueParserFactory; +pub use value_parser::_AnonymousValueParser; +pub use value_parser::_AutoValueParser; +pub use value_parser::via_prelude; +pub use value_parser::BoolValueParser; +pub use value_parser::BoolishValueParser; +pub use value_parser::EnumValueParser; +pub use value_parser::FalseyValueParser; +pub use value_parser::NonEmptyStringValueParser; +pub use value_parser::OsStringValueParser; +pub use value_parser::PathBufValueParser; + +#[allow(deprecated)] +pub use command::App; + +#[cfg(feature = "regex")] +pub use self::regex::RegexRef; + +pub(crate) use action::CountType; +pub(crate) use arg::display_arg_val; +pub(crate) use arg_predicate::ArgPredicate; diff --git a/vendor/clap-3.2.20/src/builder/possible_value.rs b/vendor/clap-3.2.20/src/builder/possible_value.rs new file mode 100644 index 000000000..1c14217a6 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/possible_value.rs @@ -0,0 +1,259 @@ +use std::{borrow::Cow, iter}; + +use crate::util::eq_ignore_case; + +/// A possible value of an argument. +/// +/// This is used for specifying [possible values] of [Args]. +/// +/// **NOTE:** This struct is likely not needed for most usecases as it is only required to +/// [hide] single values from help messages and shell completions or to attach [help] to possible values. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, PossibleValue}; +/// let cfg = Arg::new("config") +/// .takes_value(true) +/// .value_name("FILE") +/// .value_parser([ +/// PossibleValue::new("fast"), +/// PossibleValue::new("slow").help("slower than fast"), +/// PossibleValue::new("secret speed").hide(true) +/// ]); +/// ``` +/// [Args]: crate::Arg +/// [possible values]: crate::builder::ValueParser::possible_values +/// [hide]: PossibleValue::hide() +/// [help]: PossibleValue::help() +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct PossibleValue<'help> { + name: &'help str, + help: Option<&'help str>, + aliases: Vec<&'help str>, // (name, visible) + hide: bool, +} + +impl<'help> PossibleValue<'help> { + /// Create a [`PossibleValue`] with its name. + /// + /// The name will be used to decide whether this value was provided by the user to an argument. + /// + /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments + /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("fast") + /// # ; + /// ``` + /// [hidden]: PossibleValue::hide + /// [possible value]: crate::Arg::possible_values + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + pub fn new(name: &'help str) -> Self { + PossibleValue { + name, + ..Default::default() + } + } + + /// Sets the help description of the value. + /// + /// This is typically displayed in completions (where supported) and should be a short, one-line + /// description. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .help("not fast") + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn help(mut self, help: &'help str) -> Self { + self.help = Some(help); + self + } + + /// Hides this value from help and shell completions. + /// + /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only + /// want to hide some values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("secret") + /// .hide(true) + /// # ; + /// ``` + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + #[inline] + #[must_use] + pub fn hide(mut self, yes: bool) -> Self { + self.hide = yes; + self + } + + /// Sets a *hidden* alias for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .alias("not-fast") + /// # ; + /// ``` + #[must_use] + pub fn alias(mut self, name: &'help str) -> Self { + self.aliases.push(name); + self + } + + /// Sets multiple *hidden* aliases for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .aliases(["not-fast", "snake-like"]) + /// # ; + /// ``` + #[must_use] + pub fn aliases(mut self, names: I) -> Self + where + I: IntoIterator, + { + self.aliases.extend(names.into_iter()); + self + } +} + +/// Reflection +impl<'help> PossibleValue<'help> { + /// Get the name of the argument value + #[inline] + pub fn get_name(&self) -> &'help str { + self.name + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&'help str> { + self.help + } + + /// Get the help specified for this argument, if any and the argument + /// value is not hidden + #[inline] + #[cfg(feature = "unstable-v4")] + pub(crate) fn get_visible_help(&self) -> Option<&'help str> { + if !self.hide { + self.help + } else { + None + } + } + + /// Deprecated, replaced with [`PossibleValue::is_hide_set`] + #[inline] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `PossibleValue::is_hide_set`") + )] + pub fn is_hidden(&self) -> bool { + self.is_hide_set() + } + + /// Report if [`PossibleValue::hide`] is set + #[inline] + pub fn is_hide_set(&self) -> bool { + self.hide + } + + /// Report if PossibleValue is not hidden and has a help message + pub(crate) fn should_show_help(&self) -> bool { + !self.hide && self.help.is_some() + } + + /// Get the name if argument value is not hidden, `None` otherwise + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.4", + note = "Use `PossibleValue::is_hide_set` and `PossibleValue::get_name`" + ) + )] + pub fn get_visible_name(&self) -> Option<&'help str> { + if self.hide { + None + } else { + Some(self.name) + } + } + + /// Get the name if argument value is not hidden, `None` otherwise, + /// but wrapped in quotes if it contains whitespace + pub(crate) fn get_visible_quoted_name(&self) -> Option> { + if !self.hide { + Some(if self.name.contains(char::is_whitespace) { + format!("{:?}", self.name).into() + } else { + self.name.into() + }) + } else { + None + } + } + + /// Returns all valid values of the argument value. + /// + /// Namely the name and all aliases. + pub fn get_name_and_aliases(&self) -> impl Iterator + '_ { + iter::once(&self.name).chain(&self.aliases).copied() + } + + /// Tests if the value is valid for this argument value + /// + /// The value is valid if it is either the name or one of the aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// let arg_value = PossibleValue::new("fast").alias("not-slow"); + /// + /// assert!(arg_value.matches("fast", false)); + /// assert!(arg_value.matches("not-slow", false)); + /// + /// assert!(arg_value.matches("FAST", true)); + /// assert!(!arg_value.matches("FAST", false)); + /// ``` + pub fn matches(&self, value: &str, ignore_case: bool) -> bool { + if ignore_case { + self.get_name_and_aliases() + .any(|name| eq_ignore_case(name, value)) + } else { + self.get_name_and_aliases().any(|name| name == value) + } + } +} + +impl<'help> From<&'help str> for PossibleValue<'help> { + fn from(s: &'help str) -> Self { + Self::new(s) + } +} + +impl<'help> From<&'help &'help str> for PossibleValue<'help> { + fn from(s: &'help &'help str) -> Self { + Self::new(s) + } +} diff --git a/vendor/clap-3.2.20/src/builder/regex.rs b/vendor/clap-3.2.20/src/builder/regex.rs new file mode 100644 index 000000000..bf3a78e0c --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/regex.rs @@ -0,0 +1,88 @@ +use ::regex::{Error, Regex, RegexSet}; + +use core::{convert::TryFrom, ops::Deref, str::FromStr}; +use std::borrow::Cow; + +/// Contains either a regular expression or a set of them or a reference to one. +/// +/// See [Arg::validator_regex(][crate::Arg::validator_regex] to set this on an argument. +#[derive(Debug, Clone)] +pub enum RegexRef<'a> { + /// Used if the underlying is a regex set + RegexSet(Cow<'a, RegexSet>), + /// Used if the underlying is a regex + Regex(Cow<'a, Regex>), +} + +impl<'a> RegexRef<'a> { + pub(crate) fn is_match(&self, text: &str) -> bool { + match self { + Self::Regex(r) => r.deref().is_match(text), + Self::RegexSet(r) => r.deref().is_match(text), + } + } +} + +impl<'a> From<&'a Regex> for RegexRef<'a> { + fn from(r: &'a Regex) -> Self { + Self::Regex(Cow::Borrowed(r)) + } +} + +impl<'a> From for RegexRef<'a> { + fn from(r: Regex) -> Self { + Self::Regex(Cow::Owned(r)) + } +} + +impl<'a> From<&'a RegexSet> for RegexRef<'a> { + fn from(r: &'a RegexSet) -> Self { + Self::RegexSet(Cow::Borrowed(r)) + } +} + +impl<'a> From for RegexRef<'a> { + fn from(r: RegexSet) -> Self { + Self::RegexSet(Cow::Owned(r)) + } +} + +impl<'a> TryFrom<&'a str> for RegexRef<'a> { + type Error = ::Err; + + fn try_from(r: &'a str) -> Result { + Self::from_str(r) + } +} + +impl<'a> FromStr for RegexRef<'a> { + type Err = Error; + + fn from_str(s: &str) -> Result { + Regex::from_str(s).map(|v| Self::Regex(Cow::Owned(v))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::convert::TryInto; + + #[test] + fn test_try_from_with_valid_string() { + let t: Result = "^Hello, World$".try_into(); + assert!(t.is_ok()) + } + + #[test] + fn test_try_from_with_invalid_string() { + let t: Result = "^Hello, World)$".try_into(); + assert!(t.is_err()); + } + + #[test] + fn from_str() { + let t: Result = RegexRef::from_str("^Hello, World"); + assert!(t.is_ok()); + } +} diff --git a/vendor/clap-3.2.20/src/builder/tests.rs b/vendor/clap-3.2.20/src/builder/tests.rs new file mode 100644 index 000000000..76c8b8785 --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/tests.rs @@ -0,0 +1,56 @@ +use crate::Arg; +use crate::Command; + +#[test] +fn propagate_version() { + let mut cmd = Command::new("test") + .propagate_version(true) + .version("1.1") + .subcommand(Command::new("sub1")); + cmd._propagate(); + assert_eq!( + cmd.get_subcommands().next().unwrap().get_version(), + Some("1.1") + ); +} + +#[test] +fn global_setting() { + let mut cmd = Command::new("test") + .disable_version_flag(true) + .subcommand(Command::new("subcmd")); + cmd._propagate(); + assert!(cmd + .get_subcommands() + .find(|s| s.get_name() == "subcmd") + .unwrap() + .is_disable_version_flag_set()); +} + +// This test will *fail to compile* if Command is not Send + Sync +#[test] +fn app_send_sync() { + fn foo(_: T) {} + foo(Command::new("test")) +} + +#[test] +fn issue_2090() { + let mut cmd = Command::new("cmd") + .disable_version_flag(true) + .subcommand(Command::new("sub")); + cmd._build_self(); + + assert!(cmd + .get_subcommands() + .next() + .unwrap() + .is_disable_version_flag_set()); +} + +// This test will *fail to compile* if Arg is not Send + Sync +#[test] +fn arg_send_sync() { + fn foo(_: T) {} + foo(Arg::new("test")) +} diff --git a/vendor/clap-3.2.20/src/builder/usage_parser.rs b/vendor/clap-3.2.20/src/builder/usage_parser.rs new file mode 100644 index 000000000..85d0d304e --- /dev/null +++ b/vendor/clap-3.2.20/src/builder/usage_parser.rs @@ -0,0 +1,1277 @@ +#![allow(deprecated)] + +// Internal +use crate::builder::Arg; +use crate::builder::ArgSettings; +use crate::INTERNAL_ERROR_MSG; + +#[derive(PartialEq, Debug)] +enum UsageToken { + Name, + ValName, + Short, + Long, + Help, + Multiple, + Unknown, + Default, +} + +#[derive(Debug)] +pub(crate) struct UsageParser<'help> { + usage: &'help str, + pos: usize, + start: usize, + prev: UsageToken, + explicit_name_set: bool, +} + +impl<'help> UsageParser<'help> { + fn new(usage: &'help str) -> Self { + debug!("new: usage={:?}", usage); + UsageParser { + usage, + pos: 0, + start: 0, + prev: UsageToken::Unknown, + explicit_name_set: false, + } + } + + pub(crate) fn from_usage(usage: &'help str) -> Self { + debug!("UsageParser::from_usage"); + UsageParser::new(usage) + } + + pub(crate) fn parse(mut self) -> Arg<'help> { + debug!("UsageParser::parse"); + let mut arg = Arg::default(); + loop { + debug!("UsageParser::parse:iter: pos={}", self.pos); + self.stop_at(token); + if let Some(&c) = self.usage.as_bytes().get(self.pos) { + match c { + b'-' => self.short_or_long(&mut arg), + b'.' => self.multiple(&mut arg), + b'@' => self.default(&mut arg), + b'\'' => self.help(&mut arg), + _ => self.name(&mut arg), + } + } else { + break; + } + } + + debug!("UsageParser::parse: vals...{:?}", arg.val_names); + arg + } + + fn name(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::name"); + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'<' + && !self.explicit_name_set + { + arg.settings.set(ArgSettings::Required); + } + self.pos += 1; + self.stop_at(name_end); + let name = &self.usage[self.start..self.pos]; + if self.prev == UsageToken::Unknown { + debug!("UsageParser::name: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + if arg.long.is_none() && arg.short.is_none() { + debug!("name: explicit name set..."); + self.explicit_name_set = true; + self.prev = UsageToken::Name; + } + } else { + debug!("UsageParser::name: setting val name...{}", name); + if arg.val_names.is_empty() { + arg.settings.set(ArgSettings::TakesValue); + } + let len = arg.val_names.len(); + arg.val_names.insert(len, name); + self.prev = UsageToken::ValName; + } + } + + fn stop_at(&mut self, f: F) + where + F: Fn(u8) -> bool, + { + debug!("UsageParser::stop_at"); + self.start = self.pos; + self.pos += self.usage[self.start..] + .bytes() + .take_while(|&b| f(b)) + .count(); + } + + fn short_or_long(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::short_or_long"); + self.pos += 1; + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'-' + { + self.pos += 1; + self.long(arg); + return; + } + self.short(arg) + } + + fn long(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::long"); + self.stop_at(long_end); + let name = &self.usage[self.start..self.pos]; + if !self.explicit_name_set { + debug!("UsageParser::long: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + } + debug!("UsageParser::long: setting long...{}", name); + arg.long = Some(name); + self.prev = UsageToken::Long; + } + + fn short(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::short"); + let start = &self.usage[self.pos..]; + let short = start.chars().next().expect(INTERNAL_ERROR_MSG); + debug!("UsageParser::short: setting short...{}", short); + arg.short = Some(short); + if arg.name.is_empty() { + // --long takes precedence but doesn't set self.explicit_name_set + let name = &start[..short.len_utf8()]; + debug!("UsageParser::short: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + } + self.prev = UsageToken::Short; + } + + // "something..." + fn multiple(&mut self, arg: &mut Arg) { + debug!("UsageParser::multiple"); + let mut dot_counter = 1; + let start = self.pos; + let mut bytes = self.usage[start..].bytes(); + while bytes.next() == Some(b'.') { + dot_counter += 1; + self.pos += 1; + if dot_counter == 3 { + debug!("UsageParser::multiple: setting multiple"); + arg.settings.set(ArgSettings::MultipleOccurrences); + if arg.is_takes_value_set() { + arg.settings.set(ArgSettings::MultipleValues); + arg.settings.set(ArgSettings::UseValueDelimiter); + arg.val_delim.get_or_insert(','); + } + self.prev = UsageToken::Multiple; + self.pos += 1; + break; + } + } + } + + fn help(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::help"); + self.stop_at(help_start); + self.start = self.pos + 1; + self.pos = self.usage.len() - 1; + debug!( + "UsageParser::help: setting help...{}", + &self.usage[self.start..self.pos] + ); + arg.help = Some(&self.usage[self.start..self.pos]); + self.pos += 1; // Move to next byte to keep from thinking ending ' is a start + self.prev = UsageToken::Help; + } + + fn default(&mut self, arg: &mut Arg<'help>) { + debug!( + "UsageParser::default: from=\"{}\"", + &self.usage[self.pos..self.usage.len()] + ); + self.pos += 1; // Skip @ + self.stop_at(default_value_end); // Find first space after value + debug!( + "UsageParser::default: setting default...\"{}\"", + &self.usage[self.start..self.pos] + ); + arg.settings.set(ArgSettings::TakesValue); + arg.default_vals = vec![std::ffi::OsStr::new(&self.usage[self.start..self.pos])]; + self.prev = UsageToken::Default; + } +} + +#[inline] +fn name_end(b: u8) -> bool { + b != b']' && b != b'>' +} + +#[inline] +fn token(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' && b != b'@' +} + +#[inline] +fn long_end(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' ' +} + +#[inline] +fn help_start(b: u8) -> bool { + b != b'\'' +} + +#[inline] +fn default_value_end(b: u8) -> bool { + b != b' ' +} + +#[cfg(test)] +mod test { + #![allow(deprecated)] + + use crate::builder::{Arg, ArgSettings}; + + #[allow(clippy::cognitive_complexity)] + #[test] + fn create_flag_usage() { + let a = Arg::from_usage("[flag] -f 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] --flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f --flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f --flag... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f --flag... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flags"); + assert_eq!(a.name, "flags"); + assert_eq!(a.long.unwrap(), "flags"); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flags..."); + assert_eq!(a.name, "flags"); + assert_eq!(a.long.unwrap(), "flags"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flags] -f"); + assert_eq!(a.name, "flags"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flags] -f..."); + assert_eq!(a.name, "flags"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f 'some help info'"); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f"); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f..."); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn create_option_usage0() { + // Short only + let a = Arg::from_usage("[option] -o [opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::>(), [&"opt"]); + } + + #[test] + fn create_option_usage1() { + let a = Arg::from_usage("-o [opt] 'some help info'"); + assert_eq!(a.name, "o"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::>(), [&"opt"]); + } + + #[test] + fn create_option_usage2() { + let a = Arg::from_usage(" Allow invalid UTF-8 paths - -O Implicitly using `std::str::FromStr` - --sleep Allow human-readable durations - -``` - -Optimization-level (number) -```console -$ typed-derive -O 1 -Args { optimization: Some(1), include: None, bind: None, sleep: None, defines: [] } - -$ typed-derive -O plaid -? failed -error: Invalid value "plaid" for '-O ': invalid digit found in string - -For more information try --help - -``` - -Include (path) -```console -$ typed-derive -I../hello -Args { optimization: None, include: Some("../hello"), bind: None, sleep: None, defines: [] } - -``` - -IP Address -```console -$ typed-derive --bind 192.0.0.1 -Args { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, defines: [] } - -$ typed-derive --bind localhost -? failed -error: Invalid value "localhost" for '--bind ': invalid IP address syntax - -For more information try --help - -``` - -Time -```console -$ typed-derive --sleep 10s -Args { optimization: None, include: None, bind: None, sleep: Some(Duration(10s)), defines: [] } - -$ typed-derive --sleep forever -? failed -error: Invalid value "forever" for '--sleep ': expected number at 0 - -For more information try --help - -``` - -Defines (key-value pairs) -```console -$ typed-derive -D Foo=10 -D Alice=30 -Args { optimization: None, include: None, bind: None, sleep: None, defines: [("Foo", 10), ("Alice", 30)] } - -$ typed-derive -D Foo -? failed -error: Invalid value "Foo" for '-D ': invalid KEY=value: no `=` found in `Foo` - -For more information try --help - -$ typed-derive -D Foo=Bar -? failed -error: Invalid value "Foo=Bar" for '-D ': invalid digit found in string - -For more information try --help - -``` diff --git a/vendor/clap/examples/typed-derive.rs b/vendor/clap/examples/typed-derive.rs deleted file mode 100644 index 85c750f9c..000000000 --- a/vendor/clap/examples/typed-derive.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Note: this requires the `derive` feature - -use clap::Parser; -use std::error::Error; - -#[derive(Parser, Debug)] -struct Args { - /// Implicitly using `std::str::FromStr` - #[clap(short = 'O', value_parser)] - optimization: Option, - - /// Allow invalid UTF-8 paths - #[clap(short = 'I', value_parser, value_name = "DIR", value_hint = clap::ValueHint::DirPath)] - include: Option, - - /// Handle IP addresses - #[clap(long, value_parser)] - bind: Option, - - /// Allow human-readable durations - #[clap(long, value_parser)] - sleep: Option, - - /// Hand-written parser for tuples - #[clap(short = 'D', value_parser = parse_key_val::)] - defines: Vec<(String, i32)>, -} - -/// Parse a single key-value pair -fn parse_key_val(s: &str) -> Result<(T, U), Box> -where - T: std::str::FromStr, - T::Err: Error + Send + Sync + 'static, - U: std::str::FromStr, - U::Err: Error + Send + Sync + 'static, -{ - let pos = s - .find('=') - .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; - Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) -} - -fn main() { - let args = Args::parse(); - println!("{:?}", args); -} diff --git a/vendor/clap/src/bin/stdio-fixture.rs b/vendor/clap/src/bin/stdio-fixture.rs deleted file mode 100644 index e3f34b41a..000000000 --- a/vendor/clap/src/bin/stdio-fixture.rs +++ /dev/null @@ -1,14 +0,0 @@ -fn main() { - let cmd = clap::Command::new("stdio-fixture") - .version("1.0") - .long_version("1.0 - a2132c") - .arg_required_else_help(true) - .subcommand(clap::Command::new("more")) - .arg( - clap::Arg::new("verbose") - .long("verbose") - .help("log") - .long_help("more log"), - ); - cmd.get_matches(); -} diff --git a/vendor/clap/src/builder/action.rs b/vendor/clap/src/builder/action.rs deleted file mode 100644 index ab3314290..000000000 --- a/vendor/clap/src/builder/action.rs +++ /dev/null @@ -1,325 +0,0 @@ -/// Behavior of arguments when they are encountered while parsing -/// -/// # Examples -/// -/// ```rust -/// # use clap::Command; -/// # use clap::Arg; -/// let cmd = Command::new("mycmd") -/// .arg( -/// Arg::new("special-help") -/// .short('?') -/// .action(clap::ArgAction::Help) -/// ); -/// -/// // Existing help still exists -/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); -/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); -/// -/// // New help available -/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); -/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); -/// ``` -#[derive(Clone, Debug)] -#[non_exhaustive] -#[allow(missing_copy_implementations)] // In the future, we may accept `Box` -pub enum ArgAction { - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Set) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), - /// vec!["value"] - /// ); - /// ``` - Set, - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Append) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), - /// vec!["value1", "value2"] - /// ); - /// ``` - Append, - /// Deprecated, replaced with [`ArgAction::Set`] or [`ArgAction::Append`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `ArgAction::Set` or `ArgAction::Append`" - ) - )] - StoreValue, - /// Deprecated, replaced with [`ArgAction::SetTrue`] or [`ArgAction::Count`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `ArgAction::SetTrue` or `ArgAction::Count`" - ) - )] - IncOccurrence, - /// When encountered, act as if `"true"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(true) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(false) - /// ); - /// ``` - SetTrue, - /// When encountered, act as if `"false"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetFalse) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(false) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(true) - /// ); - /// ``` - SetFalse, - /// When encountered, increment a `u8` counter - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Count) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(2) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_one::("flag").copied(), - /// Some(0) - /// ); - /// ``` - Count, - /// When encountered, display [`Command::print_help`][super::App::print_help] - /// - /// Depending on the flag, [`Command::print_long_help`][super::App::print_long_help] may be shown - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("special-help") - /// .short('?') - /// .action(clap::ArgAction::Help) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// ``` - Help, - /// When encountered, display [`Command::version`][super::App::version] - /// - /// Depending on the flag, [`Command::long_version`][super::App::long_version] may be shown - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .version("1.0.0") - /// .arg( - /// Arg::new("special-version") - /// .long("special-version") - /// .action(clap::ArgAction::Version) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// ``` - Version, -} - -impl ArgAction { - /// Returns whether this action accepts values on the command-line - /// - /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be - /// processed. - pub fn takes_values(&self) -> bool { - match self { - Self::Set => true, - Self::Append => true, - #[allow(deprecated)] - Self::StoreValue => true, - #[allow(deprecated)] - Self::IncOccurrence => false, - Self::SetTrue => false, - Self::SetFalse => false, - Self::Count => false, - Self::Help => false, - Self::Version => false, - } - } - - pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { - match self { - Self::Set => None, - Self::Append => None, - #[allow(deprecated)] - Self::StoreValue => None, - #[allow(deprecated)] - Self::IncOccurrence => None, - Self::SetTrue => Some(std::ffi::OsStr::new("false")), - Self::SetFalse => Some(std::ffi::OsStr::new("true")), - Self::Count => Some(std::ffi::OsStr::new("0")), - Self::Help => None, - Self::Version => None, - } - } - - pub(crate) fn default_value_parser(&self) -> Option { - match self { - Self::Set => None, - Self::Append => None, - #[allow(deprecated)] - Self::StoreValue => None, - #[allow(deprecated)] - Self::IncOccurrence => None, - Self::SetTrue => Some(super::ValueParser::bool()), - Self::SetFalse => Some(super::ValueParser::bool()), - Self::Count => Some(crate::value_parser!(u8).into()), - Self::Help => None, - Self::Version => None, - } - } - - #[cfg(debug_assertions)] - pub(crate) fn value_type_id(&self) -> Option { - use crate::parser::AnyValueId; - - match self { - Self::Set => None, - Self::Append => None, - #[allow(deprecated)] - Self::StoreValue => None, - #[allow(deprecated)] - Self::IncOccurrence => None, - Self::SetTrue => Some(AnyValueId::of::()), - Self::SetFalse => Some(AnyValueId::of::()), - Self::Count => Some(AnyValueId::of::()), - Self::Help => None, - Self::Version => None, - } - } -} - -pub(crate) type CountType = u8; diff --git a/vendor/clap/src/builder/app_settings.rs b/vendor/clap/src/builder/app_settings.rs deleted file mode 100644 index e2d9ba6b1..000000000 --- a/vendor/clap/src/builder/app_settings.rs +++ /dev/null @@ -1,862 +0,0 @@ -#![allow(deprecated)] - -// Std -use std::ops::BitOr; -#[cfg(feature = "yaml")] -use std::str::FromStr; - -#[allow(unused)] -use crate::Arg; -#[allow(unused)] -use crate::Command; - -// Third party -use bitflags::bitflags; - -#[doc(hidden)] -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct AppFlags(Flags); - -impl Default for AppFlags { - fn default() -> Self { - AppFlags(Flags::COLOR_AUTO) - } -} - -/// Application level settings, which affect how [`Command`] operates -/// -/// **NOTE:** When these settings are used, they apply only to current command, and are *not* -/// propagated down or up through child or parent subcommands -/// -/// [`Command`]: crate::Command -#[derive(Debug, PartialEq, Copy, Clone)] -#[non_exhaustive] -pub enum AppSettings { - /// Deprecated, replaced with [`Command::ignore_errors`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::ignore_errors`") - )] - IgnoreErrors, - - /// Deprecated, replace - /// ```rust,no_run - /// let cmd = clap::Command::new("cmd") - /// .global_setting(clap::AppSettings::WaitOnError) - /// .arg(clap::arg!(--flag)); - /// let m = cmd.get_matches(); - /// ``` - /// with - /// ```rust - /// let cmd = clap::Command::new("cmd") - /// .arg(clap::arg!(--flag)); - /// let m = match cmd.try_get_matches() { - /// Ok(m) => m, - /// Err(err) => { - /// if err.use_stderr() { - /// let _ = err.print(); - /// - /// eprintln!("\nPress [ENTER] / [RETURN] to continue..."); - /// use std::io::BufRead; - /// let mut s = String::new(); - /// let i = std::io::stdin(); - /// i.lock().read_line(&mut s).unwrap(); - /// - /// std::process::exit(2); - /// } else { - /// let _ = err.print(); - /// std::process::exit(0); - /// } - /// } - /// }; - /// ``` - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "See documentation for how to hand-implement this" - ) - )] - WaitOnError, - - /// Deprecated, replaced with [`Command::allow_hyphen_values`] and - /// [`Arg::is_allow_hyphen_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" - ) - )] - AllowHyphenValues, - - /// Deprecated, replaced with [`Command::allow_negative_numbers`] and - /// [`Command::is_allow_negative_numbers_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::allow_negative_numbers` and `Command::is_allow_negative_numbers_set`" - ) - )] - AllowNegativeNumbers, - - /// Deprecated, replaced with [`Command::args_override_self`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::args_override_self`") - )] - AllArgsOverrideSelf, - - /// Deprecated, replaced with [`Command::allow_missing_positional`] and - /// [`Command::is_allow_missing_positional_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::allow_missing_positional` and `Command::is_allow_missing_positional_set`" - ) - )] - AllowMissingPositional, - - /// Deprecated, replaced with [`Command::trailing_var_arg`] and [`Command::is_trailing_var_arg_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::trailing_var_arg` and `Command::is_trailing_var_arg_set`" - ) - )] - TrailingVarArg, - - /// Deprecated, replaced with [`Command::dont_delimit_trailing_values`] and - /// [`Command::is_dont_delimit_trailing_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::dont_delimit_trailing_values` and `Command::is_dont_delimit_trailing_values_set`" - ) - )] - DontDelimitTrailingValues, - - /// Deprecated, replaced with [`Command::infer_long_args`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::infer_long_args`") - )] - InferLongArgs, - - /// Deprecated, replaced with [`Command::infer_subcommands`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::infer_subcommands`") - )] - InferSubcommands, - - /// Deprecated, replaced with [`Command::subcommand_required`] and - /// [`Command::is_subcommand_required_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::subcommand_required` and `Command::is_subcommand_required_set`" - ) - )] - SubcommandRequired, - - /// Deprecated, replaced with [`Command::subcommand_required`] combined with - /// [`Command::arg_required_else_help`]. - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::subcommand_required` combined with `Command::arg_required_else_help`" - ) - )] - SubcommandRequiredElseHelp, - - /// Deprecated, replaced with [`Command::allow_external_subcommands`] and - /// [`Command::is_allow_external_subcommands_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::allow_external_subcommands` and `Command::is_allow_external_subcommands_set`" - ) - )] - AllowExternalSubcommands, - - /// Deprecated, replaced with [`Command::multicall`] and [`Command::is_multicall_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::multicall` and `Command::is_multicall_set`" - ) - )] - Multicall, - - /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`" - ) - )] - AllowInvalidUtf8ForExternalSubcommands, - - /// Deprecated, this is now the default - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "This is now the default") - )] - UseLongFormatForHelpSubcommand, - - /// Deprecated, replaced with [`Command::subcommand_negates_reqs`] and - /// [`Command::is_subcommand_negates_reqs_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::subcommand_negates_reqs` and `Command::is_subcommand_negates_reqs_set`" - ) - )] - SubcommandsNegateReqs, - - /// Deprecated, replaced with [`Command::args_conflicts_with_subcommands`] and - /// [`Command::is_args_conflicts_with_subcommands_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::args_conflicts_with_subcommands` and `Command::is_args_conflicts_with_subcommands_set`" - ) - )] - ArgsNegateSubcommands, - - /// Deprecated, replaced with [`Command::subcommand_precedence_over_arg`] and - /// [`Command::is_subcommand_precedence_over_arg_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::subcommand_precedence_over_arg` and `Command::is_subcommand_precedence_over_arg_set`" - ) - )] - SubcommandPrecedenceOverArg, - - /// Deprecated, replaced with [`Command::arg_required_else_help`] and - /// [`Command::is_arg_required_else_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::arg_required_else_help` and `Command::is_arg_required_else_help_set`" - ) - )] - ArgRequiredElseHelp, - - /// Displays the arguments and [`subcommands`] in the help message in the order that they were - /// declared in, and not alphabetically which is the default. - /// - /// To override the declaration order, see [`Arg::display_order`] and [`Command::display_order`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, AppSettings}; - /// Command::new("myprog") - /// .global_setting(AppSettings::DeriveDisplayOrder) - /// .get_matches(); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - /// [`Arg::display_order`]: crate::Arg::display_order - /// [`Command::display_order`]: crate::Command::display_order - DeriveDisplayOrder, - - /// Deprecated, replaced with [`Command::dont_collapse_args_in_usage`] and - /// [`Command::is_dont_collapse_args_in_usage_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::dont_collapse_args_in_usage` and `Command::is_dont_collapse_args_in_usage_set`" - ) - )] - DontCollapseArgsInUsage, - - /// Deprecated, replaced with [`Command::next_line_help`] and [`Command::is_next_line_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::next_line_help` and `Command::is_next_line_help_set`" - ) - )] - NextLineHelp, - - /// Deprecated, replaced with [`Command::disable_colored_help`] and - /// [`Command::is_disable_colored_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::disable_colored_help` and `Command::is_disable_colored_help_set`" - ) - )] - DisableColoredHelp, - - /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`" - ) - )] - DisableHelpFlag, - - /// Deprecated, replaced with [`Command::disable_help_subcommand`] and - /// [`Command::is_disable_help_subcommand_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::disable_help_subcommand` and `Command::is_disable_help_subcommand_set`" - ) - )] - DisableHelpSubcommand, - - /// Deprecated, replaced with [`Command::disable_version_flag`] and - /// [`Command::is_disable_version_flag_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`" - ) - )] - DisableVersionFlag, - - /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`" - ) - )] - PropagateVersion, - - /// Deprecated, replaced with [`Command::hide`] and [`Command::is_hide_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::hide` and `Command::is_hide_set`" - ) - )] - Hidden, - - /// Deprecated, replaced with [`Command::hide_possible_values`] and - /// [`Arg::is_hide_possible_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`" - ) - )] - HidePossibleValues, - - /// Deprecated, replaced with [`Command::help_expected`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::help_expected`") - )] - HelpExpected, - - /// Deprecated, replaced with [`Command::no_binary_name`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command::no_binary_name`") - )] - NoBinaryName, - - /// Deprecated, replaced with [`Arg::action`][super::Arg::action] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::action`") - )] - NoAutoHelp, - - /// Deprecated, replaced with [`Arg::action`][super::Arg::action] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::action`") - )] - NoAutoVersion, - - /// Deprecated, replaced with [`AppSettings::AllowHyphenValues`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `AppSettings::AllowHyphenValues`" - ) - )] - #[doc(hidden)] - AllowLeadingHyphen, - - /// Deprecated, this is now the default, see [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`] and [`ArgSettings::AllowInvalidUtf8`][crate::ArgSettings::AllowInvalidUtf8] for the opposite. - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "This is now the default see `AppSettings::AllowInvalidUtf8ForExternalSubcommands` and `ArgSettings::AllowInvalidUtf8` for the opposite." - ) - )] - #[doc(hidden)] - StrictUtf8, - - /// Deprecated, this is now the default - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "This is now the default") - )] - #[doc(hidden)] - UnifiedHelpMessage, - - /// Deprecated, this is now the default - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "This is now the default") - )] - #[doc(hidden)] - ColoredHelp, - - /// Deprecated, see [`Command::color`][crate::Command::color] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::color`") - )] - #[doc(hidden)] - ColorAuto, - - /// Deprecated, replaced with [`Command::color`][crate::Command::color] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::color`") - )] - #[doc(hidden)] - ColorAlways, - - /// Deprecated, replaced with [`Command::color`][crate::Command::color] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::color`") - )] - #[doc(hidden)] - ColorNever, - - /// Deprecated, replaced with [`AppSettings::DisableHelpFlag`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `AppSettings::DisableHelpFlag`") - )] - #[doc(hidden)] - DisableHelpFlags, - - /// Deprecated, replaced with [`AppSettings::DisableVersionFlag`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `AppSettings::DisableVersionFlag`" - ) - )] - #[doc(hidden)] - DisableVersion, - - /// Deprecated, replaced with [`AppSettings::PropagateVersion`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `AppSettings::PropagateVersion`" - ) - )] - #[doc(hidden)] - GlobalVersion, - - /// Deprecated, replaced with [`AppSettings::HidePossibleValues`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with AppSettings::HidePossibleValues" - ) - )] - #[doc(hidden)] - HidePossibleValuesInHelp, - - /// Deprecated, this is now the default - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "This is now the default") - )] - #[doc(hidden)] - UnifiedHelp, - - /// If the cmd is already built, used for caching. - #[doc(hidden)] - Built, - - /// If the cmd's bin name is already built, used for caching. - #[doc(hidden)] - BinNameBuilt, -} - -bitflags! { - struct Flags: u64 { - const SC_NEGATE_REQS = 1; - const SC_REQUIRED = 1 << 1; - const ARG_REQUIRED_ELSE_HELP = 1 << 2; - const PROPAGATE_VERSION = 1 << 3; - const DISABLE_VERSION_FOR_SC = 1 << 4; - const WAIT_ON_ERROR = 1 << 6; - const SC_REQUIRED_ELSE_HELP = 1 << 7; - const NO_AUTO_HELP = 1 << 8; - const NO_AUTO_VERSION = 1 << 9; - const DISABLE_VERSION_FLAG = 1 << 10; - const HIDDEN = 1 << 11; - const TRAILING_VARARG = 1 << 12; - const NO_BIN_NAME = 1 << 13; - const ALLOW_UNK_SC = 1 << 14; - const SC_UTF8_NONE = 1 << 15; - const LEADING_HYPHEN = 1 << 16; - const NO_POS_VALUES = 1 << 17; - const NEXT_LINE_HELP = 1 << 18; - const DERIVE_DISP_ORDER = 1 << 19; - const DISABLE_COLORED_HELP = 1 << 20; - const COLOR_ALWAYS = 1 << 21; - const COLOR_AUTO = 1 << 22; - const COLOR_NEVER = 1 << 23; - const DONT_DELIM_TRAIL = 1 << 24; - const ALLOW_NEG_NUMS = 1 << 25; - const DISABLE_HELP_SC = 1 << 27; - const DONT_COLLAPSE_ARGS = 1 << 28; - const ARGS_NEGATE_SCS = 1 << 29; - const PROPAGATE_VALS_DOWN = 1 << 30; - const ALLOW_MISSING_POS = 1 << 31; - const TRAILING_VALUES = 1 << 32; - const BUILT = 1 << 33; - const BIN_NAME_BUILT = 1 << 34; - const VALID_ARG_FOUND = 1 << 35; - const INFER_SUBCOMMANDS = 1 << 36; - const CONTAINS_LAST = 1 << 37; - const ARGS_OVERRIDE_SELF = 1 << 38; - const HELP_REQUIRED = 1 << 39; - const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40; - const DISABLE_HELP_FLAG = 1 << 41; - const USE_LONG_FORMAT_FOR_HELP_SC = 1 << 42; - const INFER_LONG_ARGS = 1 << 43; - const IGNORE_ERRORS = 1 << 44; - const MULTICALL = 1 << 45; - const NO_OP = 0; - } -} - -impl_settings! { AppSettings, AppFlags, - ArgRequiredElseHelp - => Flags::ARG_REQUIRED_ELSE_HELP, - SubcommandPrecedenceOverArg - => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG, - ArgsNegateSubcommands - => Flags::ARGS_NEGATE_SCS, - AllowExternalSubcommands - => Flags::ALLOW_UNK_SC, - StrictUtf8 - => Flags::NO_OP, - AllowInvalidUtf8ForExternalSubcommands - => Flags::SC_UTF8_NONE, - AllowHyphenValues - => Flags::LEADING_HYPHEN, - AllowLeadingHyphen - => Flags::LEADING_HYPHEN, - AllowNegativeNumbers - => Flags::ALLOW_NEG_NUMS, - AllowMissingPositional - => Flags::ALLOW_MISSING_POS, - UnifiedHelpMessage - => Flags::NO_OP, - ColoredHelp - => Flags::NO_OP, - ColorAlways - => Flags::COLOR_ALWAYS, - ColorAuto - => Flags::COLOR_AUTO, - ColorNever - => Flags::COLOR_NEVER, - DontDelimitTrailingValues - => Flags::DONT_DELIM_TRAIL, - DontCollapseArgsInUsage - => Flags::DONT_COLLAPSE_ARGS, - DeriveDisplayOrder - => Flags::DERIVE_DISP_ORDER, - DisableColoredHelp - => Flags::DISABLE_COLORED_HELP, - DisableHelpSubcommand - => Flags::DISABLE_HELP_SC, - DisableHelpFlag - => Flags::DISABLE_HELP_FLAG, - DisableHelpFlags - => Flags::DISABLE_HELP_FLAG, - DisableVersionFlag - => Flags::DISABLE_VERSION_FLAG, - DisableVersion - => Flags::DISABLE_VERSION_FLAG, - PropagateVersion - => Flags::PROPAGATE_VERSION, - GlobalVersion - => Flags::PROPAGATE_VERSION, - HidePossibleValues - => Flags::NO_POS_VALUES, - HidePossibleValuesInHelp - => Flags::NO_POS_VALUES, - HelpExpected - => Flags::HELP_REQUIRED, - Hidden - => Flags::HIDDEN, - Multicall - => Flags::MULTICALL, - NoAutoHelp - => Flags::NO_AUTO_HELP, - NoAutoVersion - => Flags::NO_AUTO_VERSION, - NoBinaryName - => Flags::NO_BIN_NAME, - SubcommandsNegateReqs - => Flags::SC_NEGATE_REQS, - SubcommandRequired - => Flags::SC_REQUIRED, - SubcommandRequiredElseHelp - => Flags::SC_REQUIRED_ELSE_HELP, - UseLongFormatForHelpSubcommand - => Flags::USE_LONG_FORMAT_FOR_HELP_SC, - TrailingVarArg - => Flags::TRAILING_VARARG, - UnifiedHelp => Flags::NO_OP, - NextLineHelp - => Flags::NEXT_LINE_HELP, - IgnoreErrors - => Flags::IGNORE_ERRORS, - WaitOnError - => Flags::WAIT_ON_ERROR, - Built - => Flags::BUILT, - BinNameBuilt - => Flags::BIN_NAME_BUILT, - InferSubcommands - => Flags::INFER_SUBCOMMANDS, - AllArgsOverrideSelf - => Flags::ARGS_OVERRIDE_SELF, - InferLongArgs - => Flags::INFER_LONG_ARGS -} - -/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? -#[cfg(feature = "yaml")] -impl FromStr for AppSettings { - type Err = String; - fn from_str(s: &str) -> Result::Err> { - #[allow(deprecated)] - #[allow(unreachable_patterns)] - match &*s.to_ascii_lowercase() { - "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), - "subcommandprecedenceoverarg" => Ok(AppSettings::SubcommandPrecedenceOverArg), - "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), - "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), - "strictutf8" => Ok(AppSettings::StrictUtf8), - "allowinvalidutf8forexternalsubcommands" => { - Ok(AppSettings::AllowInvalidUtf8ForExternalSubcommands) - } - "allowhyphenvalues" => Ok(AppSettings::AllowHyphenValues), - "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), - "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), - "allowmissingpositional" => Ok(AppSettings::AllowMissingPositional), - "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), - "coloredhelp" => Ok(AppSettings::ColoredHelp), - "coloralways" => Ok(AppSettings::ColorAlways), - "colorauto" => Ok(AppSettings::ColorAuto), - "colornever" => Ok(AppSettings::ColorNever), - "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), - "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), - "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), - "disablecoloredhelp" => Ok(AppSettings::DisableColoredHelp), - "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), - "disablehelpflag" => Ok(AppSettings::DisableHelpFlag), - "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), - "disableversionflag" => Ok(AppSettings::DisableVersionFlag), - "disableversion" => Ok(AppSettings::DisableVersion), - "propagateversion" => Ok(AppSettings::PropagateVersion), - "propagateversion" => Ok(AppSettings::GlobalVersion), - "hidepossiblevalues" => Ok(AppSettings::HidePossibleValues), - "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), - "helpexpected" => Ok(AppSettings::HelpExpected), - "hidden" => Ok(AppSettings::Hidden), - "noautohelp" => Ok(AppSettings::NoAutoHelp), - "noautoversion" => Ok(AppSettings::NoAutoVersion), - "nobinaryname" => Ok(AppSettings::NoBinaryName), - "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), - "subcommandrequired" => Ok(AppSettings::SubcommandRequired), - "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), - "uselongformatforhelpsubcommand" => Ok(AppSettings::UseLongFormatForHelpSubcommand), - "trailingvararg" => Ok(AppSettings::TrailingVarArg), - "unifiedhelp" => Ok(AppSettings::UnifiedHelp), - "nextlinehelp" => Ok(AppSettings::NextLineHelp), - "ignoreerrors" => Ok(AppSettings::IgnoreErrors), - "waitonerror" => Ok(AppSettings::WaitOnError), - "built" => Ok(AppSettings::Built), - "binnamebuilt" => Ok(AppSettings::BinNameBuilt), - "infersubcommands" => Ok(AppSettings::InferSubcommands), - "allargsoverrideself" => Ok(AppSettings::AllArgsOverrideSelf), - "inferlongargs" => Ok(AppSettings::InferLongArgs), - _ => Err(format!("unknown AppSetting: `{}`", s)), - } - } -} - -#[cfg(test)] -mod test { - #[allow(clippy::cognitive_complexity)] - #[test] - #[cfg(feature = "yaml")] - fn app_settings_fromstr() { - use super::AppSettings; - - assert_eq!( - "disablehelpflag".parse::().unwrap(), - AppSettings::DisableHelpFlag - ); - assert_eq!( - "argsnegatesubcommands".parse::().unwrap(), - AppSettings::ArgsNegateSubcommands - ); - assert_eq!( - "argrequiredelsehelp".parse::().unwrap(), - AppSettings::ArgRequiredElseHelp - ); - assert_eq!( - "subcommandprecedenceoverarg" - .parse::() - .unwrap(), - AppSettings::SubcommandPrecedenceOverArg - ); - assert_eq!( - "allowexternalsubcommands".parse::().unwrap(), - AppSettings::AllowExternalSubcommands - ); - assert_eq!( - "allowinvalidutf8forexternalsubcommands" - .parse::() - .unwrap(), - AppSettings::AllowInvalidUtf8ForExternalSubcommands - ); - assert_eq!( - "allowhyphenvalues".parse::().unwrap(), - AppSettings::AllowHyphenValues - ); - assert_eq!( - "allownegativenumbers".parse::().unwrap(), - AppSettings::AllowNegativeNumbers - ); - assert_eq!( - "disablehelpsubcommand".parse::().unwrap(), - AppSettings::DisableHelpSubcommand - ); - assert_eq!( - "disableversionflag".parse::().unwrap(), - AppSettings::DisableVersionFlag - ); - assert_eq!( - "dontcollapseargsinusage".parse::().unwrap(), - AppSettings::DontCollapseArgsInUsage - ); - assert_eq!( - "dontdelimittrailingvalues".parse::().unwrap(), - AppSettings::DontDelimitTrailingValues - ); - assert_eq!( - "derivedisplayorder".parse::().unwrap(), - AppSettings::DeriveDisplayOrder - ); - assert_eq!( - "disablecoloredhelp".parse::().unwrap(), - AppSettings::DisableColoredHelp - ); - assert_eq!( - "propagateversion".parse::().unwrap(), - AppSettings::PropagateVersion - ); - assert_eq!( - "hidden".parse::().unwrap(), - AppSettings::Hidden - ); - assert_eq!( - "hidepossiblevalues".parse::().unwrap(), - AppSettings::HidePossibleValues - ); - assert_eq!( - "helpexpected".parse::().unwrap(), - AppSettings::HelpExpected - ); - assert_eq!( - "nobinaryname".parse::().unwrap(), - AppSettings::NoBinaryName - ); - assert_eq!( - "nextlinehelp".parse::().unwrap(), - AppSettings::NextLineHelp - ); - assert_eq!( - "subcommandsnegatereqs".parse::().unwrap(), - AppSettings::SubcommandsNegateReqs - ); - assert_eq!( - "subcommandrequired".parse::().unwrap(), - AppSettings::SubcommandRequired - ); - assert_eq!( - "subcommandrequiredelsehelp".parse::().unwrap(), - AppSettings::SubcommandRequiredElseHelp - ); - assert_eq!( - "uselongformatforhelpsubcommand" - .parse::() - .unwrap(), - AppSettings::UseLongFormatForHelpSubcommand - ); - assert_eq!( - "trailingvararg".parse::().unwrap(), - AppSettings::TrailingVarArg - ); - assert_eq!( - "waitonerror".parse::().unwrap(), - AppSettings::WaitOnError - ); - assert_eq!("built".parse::().unwrap(), AppSettings::Built); - assert_eq!( - "binnamebuilt".parse::().unwrap(), - AppSettings::BinNameBuilt - ); - assert_eq!( - "infersubcommands".parse::().unwrap(), - AppSettings::InferSubcommands - ); - assert!("hahahaha".parse::().is_err()); - } -} diff --git a/vendor/clap/src/builder/arg.rs b/vendor/clap/src/builder/arg.rs deleted file mode 100644 index 63e88e80e..000000000 --- a/vendor/clap/src/builder/arg.rs +++ /dev/null @@ -1,5474 +0,0 @@ -#![allow(deprecated)] - -// Std -use std::{ - borrow::Cow, - cmp::{Ord, Ordering}, - error::Error, - ffi::OsStr, - fmt::{self, Display, Formatter}, - str, - sync::{Arc, Mutex}, -}; -#[cfg(feature = "env")] -use std::{env, ffi::OsString}; - -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -// Internal -use crate::builder::usage_parser::UsageParser; -use crate::builder::ArgPredicate; -use crate::util::{Id, Key}; -use crate::ArgAction; -use crate::PossibleValue; -use crate::ValueHint; -use crate::INTERNAL_ERROR_MSG; -use crate::{ArgFlags, ArgSettings}; - -#[cfg(feature = "regex")] -use crate::builder::RegexRef; - -/// The abstract representation of a command line argument. Used to set all the options and -/// relationships that define a valid argument for the program. -/// -/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options -/// manually, or using a usage string which is far less verbose but has fewer options. You can also -/// use a combination of the two methods to achieve the best of both worlds. -/// -/// - [Basic API][crate::Arg#basic-api] -/// - [Value Handling][crate::Arg#value-handling] -/// - [Help][crate::Arg#help-1] -/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] -/// - [Reflection][crate::Arg#reflection] -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Arg, arg}; -/// // Using the traditional builder pattern and setting each option manually -/// let cfg = Arg::new("config") -/// .short('c') -/// .long("config") -/// .takes_value(true) -/// .value_name("FILE") -/// .help("Provides a config file to myprog"); -/// // Using a usage string (setting a similar argument to the one above) -/// let input = arg!(-i --input "Provides an input file to the program"); -/// ``` -#[allow(missing_debug_implementations)] -#[derive(Default, Clone)] -pub struct Arg<'help> { - pub(crate) id: Id, - pub(crate) provider: ArgProvider, - pub(crate) name: &'help str, - pub(crate) help: Option<&'help str>, - pub(crate) long_help: Option<&'help str>, - pub(crate) action: Option, - pub(crate) value_parser: Option, - pub(crate) blacklist: Vec, - pub(crate) settings: ArgFlags, - pub(crate) overrides: Vec, - pub(crate) groups: Vec, - pub(crate) requires: Vec<(ArgPredicate<'help>, Id)>, - pub(crate) r_ifs: Vec<(Id, &'help str)>, - pub(crate) r_ifs_all: Vec<(Id, &'help str)>, - pub(crate) r_unless: Vec, - pub(crate) r_unless_all: Vec, - pub(crate) short: Option, - pub(crate) long: Option<&'help str>, - pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible) - pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) - pub(crate) disp_ord: DisplayOrder, - pub(crate) possible_vals: Vec>, - pub(crate) val_names: Vec<&'help str>, - pub(crate) num_vals: Option, - pub(crate) max_occurs: Option, - pub(crate) max_vals: Option, - pub(crate) min_vals: Option, - pub(crate) validator: Option>>>, - pub(crate) validator_os: Option>>>, - pub(crate) val_delim: Option, - pub(crate) default_vals: Vec<&'help OsStr>, - pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate<'help>, Option<&'help OsStr>)>, - pub(crate) default_missing_vals: Vec<&'help OsStr>, - #[cfg(feature = "env")] - pub(crate) env: Option<(&'help OsStr, Option)>, - pub(crate) terminator: Option<&'help str>, - pub(crate) index: Option, - pub(crate) help_heading: Option>, - pub(crate) value_hint: Option, -} - -/// # Basic API -impl<'help> Arg<'help> { - /// Create a new [`Arg`] with a unique name. - /// - /// The name is used to check whether or not the argument was used at - /// runtime, get values, set relationships with other args, etc.. - /// - /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) - /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also - /// be displayed when the user prints the usage/help information of the program. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// # ; - /// ``` - /// [`Arg::takes_value(true)`]: Arg::takes_value() - pub fn new>(n: S) -> Self { - Arg::default().name(n) - } - - /// Set the identifier used for referencing this argument in the clap API. - /// - /// See [`Arg::new`] for more details. - #[must_use] - pub fn id>(mut self, n: S) -> Self { - let name = n.into(); - self.id = Id::from(&*name); - self.name = name; - self - } - - /// Deprecated, replaced with [`Arg::id`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Arg::id`") - )] - pub fn name>(self, n: S) -> Self { - self.id(n) - } - - /// Sets the short version of the argument without the preceding `-`. - /// - /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, - /// respectively. You may use the uppercase `V` or lowercase `h` for your own arguments, in - /// which case `clap` simply will not assign those to the auto-generated - /// `version` or `help` arguments. - /// - /// # Examples - /// - /// When calling `short`, use a single valid UTF-8 character which will allow using the - /// argument via a single hyphen (`-`) such as `-c`: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "-c", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::("config").map(String::as_str), Some("file.toml")); - /// ``` - #[inline] - #[must_use] - pub fn short(mut self, s: char) -> Self { - assert!(s != '-', "short option name cannot be `-`"); - - self.short = Some(s); - self - } - - /// Sets the long version of the argument without the preceding `--`. - /// - /// By default `version` and `help` are used by the auto-generated `version` and `help` - /// arguments, respectively. You may use the word `version` or `help` for the long form of your - /// own arguments, in which case `clap` simply will not assign those to the auto-generated - /// `version` or `help` arguments. - /// - /// **NOTE:** Any leading `-` characters will be stripped - /// - /// # Examples - /// - /// To set `long` use a word containing valid UTF-8. If you supply a double leading - /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, - /// will *not* be stripped (i.e. `config-file` is allowed). - /// - /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--config", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::("cfg").map(String::as_str), Some("file.toml")); - /// ``` - #[inline] - #[must_use] - pub fn long(mut self, l: &'help str) -> Self { - #[cfg(feature = "unstable-v4")] - { - self.long = Some(l); - } - #[cfg(not(feature = "unstable-v4"))] - { - self.long = Some(l.trim_start_matches(|c| c == '-')); - } - self - } - - /// Add an alias, which functions as a hidden long flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .alias("alias") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--alias", "cool" - /// ]); - /// assert!(m.contains_id("test")); - /// assert_eq!(m.value_of("test"), Some("cool")); - /// ``` - #[must_use] - pub fn alias>(mut self, name: S) -> Self { - self.aliases.push((name.into(), false)); - self - } - - /// Add an alias, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_alias('e') - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "-e", "cool" - /// ]); - /// assert!(m.contains_id("test")); - /// assert_eq!(m.value_of("test"), Some("cool")); - /// ``` - #[must_use] - pub fn short_alias(mut self, name: char) -> Self { - assert!(name != '-', "short alias name cannot be `-`"); - - self.short_aliases.push((name, false)); - self - } - - /// Add aliases, which function as hidden long flags. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .aliases(&["do-stuff", "do-tests", "tests"]) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "--do-tests" - /// ]); - /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); - /// ``` - #[must_use] - pub fn aliases(mut self, names: &[&'help str]) -> Self { - self.aliases.extend(names.iter().map(|&x| (x, false))); - self - } - - /// Add aliases, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_aliases(&['e', 's']) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "-s" - /// ]); - /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); - /// ``` - #[must_use] - pub fn short_aliases(mut self, names: &[char]) -> Self { - for s in names { - assert!(s != &'-', "short alias name cannot be `-`"); - self.short_aliases.push((*s, false)); - } - self - } - - /// Add an alias, which functions as a visible long flag. - /// - /// Like [`Arg::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .visible_alias("something-awesome") - /// .long("test") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--something-awesome", "coffee" - /// ]); - /// assert!(m.contains_id("test")); - /// assert_eq!(m.value_of("test"), Some("coffee")); - /// ``` - /// [`Command::alias`]: Arg::alias() - #[must_use] - pub fn visible_alias>(mut self, name: S) -> Self { - self.aliases.push((name.into(), true)); - self - } - - /// Add an alias, which functions as a visible short flag. - /// - /// Like [`Arg::short_alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .visible_short_alias('t') - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "-t", "coffee" - /// ]); - /// assert!(m.contains_id("test")); - /// assert_eq!(m.value_of("test"), Some("coffee")); - /// ``` - #[must_use] - pub fn visible_short_alias(mut self, name: char) -> Self { - assert!(name != '-', "short alias name cannot be `-`"); - - self.short_aliases.push((name, true)); - self - } - - /// Add aliases, which function as visible long flags. - /// - /// Like [`Arg::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_aliases(&["something", "awesome", "cool"])) - /// .get_matches_from(vec![ - /// "prog", "--awesome" - /// ]); - /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); - /// ``` - /// [`Command::aliases`]: Arg::aliases() - #[must_use] - pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { - self.aliases.extend(names.iter().map(|n| (*n, true))); - self - } - - /// Add aliases, which function as visible short flags. - /// - /// Like [`Arg::short_aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_short_aliases(&['t', 'e'])) - /// .get_matches_from(vec![ - /// "prog", "-t" - /// ]); - /// assert_eq!(*m.get_one::("test").expect("defaulted by clap"), true); - /// ``` - #[must_use] - pub fn visible_short_aliases(mut self, names: &[char]) -> Self { - for n in names { - assert!(n != &'-', "short alias name cannot be `-`"); - self.short_aliases.push((*n, true)); - } - self - } - - /// Specifies the index of a positional argument **starting at** 1. - /// - /// **NOTE:** The index refers to position according to **other positional argument**. It does - /// not define position in the argument list as a whole. - /// - /// **NOTE:** You can optionally leave off the `index` method, and the index will be - /// assigned in order of evaluation. Utilizing the `index` method allows for setting - /// indexes out of order - /// - /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used - /// with [`Arg::short`] or [`Arg::long`]. - /// - /// **NOTE:** When utilized with [`Arg::multiple_values(true)`], only the **last** positional argument - /// may be defined as multiple (i.e. with the highest index) - /// - /// # Panics - /// - /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` - /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest - /// index - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// .index(1) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .index(1)) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .get_matches_from(vec![ - /// "prog", "--debug", "fast" - /// ]); - /// - /// assert!(m.contains_id("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" - /// // *not* first argument - /// ``` - /// [`Arg::short`]: Arg::short() - /// [`Arg::long`]: Arg::long() - /// [`Arg::multiple_values(true)`]: Arg::multiple_values() - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn index(mut self, idx: usize) -> Self { - self.index = Some(idx); - self - } - - /// This arg is the last, or final, positional argument (i.e. has the highest - /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- - /// last_arg`). - /// - /// Even, if no other arguments are left to parse, if the user omits the `--` syntax - /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also - /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with - /// the `--` syntax is otherwise not possible. - /// - /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- ]` if - /// `ARG` is marked as `.last(true)`. - /// - /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing - /// to set this can make the usage string very confusing. - /// - /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// **CAUTION:** Using this setting *and* having child subcommands is not - /// recommended with the exception of *also* using - /// [`crate::Command::args_conflicts_with_subcommands`] - /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also - /// marked [`Arg::required`]) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("args") - /// .takes_value(true) - /// .last(true) - /// # ; - /// ``` - /// - /// Setting `last` ensures the arg has the highest [index] of all positional args - /// and requires that the `--` syntax be used to access it early. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .takes_value(true) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "--", "three" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.value_of("third"), Some("three")); - /// assert!(m.value_of("second").is_none()); - /// ``` - /// - /// Even if the positional argument marked `Last` is the only argument left to parse, - /// failing to use the `--` syntax results in an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .takes_value(true) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "two", "three" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [index]: Arg::index() - /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument - #[inline] - #[must_use] - pub fn last(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Last) - } else { - self.unset_setting(ArgSettings::Last) - } - } - - /// Specifies that the argument must be present. - /// - /// Required by default means it is required, when no other conflicting rules or overrides have - /// been evaluated. Conflicting rules take precedence over being required. - /// - /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be - /// required by default. This is because if a flag were to be required, it should simply be - /// implied. No additional information is required from user. Flags by their very nature are - /// simply boolean on/off switches. The only time a user *should* be required to use a flag - /// is if the operation is destructive in nature, and the user is essentially proving to you, - /// "Yes, I know what I'm doing." - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required(true) - /// # ; - /// ``` - /// - /// Setting required requires that the argument be used at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting required and then *not* supplying that argument at runtime is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - #[inline] - #[must_use] - pub fn required(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Required) - } else { - self.unset_setting(ArgSettings::Required) - } - } - - /// Sets an argument that is required when this one is present - /// - /// i.e. when using this argument, the following argument *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires("input") - /// # ; - /// ``` - /// - /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the - /// defining argument is used. If the defining argument isn't used, the other argument isn't - /// required - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required - /// ``` - /// - /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires(mut self, arg_id: T) -> Self { - self.requires.push((ArgPredicate::IsPresent, arg_id.into())); - self - } - - /// This argument must be passed alone; it conflicts with all other arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .exclusive(true) - /// # ; - /// ``` - /// - /// Setting an exclusive argument and having any other arguments present at runtime - /// is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("exclusive") - /// .takes_value(true) - /// .exclusive(true) - /// .long("exclusive")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--exclusive", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - #[inline] - #[must_use] - pub fn exclusive(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Exclusive) - } else { - self.unset_setting(ArgSettings::Exclusive) - } - } - - /// Specifies that an argument can be matched to all child [`Subcommand`]s. - /// - /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however - /// their values once a user uses them will be propagated back up to parents. In effect, this - /// means one should *define* all global arguments at the top level, however it doesn't matter - /// where the user *uses* the global argument. - /// - /// # Examples - /// - /// Assume an application with two subcommands, and you'd like to define a - /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't - /// want to clutter the source with three duplicate [`Arg`] definitions. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("verb") - /// .long("verbose") - /// .short('v') - /// .action(ArgAction::SetTrue) - /// .global(true)) - /// .subcommand(Command::new("test")) - /// .subcommand(Command::new("do-stuff")) - /// .get_matches_from(vec![ - /// "prog", "do-stuff", "--verbose" - /// ]); - /// - /// assert_eq!(m.subcommand_name(), Some("do-stuff")); - /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); - /// assert_eq!(*sub_m.get_one::("verb").expect("defaulted by clap"), true); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - #[inline] - #[must_use] - pub fn global(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Global) - } else { - self.unset_setting(ArgSettings::Global) - } - } - - /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::action` (Issue #3772)") - )] - pub fn multiple_occurrences(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::MultipleOccurrences) - } else { - self.unset_setting(ArgSettings::MultipleOccurrences) - } - } - - /// Deprecated, for flags this is replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))` - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "For flags, replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`" - ) - )] - pub fn max_occurrences(mut self, qty: usize) -> Self { - self.max_occurs = Some(qty); - if qty > 1 { - self.multiple_occurrences(true) - } else { - self - } - } - - /// Check if the [`ArgSettings`] variant is currently set on the argument. - /// - /// [`ArgSettings`]: crate::ArgSettings - #[inline] - pub fn is_set(&self, s: ArgSettings) -> bool { - self.settings.is_set(s) - } - - /// Apply a setting to the argument. - /// - /// See [`ArgSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Arg, ArgSettings}; - /// Arg::new("config") - /// .setting(ArgSettings::Required) - /// .setting(ArgSettings::TakesValue) - /// # ; - /// ``` - /// - /// ```no_run - /// # use clap::{Arg, ArgSettings}; - /// Arg::new("config") - /// .setting(ArgSettings::Required | ArgSettings::TakesValue) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn setting(mut self, setting: F) -> Self - where - F: Into, - { - self.settings.insert(setting.into()); - self - } - - /// Remove a setting from the argument. - /// - /// See [`ArgSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Arg, ArgSettings}; - /// Arg::new("config") - /// .unset_setting(ArgSettings::Required) - /// .unset_setting(ArgSettings::TakesValue) - /// # ; - /// ``` - /// - /// ```no_run - /// # use clap::{Arg, ArgSettings}; - /// Arg::new("config") - /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn unset_setting(mut self, setting: F) -> Self - where - F: Into, - { - self.settings.remove(setting.into()); - self - } -} - -/// # Value Handling -impl<'help> Arg<'help> { - /// Specifies that the argument takes a value at run time. - /// - /// **NOTE:** values for arguments may be specified in any of the following methods - /// - /// - Using a space such as `-o value` or `--option value` - /// - Using an equals and no space such as `-o=value` or `--option=value` - /// - Use a short and no space such as `-ovalue` - /// - /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning - /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to - /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], - /// alternatively you can turn delimiting values **OFF** by using - /// [`Arg::use_value_delimiter(false)`][Arg::use_value_delimiter] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// - /// assert!(m.contains_id("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter() - /// [multiple values]: Arg::multiple_values - #[inline] - #[must_use] - pub fn takes_value(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::TakesValue) - } else { - self.unset_setting(ArgSettings::TakesValue) - } - } - - /// Specify the behavior when parsing an argument - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Set) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!(matches.occurrences_of("flag"), 0); - /// assert_eq!( - /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), - /// vec!["value"] - /// ); - /// ``` - #[inline] - #[must_use] - pub fn action(mut self, action: ArgAction) -> Self { - self.action = Some(action); - self - } - - /// Specify the type of the argument. - /// - /// This allows parsing and validating a value before storing it into - /// [`ArgMatches`][crate::ArgMatches]. - /// - /// See also - /// - [`value_parser!`][crate::value_parser!] for auto-selecting a value parser for a given type - /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations - /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings - /// - [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] and [`RangedU64ValueParser`][crate::builder::RangedU64ValueParser] for numeric ranges - /// - [`EnumValueParser`][crate::builder::EnumValueParser] and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values - /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation - /// - /// ```rust - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("color") - /// .long("color") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// ) - /// .arg( - /// clap::Arg::new("hostname") - /// .long("hostname") - /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) - /// .takes_value(true) - /// .required(true) - /// ) - /// .arg( - /// clap::Arg::new("port") - /// .long("port") - /// .value_parser(clap::value_parser!(u16).range(3000..)) - /// .takes_value(true) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut( - /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] - /// ).unwrap(); - /// - /// let color: &String = m.get_one("color") - /// .expect("default"); - /// assert_eq!(color, "auto"); - /// - /// let hostname: &String = m.get_one("hostname") - /// .expect("required"); - /// assert_eq!(hostname, "rust-lang.org"); - /// - /// let port: u16 = *m.get_one("port") - /// .expect("required"); - /// assert_eq!(port, 3001); - /// ``` - pub fn value_parser(mut self, parser: impl Into) -> Self { - self.value_parser = Some(parser.into()); - self - } - - /// Specifies that the argument may have an unknown number of values - /// - /// Without any other settings, this argument may appear only *once*. - /// - /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not. - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`]. - /// - /// **WARNING:** - /// - /// Setting `multiple_values` for an argument that takes a value, but with no other details can - /// be dangerous in some circumstances. Because multiple values are allowed, - /// `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI where - /// positional arguments are *also* expected as `clap` will continue parsing *values* until one - /// of the following happens: - /// - /// - It reaches the [maximum number of values] - /// - It reaches a [specific number of values] - /// - It finds another flag or option (i.e. something that starts with a `-`) - /// - It reaches a [value terminator][Arg::value_terminator] is reached - /// - /// Alternatively, [require a delimiter between values][Arg::require_delimiter]. - /// - /// **WARNING:** - /// - /// When using args with `multiple_values` and [`subcommands`], one needs to consider the - /// possibility of an argument value being the same as a valid subcommand. By default `clap` will - /// parse the argument in question as a value *only if* a value is possible at that moment. - /// Otherwise it will be parsed as a subcommand. In effect, this means using `multiple_values` with no - /// additional parameters and a value that coincides with a subcommand name, the subcommand - /// cannot be called unless another argument is passed between them. - /// - /// As an example, consider a CLI with an option `--ui-paths=...` and subcommand `signer` - /// - /// The following would be parsed as values to `--ui-paths`. - /// - /// ```text - /// $ program --ui-paths path1 path2 signer - /// ``` - /// - /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values - /// until another argument is reached and it knows `--ui-paths` is done parsing. - /// - /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding - /// [`Arg::number_of_values(1)`] or using *only* [`ArgAction::Append`]. The following are all - /// valid, and `signer` is parsed as a subcommand in the first case, but a value in the second - /// case. - /// - /// ```text - /// $ program --ui-paths path1 signer - /// $ program --ui-paths path1 --ui-paths signer signer - /// ``` - /// - /// # Examples - /// - /// An example with options - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .multiple_values(true) - /// .short('F')) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(m.contains_id("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// - /// Although `multiple_values` has been specified, we cannot use the argument more than once. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .multiple_values(true) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage) - /// ``` - /// - /// A common mistake is to define an option which allows multiple values, and a positional - /// argument. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .multiple_values(true) - /// .short('F')) - /// .arg(Arg::new("word")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(m.contains_id("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! - /// assert!(!m.contains_id("word")); // but we clearly used word! - /// ``` - /// - /// The problem is `clap` doesn't know when to stop parsing values for "files". This is further - /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would - /// appear to only fail sometimes...not good! - /// - /// A solution for the example above is to limit how many values with a [maximum], or [specific] - /// number, or to say [`ArgAction::Append`] is ok, but multiple values is not. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .action(ArgAction::Append) - /// .short('F')) - /// .arg(Arg::new("word")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" - /// ]); - /// - /// assert!(m.contains_id("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert!(m.contains_id("word")); - /// assert_eq!(m.value_of("word"), Some("word")); - /// ``` - /// - /// As a final example, let's fix the above error and get a pretty message to the user :) - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .action(ArgAction::Append) - /// .short('F')) - /// .arg(Arg::new("word")) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - /// [`Arg::number_of_values(1)`]: Arg::number_of_values() - /// [maximum number of values]: Arg::max_values() - /// [specific number of values]: Arg::number_of_values() - /// [maximum]: Arg::max_values() - /// [specific]: Arg::number_of_values() - #[inline] - #[must_use] - pub fn multiple_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::MultipleValues) - } else { - self.unset_setting(ArgSettings::MultipleValues) - } - } - - /// The number of values allowed for this argument. - /// - /// For example, if you had a - /// `-f ` argument where you wanted exactly 3 'files' you would set - /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided - /// 3 and only 3 values. - /// - /// **NOTE:** Does *not* require [`Arg::multiple_occurrences(true)`] to be set. Setting - /// [`Arg::multiple_occurrences(true)`] would allow `-f -f ` where - /// as *not* setting it would only allow one occurrence of this argument. - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("file") - /// .short('f') - /// .number_of_values(3); - /// ``` - /// - /// Not supplying the correct number of values is an error - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .number_of_values(2) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() - #[inline] - #[must_use] - pub fn number_of_values(mut self, qty: usize) -> Self { - self.num_vals = Some(qty); - self.takes_value(true).multiple_values(true) - } - - /// The *maximum* number of values are for this argument. - /// - /// For example, if you had a - /// `-f ` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and - /// this argument would be satisfied if the user provided, 1, 2, or 3 values. - /// - /// **NOTE:** This does *not* implicitly set [`Arg::multiple_occurrences(true)`]. This is because - /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single - /// occurrence with multiple values. For positional arguments this **does** set - /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("file") - /// .short('f') - /// .max_values(3); - /// ``` - /// - /// Supplying less than the maximum number of values is allowed - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .max_values(3) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1", "file2" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2"]); - /// ``` - /// - /// Supplying more than the maximum number of values is an error - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .max_values(2) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() - #[inline] - #[must_use] - pub fn max_values(mut self, qty: usize) -> Self { - self.max_vals = Some(qty); - self.takes_value(true).multiple_values(true) - } - - /// The *minimum* number of values for this argument. - /// - /// For example, if you had a - /// `-f ` argument where you wanted at least 2 'files' you would set - /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more - /// values. - /// - /// **NOTE:** This does not implicitly set [`Arg::multiple_occurrences(true)`]. This is because - /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single - /// occurrence with multiple values. For positional arguments this **does** set - /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// **NOTE:** Passing a non-zero value is not the same as specifying [`Arg::required(true)`]. - /// This is due to min and max validation only being performed for present arguments, - /// marking them as required will thus perform validation and a min value of 1 - /// is unnecessary, ignored if not required. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("file") - /// .short('f') - /// .min_values(3); - /// ``` - /// - /// Supplying more than the minimum number of values is allowed - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .min_values(2) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// - /// Supplying less than the minimum number of values is an error - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("file") - /// .takes_value(true) - /// .min_values(2) - /// .short('F')) - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues); - /// ``` - /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() - /// [`Arg::required(true)`]: Arg::required() - #[inline] - #[must_use] - pub fn min_values(mut self, qty: usize) -> Self { - self.min_vals = Some(qty); - self.takes_value(true).multiple_values(true) - } - - /// Placeholder for the argument's value in the help message / usage. - /// - /// This name is cosmetic only; the name is **not** used to access arguments. - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("cfg") - /// .long("config") - /// .value_name("FILE") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .long("config") - /// .value_name("FILE") - /// .help("Some help text")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// USAGE: - /// valnames [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [option]: Arg::takes_value() - /// [positional]: Arg::index() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - #[inline] - #[must_use] - pub fn value_name(self, name: &'help str) -> Self { - self.value_names(&[name]) - } - - /// Placeholders for the argument's values in the help message / usage. - /// - /// These names are cosmetic only, used for help and usage strings only. The names are **not** - /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. - /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will - /// be the second). - /// - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or - /// multiple value names in order to not throw off the help text alignment of all options. - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("speed") - /// .short('s') - /// .value_names(&["fast", "slow"]); - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("io") - /// .long("io-files") - /// .value_names(&["INFILE", "OUTFILE"])) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// USAGE: - /// valnames [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// --io-files Some help text - /// -V, --version Print version information - /// ``` - /// [`Arg::next_line_help(true)`]: Arg::next_line_help() - /// [`Arg::number_of_values`]: Arg::number_of_values() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::multiple_values(true)`]: Arg::multiple_values() - #[must_use] - pub fn value_names(mut self, names: &[&'help str]) -> Self { - self.val_names = names.to_vec(); - self.takes_value(true) - } - - /// Provide the shell a hint about how to complete this argument. - /// - /// See [`ValueHint`][crate::ValueHint] for more information. - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]. - /// - /// For example, to take a username as argument: - /// - /// ``` - /// # use clap::{Arg, ValueHint}; - /// Arg::new("user") - /// .short('u') - /// .long("user") - /// .value_hint(ValueHint::Username); - /// ``` - /// - /// To take a full command line and its arguments (for example, when writing a command wrapper): - /// - /// ``` - /// # use clap::{Command, Arg, ValueHint}; - /// Command::new("prog") - /// .trailing_var_arg(true) - /// .arg( - /// Arg::new("command") - /// .takes_value(true) - /// .multiple_values(true) - /// .value_hint(ValueHint::CommandWithArguments) - /// ); - /// ``` - #[must_use] - pub fn value_hint(mut self, value_hint: ValueHint) -> Self { - self.value_hint = Some(value_hint); - self.takes_value(true) - } - - /// Deprecated, replaced with [`Arg::value_parser(...)`] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`") - )] - pub fn validator(mut self, mut f: F) -> Self - where - F: FnMut(&str) -> Result + Send + 'help, - E: Into>, - { - self.validator = Some(Arc::new(Mutex::new(move |s: &str| { - f(s).map(|_| ()).map_err(|e| e.into()) - }))); - self - } - - /// Deprecated, replaced with [`Arg::value_parser(...)`] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`") - )] - pub fn validator_os(mut self, mut f: F) -> Self - where - F: FnMut(&OsStr) -> Result + Send + 'help, - E: Into>, - { - self.validator_os = Some(Arc::new(Mutex::new(move |s: &OsStr| { - f(s).map(|_| ()).map_err(|e| e.into()) - }))); - self - } - - /// Deprecated in [Issue #3743](https://github.com/clap-rs/clap/issues/3743), replaced with [`Arg::value_parser(...)`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Deprecated in Issue #3743; eplaced with `Arg::value_parser(...)`" - ) - )] - #[cfg(feature = "regex")] - #[must_use] - pub fn validator_regex( - self, - regex: impl Into>, - err_message: &'help str, - ) -> Self { - let regex = regex.into(); - self.validator(move |s: &str| { - if regex.is_match(s) { - Ok(()) - } else { - Err(err_message) - } - }) - } - - /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`" - ) - )] - #[must_use] - pub fn possible_value(mut self, value: T) -> Self - where - T: Into>, - { - self.possible_vals.push(value.into()); - self.takes_value(true) - } - - /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`" - ) - )] - #[must_use] - pub fn possible_values(mut self, values: I) -> Self - where - I: IntoIterator, - T: Into>, - { - self.possible_vals - .extend(values.into_iter().map(|value| value.into())); - self.takes_value(true) - } - - /// Match values against [`Arg::possible_values`] without matching case. - /// - /// When other arguments are conditionally required based on the - /// value of a case-insensitive argument, the equality check done - /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or - /// [`Arg::required_if_eq_all`] is case-insensitive. - /// - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .long("option") - /// .takes_value(true) - /// .ignore_case(true) - /// .value_parser(["test123"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", - /// ]); - /// - /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); - /// ``` - /// - /// This setting also works when multiple values can be defined: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .short('o') - /// .long("option") - /// .takes_value(true) - /// .ignore_case(true) - /// .multiple_values(true) - /// .value_parser(["test123", "test321"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", "teST123", "tESt321" - /// ]); - /// - /// let matched_vals = m.values_of("option").unwrap().collect::>(); - /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); - /// ``` - #[inline] - #[must_use] - pub fn ignore_case(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::IgnoreCase) - } else { - self.unset_setting(ArgSettings::IgnoreCase) - } - } - - /// Allows values which start with a leading hyphen (`-`) - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// **WARNING**: Take caution when using this setting combined with - /// [`Arg::multiple_values`], as this becomes ambiguous `$ prog --arg -- -- val`. All - /// three `--, --, val` will be values when the user may have thought the second `--` would - /// constitute the normal, "Only positional args follow" idiom. To fix this, consider using - /// [`Arg::multiple_occurrences`] which only allows a single value at a time. - /// - /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and - /// the user passing in a value that matches a valid short. For example, `prog -opt -F` where - /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. - /// Care should be taken when designing these args. This is compounded by the ability to "stack" - /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid - /// shorts. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("pat") - /// .takes_value(true) - /// .allow_hyphen_values(true) - /// .long("pattern")) - /// .get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert_eq!(m.value_of("pat"), Some("-file")); - /// ``` - /// - /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a - /// hyphen is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("pat") - /// .takes_value(true) - /// .long("pattern")) - /// .try_get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::number_of_values(1)`]: Arg::number_of_values() - #[inline] - #[must_use] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowHyphenValues) - } else { - self.unset_setting(ArgSettings::AllowHyphenValues) - } - } - - /// Deprecated, replaced with [`Arg::value_parser(...)`] with either [`ValueParser::os_string()`][crate::builder::ValueParser::os_string] - /// or [`ValueParser::path_buf()`][crate::builder::ValueParser::path_buf] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `Arg::value_parser(...)` with either `ValueParser::os_string()` or `ValueParser::path_buf()`" - ) - )] - pub fn allow_invalid_utf8(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowInvalidUtf8) - } else { - self.unset_setting(ArgSettings::AllowInvalidUtf8) - } - } - - /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`" - ) - )] - pub fn forbid_empty_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::ForbidEmptyValues) - } else { - self.unset_setting(ArgSettings::ForbidEmptyValues) - } - } - - /// Requires that options use the `--option=val` syntax - /// - /// i.e. an equals between the option and associated value. - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// # Examples - /// - /// Setting `require_equals` requires that the option have an equals sign between - /// it and the associated value. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config=file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `require_equals` and *not* supplying the equals will cause an - /// error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - #[inline] - #[must_use] - pub fn require_equals(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::RequireEquals) - } else { - self.unset_setting(ArgSettings::RequireEquals) - } - } - - /// Specifies that an argument should allow grouping of multiple values via a - /// delimiter. - /// - /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, - /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the - /// value delimiter for all arguments that accept values (options and positional arguments) - /// - /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`] - /// to the comma `,`. - /// - /// **NOTE:** Implicitly sets [`Arg::takes_value`] - /// - /// # Examples - /// - /// The following example shows the default behavior. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let delims = Command::new("prog") - /// .arg(Arg::new("option") - /// .long("option") - /// .use_value_delimiter(true) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(delims.contains_id("option")); - /// assert_eq!(delims.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); - /// ``` - /// The next example shows the difference when turning delimiters off. This is the default - /// behavior - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let nodelims = Command::new("prog") - /// .arg(Arg::new("option") - /// .long("option") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(nodelims.contains_id("option")); - /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); - /// ``` - /// [`Arg::value_delimiter`]: Arg::value_delimiter() - #[inline] - #[must_use] - pub fn use_value_delimiter(mut self, yes: bool) -> Self { - if yes { - if self.val_delim.is_none() { - self.val_delim = Some(','); - } - self.takes_value(true) - .setting(ArgSettings::UseValueDelimiter) - } else { - self.val_delim = None; - self.unset_setting(ArgSettings::UseValueDelimiter) - } - } - - /// Deprecated, replaced with [`Arg::use_value_delimiter`] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Arg::use_value_delimiter`") - )] - pub fn use_delimiter(self, yes: bool) -> Self { - self.use_value_delimiter(yes) - } - - /// Separator between the arguments values, defaults to `,` (comma). - /// - /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`] - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .long("config") - /// .value_delimiter(';')) - /// .get_matches_from(vec![ - /// "prog", "--config=val1;val2;val3" - /// ]); - /// - /// assert_eq!(m.values_of("config").unwrap().collect::>(), ["val1", "val2", "val3"]) - /// ``` - /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - #[inline] - #[must_use] - pub fn value_delimiter(mut self, d: char) -> Self { - self.val_delim = Some(d); - self.takes_value(true).use_value_delimiter(true) - } - - /// Specifies that *multiple values* may only be set using the delimiter. - /// - /// This means if an option is encountered, and no delimiter is found, it is assumed that no - /// additional values for that option follow. This is unlike the default, where it is generally - /// assumed that more values will follow regardless of whether or not a delimiter is used. - /// - /// **NOTE:** The default is `false`. - /// - /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and - /// [`Arg::takes_value`] - /// - /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either - /// through help text or other means. - /// - /// # Examples - /// - /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice - /// everything works in this first example, as we use a delimiter, as expected. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let delims = Command::new("prog") - /// .arg(Arg::new("opt") - /// .short('o') - /// .takes_value(true) - /// .use_value_delimiter(true) - /// .require_delimiter(true) - /// .multiple_values(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1,val2,val3", - /// ]); - /// - /// assert!(delims.contains_id("opt")); - /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); - /// ``` - /// - /// In this next example, we will *not* use a delimiter. Notice it's now an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("opt") - /// .short('o') - /// .takes_value(true) - /// .use_value_delimiter(true) - /// .require_delimiter(true)) - /// .try_get_matches_from(vec![ - /// "prog", "-o", "val1", "val2", "val3", - /// ]); - /// - /// assert!(res.is_err()); - /// let err = res.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::UnknownArgument); - /// ``` - /// - /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none - /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no - /// positional arguments have been defined, it's an error of an unexpected argument. - /// - /// In this final example, we contrast the above with `clap`'s default behavior where the above - /// is *not* an error. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let delims = Command::new("prog") - /// .arg(Arg::new("opt") - /// .short('o') - /// .takes_value(true) - /// .multiple_values(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1", "val2", "val3", - /// ]); - /// - /// assert!(delims.contains_id("opt")); - /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); - /// ``` - #[inline] - #[must_use] - pub fn require_value_delimiter(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::RequireDelimiter) - } else { - self.unset_setting(ArgSettings::RequireDelimiter) - } - } - - /// Deprecated, replaced with [`Arg::require_value_delimiter`] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Arg::require_value_delimiter`") - )] - pub fn require_delimiter(self, yes: bool) -> Self { - self.require_value_delimiter(yes) - } - - /// Sentinel to **stop** parsing multiple values of a give argument. - /// - /// By default when - /// one sets [`multiple_values(true)`] on an argument, clap will continue parsing values for that - /// argument until it reaches another valid argument, or one of the other more specific settings - /// for multiple values is used (such as [`min_values`], [`max_values`] or - /// [`number_of_values`]). - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one - /// of the values - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("vals") - /// .takes_value(true) - /// .multiple_values(true) - /// .value_terminator(";") - /// # ; - /// ``` - /// - /// The following example uses two arguments, a sequence of commands, and the location in which - /// to perform them - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cmds") - /// .takes_value(true) - /// .multiple_values(true) - /// .allow_hyphen_values(true) - /// .value_terminator(";")) - /// .arg(Arg::new("location")) - /// .get_matches_from(vec![ - /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" - /// ]); - /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); - /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); - /// assert_eq!(m.value_of("location"), Some("/home/clap")); - /// ``` - /// [options]: Arg::takes_value() - /// [positional arguments]: Arg::index() - /// [`multiple_values(true)`]: Arg::multiple_values() - /// [`min_values`]: Arg::min_values() - /// [`number_of_values`]: Arg::number_of_values() - /// [`max_values`]: Arg::max_values() - #[inline] - #[must_use] - pub fn value_terminator(mut self, term: &'help str) -> Self { - self.terminator = Some(term); - self.takes_value(true) - } - - /// Consume all following arguments. - /// - /// Do not be parse them individually, but rather pass them in entirety. - /// - /// It is worth noting that setting this requires all values to come after a `--` to indicate - /// they should all be captured. For example: - /// - /// ```text - /// --foo something -- -v -v -v -b -b -b --baz -q -u -x - /// ``` - /// - /// Will result in everything after `--` to be considered one raw argument. This behavior - /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`] - /// may be more appropriate. - /// - /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] [`Arg::multiple_values(true)`], - /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. - /// - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::multiple_values(true)`]: Arg::multiple_values() - /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() - /// [`Arg::last(true)`]: Arg::last() - #[inline] - #[must_use] - pub fn raw(self, yes: bool) -> Self { - self.takes_value(yes) - .multiple_values(yes) - .allow_hyphen_values(yes) - .last(yes) - } - - /// Value for the argument when not present. - /// - /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] - /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. - /// - /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will - /// still return `true`. If you wish to determine whether the argument was used at runtime or - /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided - /// a value at runtime **and** these other conditions are met as well. If you have set - /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg - /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` - /// will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// # Examples - /// - /// First we use the default value without providing any value at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg, ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("opt"), Some("myval")); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); - /// ``` - /// - /// Next we provide a value at runtime to override the default. - /// - /// ```rust - /// # use clap::{Command, Arg, ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog", "--myopt=non_default" - /// ]); - /// - /// assert_eq!(m.value_of("opt"), Some("non_default")); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); - /// ``` - /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of() - /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[inline] - #[must_use] - pub fn default_value(self, val: &'help str) -> Self { - self.default_values_os(&[OsStr::new(val)]) - } - - /// Value for the argument when not present. - /// - /// See [`Arg::default_value`]. - /// - /// [`Arg::default_value`]: Arg::default_value() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_value_os(self, val: &'help OsStr) -> Self { - self.default_values_os(&[val]) - } - - /// Value for the argument when not present. - /// - /// See [`Arg::default_value`]. - /// - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_values(self, vals: &[&'help str]) -> Self { - let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); - self.default_values_os(&vals_vec[..]) - } - - /// Value for the argument when not present. - /// - /// See [`Arg::default_values`]. - /// - /// [`Arg::default_values`]: Arg::default_values() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_values_os(mut self, vals: &[&'help OsStr]) -> Self { - self.default_vals = vals.to_vec(); - self.takes_value(true) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// This configuration option is often used to give the user a shortcut and allow them to - /// efficiently specify an option argument without requiring an explicitly value. The `--color` - /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, - /// the user can quickly just add `--color` to the command line to produce the desired color output. - /// - /// **NOTE:** using this configuration option requires the use of the `.min_values(0)` and the - /// `.require_equals(true)` configuration option. These are required in order to unambiguously - /// determine what, if any, value was supplied for the argument. - /// - /// # Examples - /// - /// For POSIX style `--color`: - /// ```rust - /// # use clap::{Command, Arg, ValueSource}; - /// fn cli() -> Command<'static> { - /// Command::new("prog") - /// .arg(Arg::new("color").long("color") - /// .value_name("WHEN") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// .min_values(0) - /// .require_equals(true) - /// .default_missing_value("always") - /// .help("Specify WHEN to colorize output.") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.value_of("color"), Some("auto")); - /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color=never" - /// ]); - /// assert_eq!(m.value_of("color"), Some("never")); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color" - /// ]); - /// assert_eq!(m.value_of("color"), Some("always")); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// For bool literals: - /// ```rust - /// # use clap::{Command, Arg, ValueSource, value_parser}; - /// fn cli() -> Command<'static> { - /// Command::new("prog") - /// .arg(Arg::new("create").long("create") - /// .value_name("BOOL") - /// .value_parser(value_parser!(bool)) - /// .min_values(0) - /// .require_equals(true) - /// .default_missing_value("true") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.get_one::("create").copied(), None); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create=false" - /// ]); - /// assert_eq!(m.get_one::("create").copied(), Some(false)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create" - /// ]); - /// assert_eq!(m.get_one::("create").copied(), Some(true)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// [`ArgMatches::value_of`]: ArgMatches::value_of() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_missing_value(self, val: &'help str) -> Self { - self.default_missing_values_os(&[OsStr::new(val)]) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_value_os(self, val: &'help OsStr) -> Self { - self.default_missing_values_os(&[val]) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - #[inline] - #[must_use] - pub fn default_missing_values(self, vals: &[&'help str]) -> Self { - let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); - self.default_missing_values_os(&vals_vec[..]) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_values`]. - /// - /// [`Arg::default_missing_values`]: Arg::default_missing_values() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_values_os(mut self, vals: &[&'help OsStr]) -> Self { - self.default_missing_vals = vals.to_vec(); - self.takes_value(true) - } - - /// Read from `name` environment variable when argument is not present. - /// - /// If it is not present in the environment, then default - /// rules will apply. - /// - /// If user sets the argument in the environment: - /// - When [`Arg::takes_value(true)`] is not set, the flag is considered raised. - /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will - /// return value of the environment variable. - /// - /// If user doesn't set the argument in the environment: - /// - When [`Arg::takes_value(true)`] is not set, the flag is considered off. - /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will - /// return the default specified. - /// - /// # Examples - /// - /// In this example, we show the variable coming from the environment: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("env")); - /// ``` - /// - /// In this example, because [`Arg::takes_value(false)`] (by default), - /// `prog` is a flag that accepts an optional, case-insensitive boolean literal. - /// A `false` literal is `n`, `no`, `f`, `false`, `off` or `0`. - /// An absent environment variable will also be considered as `false`. - /// Anything else will considered as `true`. - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg}; - /// - /// env::set_var("TRUE_FLAG", "true"); - /// env::set_var("FALSE_FLAG", "0"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("true_flag") - /// .long("true_flag") - /// .env("TRUE_FLAG")) - /// .arg(Arg::new("false_flag") - /// .long("false_flag") - /// .env("FALSE_FLAG")) - /// .arg(Arg::new("absent_flag") - /// .long("absent_flag") - /// .env("ABSENT_FLAG")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(m.is_present("true_flag")); - /// assert_eq!(m.value_of("true_flag"), None); - /// assert!(!m.is_present("false_flag")); - /// assert!(!m.is_present("absent_flag")); - /// ``` - /// - /// In this example, we show the variable coming from an option on the CLI: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--flag", "opt" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("opt")); - /// ``` - /// - /// In this example, we show the variable coming from the environment even with the - /// presence of a default: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .takes_value(true) - /// .default_value("default")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("env")); - /// ``` - /// - /// In this example, we show the use of multiple values in a single environment variable: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg}; - /// - /// env::set_var("MY_FLAG_MULTI", "env1,env2"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG_MULTI") - /// .takes_value(true) - /// .multiple_values(true) - /// .use_value_delimiter(true)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.values_of("flag").unwrap().collect::>(), vec!["env1", "env2"]); - /// ``` - /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn env(self, name: &'help str) -> Self { - self.env_os(OsStr::new(name)) - } - - /// Read from `name` environment variable when argument is not present. - /// - /// See [`Arg::env`]. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn env_os(mut self, name: &'help OsStr) -> Self { - self.env = Some((name, env::var_os(name))); - self - } -} - -/// # Help -impl<'help> Arg<'help> { - /// Sets the description of the argument for short help (`-h`). - /// - /// Typically, this is a short (one line) description of the arg. - /// - /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [`Arg::long_help`]: Arg::long_help() - #[inline] - #[must_use] - pub fn help(mut self, h: impl Into>) -> Self { - self.help = h.into(); - self - } - - /// Sets the description of the argument for long help (`--help`). - /// - /// Typically this a more detailed (multi-line) message - /// that describes the arg. - /// - /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .long_help( - /// "The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now.")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// prog - /// - /// USAGE: - /// prog [OPTIONS] - /// - /// OPTIONS: - /// --config - /// The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now. - /// - /// -h, --help - /// Print help information - /// - /// -V, --version - /// Print version information - /// ``` - /// [`Arg::help`]: Arg::help() - #[inline] - #[must_use] - pub fn long_help(mut self, h: impl Into>) -> Self { - self.long_help = h.into(); - self - } - - /// Allows custom ordering of args within the help message. - /// - /// Args with a lower value will be displayed first in the help message. This is helpful when - /// one would like to emphasise frequently used args, or prioritize those towards the top of - /// the list. Args with duplicate display orders will be displayed in alphabetical order. - /// - /// **NOTE:** The default is 999 for all arguments. - /// - /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in - /// [index] order. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name. - /// // Args without a display_order have a value of 999 and are - /// // displayed alphabetically with all other 999 valued args. - /// .long("long-option") - /// .short('o') - /// .takes_value(true) - /// .help("Some help and text")) - /// .arg(Arg::new("b") - /// .long("other-option") - /// .short('O') - /// .takes_value(true) - /// .display_order(1) // In order to force this arg to appear *first* - /// // all we have to do is give it a value lower than 999. - /// // Any other args with a value of 1 will be displayed - /// // alphabetically with this one...then 2 values, then 3, etc. - /// .help("I should be first!")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// cust-ord - /// - /// USAGE: - /// cust-ord [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// -O, --other-option I should be first! - /// -o, --long-option Some help and text - /// ``` - /// [positional arguments]: Arg::index() - /// [index]: Arg::index() - #[inline] - #[must_use] - pub fn display_order(mut self, ord: usize) -> Self { - self.disp_ord.set_explicit(ord); - self - } - - /// Override the [current] help section. - /// - /// [current]: crate::Command::help_heading - #[inline] - #[must_use] - pub fn help_heading(mut self, heading: O) -> Self - where - O: Into>, - { - self.help_heading = Some(heading.into()); - self - } - - /// Render the [help][Arg::help] on the line after the argument. - /// - /// This can be helpful for arguments with very long or complex help messages. - /// This can also be helpful for arguments with very long flag names, or many/long value names. - /// - /// **NOTE:** To apply this setting to all arguments and subcommands, consider using - /// [`crate::Command::next_line_help`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("long-option-flag") - /// .short('o') - /// .takes_value(true) - /// .next_line_help(true) - /// .value_names(&["value1", "value2"]) - /// .help("Some really long help and complex\n\ - /// help that makes more sense to be\n\ - /// on a line after the option")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// nlh - /// - /// USAGE: - /// nlh [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// -o, --long-option-flag - /// Some really long help and complex - /// help that makes more sense to be - /// on a line after the option - /// ``` - #[inline] - #[must_use] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::NextLineHelp) - } else { - self.unset_setting(ArgSettings::NextLineHelp) - } - } - - /// Do not display the argument in help message. - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// # Examples - /// - /// Setting `Hidden` will hide the argument when displaying help text - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Hidden) - } else { - self.unset_setting(ArgSettings::Hidden) - } - } - - /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. - /// - /// This is useful for args with many values, or ones which are explained elsewhere in the - /// help text. - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// To set this for all arguments, see - /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .value_parser(["fast", "slow"]) - /// .takes_value(true) - /// .hide_possible_values(true)); - /// ``` - /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HidePossibleValues) - } else { - self.unset_setting(ArgSettings::HidePossibleValues) - } - } - - /// Do not display the default value of the argument in the help message. - /// - /// This is useful when default behavior of an arg is explained elsewhere in the help text. - /// - /// **NOTE:** Setting this requires [`Arg::takes_value`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .default_value("localhost") - /// .takes_value(true) - /// .hide_default_value(true)); - /// - /// ``` - /// - /// If we were to run the above program with `--help` the `[default: localhost]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_default_value(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideDefaultValue) - } else { - self.unset_setting(ArgSettings::HideDefaultValue) - } - } - - /// Do not display in help the environment variable name. - /// - /// This is useful when the variable option is explained elsewhere in the help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .env("MODE") - /// .takes_value(true) - /// .hide_env(true)); - /// ``` - /// - /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help - /// text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnv) - } else { - self.unset_setting(ArgSettings::HideEnv) - } - } - - /// Do not display in help any values inside the associated ENV variables for the argument. - /// - /// This is useful when ENV vars contain sensitive values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .env("CONNECT") - /// .takes_value(true) - /// .hide_env_values(true)); - /// - /// ``` - /// - /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the - /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnvValues) - } else { - self.unset_setting(ArgSettings::HideEnvValues) - } - } - - /// Hides an argument from short help (`-h`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("debug") - /// .hide_short_help(true); - /// ``` - /// - /// Setting `hide_short_help(true)` will hide the argument when displaying short help text - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when --help is called - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_short_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenShortHelp) - } else { - self.unset_setting(ArgSettings::HiddenShortHelp) - } - } - - /// Hides an argument from long help (`--help`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// Setting `hide_long_help(true)` will hide the argument when displaying long help text - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when -h is called - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// USAGE: - /// helptest [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_long_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenLongHelp) - } else { - self.unset_setting(ArgSettings::HiddenLongHelp) - } - } -} - -/// # Advanced Argument Relations -impl<'help> Arg<'help> { - /// The name of the [`ArgGroup`] the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("debug") - /// .long("debug") - /// .group("mode") - /// # ; - /// ``` - /// - /// Multiple arguments can be a member of a single group and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .group("mode")) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .group("mode")) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn group(mut self, group_id: T) -> Self { - self.groups.push(group_id.into()); - self - } - - /// The names of [`ArgGroup`]'s the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("debug") - /// .long("debug") - /// .groups(&["mode", "verbosity"]) - /// # ; - /// ``` - /// - /// Arguments can be members of multiple groups and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .groups(&["mode", "verbosity"])) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .groups(&["mode", "verbosity"])) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// assert!(m.contains_id("verbosity")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn groups(mut self, group_ids: &[T]) -> Self { - self.groups.extend(group_ids.iter().map(Id::from)); - self - } - - /// Specifies the value of the argument if `arg` has been used at runtime. - /// - /// If `val` is set to `None`, `arg` only needs to be present. If `val` is set to `"some-val"` - /// then `arg` must be present at runtime **and** have the value `val`. - /// - /// If `default` is set to `None`, `default_value` will be removed. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. This setting however only takes effect when the user has not provided a value at - /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` - /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were - /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", None, Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", None, Some("default"))) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// - /// Now lets only use the default value if `--opt` contains the value `special`. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "special" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// - /// We can run the same test and provide any value *other than* `special` and we won't get a - /// default value. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "hahaha" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// - /// If we want to unset the default value for an Arg based on the presence or - /// value of some other Arg. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value("default") - /// .default_value_if("flag", None, None)) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::default_value`]: Arg::default_value() - #[must_use] - pub fn default_value_if( - self, - arg_id: T, - val: Option<&'help str>, - default: Option<&'help str>, - ) -> Self { - self.default_value_if_os(arg_id, val.map(OsStr::new), default.map(OsStr::new)) - } - - /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] - /// only using [`OsStr`]s instead. - /// - /// [`Arg::default_value_if`]: Arg::default_value_if() - /// [`OsStr`]: std::ffi::OsStr - #[must_use] - pub fn default_value_if_os( - mut self, - arg_id: T, - val: Option<&'help OsStr>, - default: Option<&'help OsStr>, - ) -> Self { - self.default_vals_ifs - .push((arg_id.into(), val.into(), default)); - self.takes_value(true) - } - - /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. - /// - /// The method takes a slice of tuples in the `(arg, Option, default)` format. - /// - /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first - /// if multiple conditions are true, the first one found will be applied and the ultimate value. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, Some("default")), - /// ("opt", Some("channal"), Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("chan")); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, Some("default")), - /// ("opt", Some("channal"), Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// - /// We can also see that these values are applied in order, and if more than one condition is - /// true, only the first evaluated "wins" - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag")) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, Some("default")), - /// ("opt", Some("channal"), Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// [`Arg::takes_value(true)`]: Arg::takes_value() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[must_use] - pub fn default_value_ifs( - mut self, - ifs: &[(T, Option<&'help str>, Option<&'help str>)], - ) -> Self { - for (arg, val, default) in ifs { - self = self.default_value_if_os(arg, val.map(OsStr::new), default.map(OsStr::new)); - } - self - } - - /// Provides multiple conditional default values in the exact same manner as - /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. - /// - /// [`Arg::default_value_ifs`]: Arg::default_value_ifs() - /// [`OsStr`]: std::ffi::OsStr - #[must_use] - pub fn default_value_ifs_os( - mut self, - ifs: &[(T, Option<&'help OsStr>, Option<&'help OsStr>)], - ) -> Self { - for (arg, val, default) in ifs { - self = self.default_value_if_os(arg, *val, *default); - } - self - } - - /// Set this arg as [required] as long as the specified argument is not present at runtime. - /// - /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not - /// mandatory to also set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present("debug") - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, - /// but it's not an error because the `unless` arg has been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_unless_present(mut self, arg_id: T) -> Self { - self.r_unless.push(arg_id.into()); - self - } - - /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *all* of the `names` arguments. - /// - /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are - /// present see [`Arg::required_unless_present_any`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_all(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, but it's not an error - /// because *all* of the `names` args have been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .arg(Arg::new("infile") - /// .short('i') - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "-i", "file" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying - /// either *all* of `unless` args or the `self` arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .arg(Arg::new("infile") - /// .short('i') - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_all(mut self, names: I) -> Self - where - I: IntoIterator, - T: Key, - { - self.r_unless_all.extend(names.into_iter().map(Id::from)); - self - } - - /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *one or more* of the `unless` arguments. - /// - /// **NOTE:** If you wish for this argument to be required unless *all of* these args are - /// present see [`Arg::required_unless_present_all`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_any(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime - /// *unless* *at least one of* the args in `names` are present. In the following example, the - /// required argument is *not* provided, but it's not an error because one the `unless` args - /// have been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .arg(Arg::new("infile") - /// .short('i') - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` - /// or this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .arg(Arg::new("infile") - /// .short('i') - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_any(mut self, names: I) -> Self - where - I: IntoIterator, - T: Key, - { - self.r_unless.extend(names.into_iter().map(Id::from)); - self - } - - /// This argument is [required] only if the specified `arg` is present at runtime and its value - /// equals `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq("other_arg", "value") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "not-special" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "special" - /// ]); - /// - /// // We did use --other=special so "cfg" had become required but was missing. - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // By default, the comparison is case-sensitive, so "cfg" wasn't required - /// assert!(res.is_ok()); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .ignore_case(true) - /// .takes_value(true)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq(mut self, arg_id: T, val: &'help str) -> Self { - self.r_ifs.push((arg_id.into(), val)); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_any(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_any(&[(arg, val)])` makes this arg required if any of the `arg`s - /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .takes_value(true) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "other" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_any(&[(arg, val)])` and having any of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .takes_value(true) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_any(mut self, ifs: &[(T, &'help str)]) -> Self { - self.r_ifs - .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if every one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_all(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_all(&[(arg, val)])` makes this arg required if all of the `arg`s - /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .takes_value(true) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_all(&[(arg, val)])` and having all of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .takes_value(true) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--extra", "val", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_all(mut self, ifs: &[(T, &'help str)]) -> Self { - self.r_ifs_all - .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); - self - } - - /// Require another argument if this arg was present at runtime and its value equals to `val`. - /// - /// This method takes `value, another_arg` pair. At runtime, clap will check - /// if this arg (`self`) is present and its value equals to `val`. - /// If it does, `another_arg` will be marked as required. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_if("val", "arg") - /// # ; - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument is anything other than - /// `val`, the other argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "other") - /// .long("config")) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "some.cfg" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying - /// `arg` is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "my.cfg" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_if(mut self, val: &'help str, arg_id: T) -> Self { - self.requires - .push((ArgPredicate::Equals(OsStr::new(val)), arg_id.into())); - self - } - - /// Allows multiple conditional requirements. - /// - /// The requirement will only become valid if this arg's value equals `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_ifs(&[ - /// ("val", "arg"), - /// ("other_val", "arg2"), - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::requires_ifs(&["val", "arg"])` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument's value is anything other - /// than `val`, `arg` isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires_ifs(&[ - /// ("special.conf", "opt"), - /// ("other.conf", "other"), - /// ]) - /// .long("config")) - /// .arg(Arg::new("opt") - /// .long("option") - /// .takes_value(true)) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "special.conf" - /// ]); - /// - /// assert!(res.is_err()); // We used --config=special.conf so --option is required - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_ifs(mut self, ifs: &[(&'help str, T)]) -> Self { - self.requires.extend( - ifs.iter() - .map(|(val, arg)| (ArgPredicate::Equals(OsStr::new(*val)), Id::from(arg))), - ); - self - } - - /// Require these arguments names when this one is presen - /// - /// i.e. when using this argument, the following arguments *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// by default. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_all(&["input", "output"]) - /// # ; - /// ``` - /// - /// Setting `Arg::requires_all(&[arg, arg2])` requires that all the arguments be used at - /// runtime if the defining argument is used. If the defining argument isn't used, the other - /// argument isn't required - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .arg(Arg::new("output")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required - /// ``` - /// - /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an - /// error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .requires_all(&["input", "output"]) - /// .long("config")) - /// .arg(Arg::new("input")) - /// .arg(Arg::new("output")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "in.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// // We didn't use output - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_all(mut self, names: &[T]) -> Self { - self.requires - .extend(names.iter().map(|s| (ArgPredicate::IsPresent, s.into()))); - self - } - - /// This argument is mutually exclusive with the specified argument. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. - /// - /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with("debug") - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having both arguments present at runtime is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .conflicts_with("debug") - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with(mut self, arg_id: T) -> Self { - self.blacklist.push(arg_id.into()); - self - } - - /// This argument is mutually exclusive with the specified arguments. - /// - /// See [`Arg::conflicts_with`]. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with_all(&["debug", "input"]) - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having any of the arguments present at runtime with a - /// conflicting argument is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .takes_value(true) - /// .conflicts_with_all(&["debug", "input"]) - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [`Arg::conflicts_with`]: Arg::conflicts_with() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with_all(mut self, names: &[&str]) -> Self { - self.blacklist.extend(names.iter().copied().map(Id::from)); - self - } - - /// Sets an overridable argument. - /// - /// i.e. this argument and the following argument - /// will override each other in POSIX style (whichever argument was specified at runtime - /// **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. - /// - /// **WARNING:** Positional arguments and options which accept - /// [`Arg::multiple_occurrences`] cannot override themselves (or we - /// would never be able to advance to the next positional). If a positional - /// argument or option with one of the [`Arg::multiple_occurrences`] - /// settings lists itself as an override, it is simply ignored. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("debug")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with("flag")) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color - /// - /// assert!(m.is_present("color")); - /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag - /// // was never used because it was overridden with color - /// assert!(!m.is_present("flag")); - /// ``` - /// Care must be taken when using this setting, and having an arg override with itself. This - /// is common practice when supporting things like shell aliases, config files, etc. - /// However, when combined with multiple values, it can get dicy. - /// Here is how clap handles such situations: - /// - /// When a flag overrides itself, it's as if the flag was only ever used once (essentially - /// preventing a "Unexpected multiple usage" error): - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("posix") - /// .arg(arg!(--flag "some flag").overrides_with("flag")) - /// .get_matches_from(vec!["posix", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// ``` - /// - /// Making an arg [`Arg::multiple_occurrences`] and override itself - /// is essentially meaningless. Therefore clap ignores an override of self - /// if it's a flag and it already accepts multiple occurrences. - /// - /// ``` - /// # use clap::{Command, arg}; - /// let m = Command::new("posix") - /// .arg(arg!(--flag ... "some flag").overrides_with("flag")) - /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// ``` - /// - /// Now notice with options (which *do not* set - /// [`Arg::multiple_occurrences`]), it's as if only the last - /// occurrence happened. - /// - /// ``` - /// # use clap::{Command, arg}; - /// let m = Command::new("posix") - /// .arg(arg!(--opt "some option").overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.value_of("opt"), Some("other")); - /// ``` - /// - /// This will also work when [`Arg::multiple_values`] is enabled: - /// - /// ``` - /// # use clap::{Command, Arg}; - /// let m = Command::new("posix") - /// .arg( - /// Arg::new("opt") - /// .long("opt") - /// .takes_value(true) - /// .multiple_values(true) - /// .overrides_with("opt") - /// ) - /// .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["3", "4", "5"]); - /// ``` - /// - /// Just like flags, options with [`Arg::multiple_occurrences`] set - /// will ignore the "override self" setting. - /// - /// ``` - /// # use clap::{Command, arg}; - /// let m = Command::new("posix") - /// .arg(arg!(--opt ... "some option") - /// .multiple_values(true) - /// .overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "over", "other", "val"]); - /// ``` - #[must_use] - pub fn overrides_with(mut self, arg_id: T) -> Self { - self.overrides.push(arg_id.into()); - self - } - - /// Sets multiple mutually overridable arguments by name. - /// - /// i.e. this argument and the following argument will override each other in POSIX style - /// (whichever argument was specified at runtime **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("color")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with_all(&["flag", "debug"])) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color - /// - /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag - /// // and debug were never used because they were overridden - /// // with color - /// assert!(!m.is_present("debug")); - /// assert!(!m.is_present("flag")); - /// ``` - #[must_use] - pub fn overrides_with_all(mut self, names: &[T]) -> Self { - self.overrides.extend(names.iter().map(Id::from)); - self - } -} - -/// # Reflection -impl<'help> Arg<'help> { - /// Get the name of the argument - #[inline] - pub fn get_id(&self) -> &'help str { - self.name - } - - /// Deprecated, replaced with [`Arg::get_id`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Arg::get_id`") - )] - pub fn get_name(&self) -> &'help str { - self.get_id() - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&'help str> { - self.help - } - - /// Get the long help specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// let arg = Arg::new("foo").long_help("long help"); - /// assert_eq!(Some("long help"), arg.get_long_help()); - /// ``` - /// - #[inline] - pub fn get_long_help(&self) -> Option<&'help str> { - self.long_help - } - - /// Get the help heading specified for this argument, if any - #[inline] - pub fn get_help_heading(&self) -> Option<&'help str> { - self.help_heading.unwrap_or_default() - } - - /// Get the short option name for this argument, if any - #[inline] - pub fn get_short(&self) -> Option { - self.short - } - - /// Get visible short aliases for this argument, if any - #[inline] - pub fn get_visible_short_aliases(&self) -> Option> { - if self.short_aliases.is_empty() { - None - } else { - Some( - self.short_aliases - .iter() - .filter_map(|(c, v)| if *v { Some(c) } else { None }) - .copied() - .collect(), - ) - } - } - - /// Get the short option name and its visible aliases, if any - #[inline] - pub fn get_short_and_visible_aliases(&self) -> Option> { - let mut shorts = match self.short { - Some(short) => vec![short], - None => return None, - }; - if let Some(aliases) = self.get_visible_short_aliases() { - shorts.extend(aliases); - } - Some(shorts) - } - - /// Get the long option name for this argument, if any - #[inline] - pub fn get_long(&self) -> Option<&'help str> { - self.long - } - - /// Get visible aliases for this argument, if any - #[inline] - pub fn get_visible_aliases(&self) -> Option> { - if self.aliases.is_empty() { - None - } else { - Some( - self.aliases - .iter() - .filter_map(|(s, v)| if *v { Some(s) } else { None }) - .copied() - .collect(), - ) - } - } - - /// Get the long option name and its visible aliases, if any - #[inline] - pub fn get_long_and_visible_aliases(&self) -> Option> { - let mut longs = match self.long { - Some(long) => vec![long], - None => return None, - }; - if let Some(aliases) = self.get_visible_aliases() { - longs.extend(aliases); - } - Some(longs) - } - - /// Deprecated, replaced with [`Arg::get_value_parser().possible_values()`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with `Arg::get_value_parser().possible_values()`" - ) - )] - pub fn get_possible_values(&self) -> Option<&[PossibleValue<'help>]> { - if self.possible_vals.is_empty() { - None - } else { - Some(&self.possible_vals) - } - } - - pub(crate) fn get_possible_values2(&self) -> Vec> { - #![allow(deprecated)] - if !self.is_takes_value_set() { - vec![] - } else if let Some(pvs) = self.get_possible_values() { - // Check old first in case the user explicitly set possible values and the derive inferred - // a `ValueParser` with some. - pvs.to_vec() - } else { - self.get_value_parser() - .possible_values() - .map(|pvs| pvs.collect()) - .unwrap_or_default() - } - } - - /// Get the names of values for this argument. - #[inline] - pub fn get_value_names(&self) -> Option<&[&'help str]> { - if self.val_names.is_empty() { - None - } else { - Some(&self.val_names) - } - } - - /// Get the number of values for this argument. - #[inline] - pub fn get_num_vals(&self) -> Option { - self.num_vals - } - - /// Get the delimiter between multiple values - #[inline] - pub fn get_value_delimiter(&self) -> Option { - self.val_delim - } - - /// Get the index of this argument, if any - #[inline] - pub fn get_index(&self) -> Option { - self.index - } - - /// Get the value hint of this argument - pub fn get_value_hint(&self) -> ValueHint { - self.value_hint.unwrap_or_else(|| { - if self.is_takes_value_set() { - let type_id = self.get_value_parser().type_id(); - if type_id == crate::parser::AnyValueId::of::() { - ValueHint::AnyPath - } else { - ValueHint::default() - } - } else { - ValueHint::default() - } - }) - } - - /// Deprecated, replaced with [`Arg::is_global_set`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Arg::is_global_set`") - )] - pub fn get_global(&self) -> bool { - self.is_global_set() - } - - /// Get the environment variable name specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use std::ffi::OsStr; - /// # use clap::Arg; - /// let arg = Arg::new("foo").env("ENVIRONMENT"); - /// assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env()); - /// ``` - #[cfg(feature = "env")] - pub fn get_env(&self) -> Option<&OsStr> { - self.env.as_ref().map(|x| x.0) - } - - /// Get the default values specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// let arg = Arg::new("foo").default_value("default value"); - /// assert_eq!(&["default value"], arg.get_default_values()); - /// ``` - pub fn get_default_values(&self) -> &[&OsStr] { - &self.default_vals - } - - /// Checks whether this argument is a positional or not. - /// - /// # Examples - /// - /// ``` - /// # use clap::Arg; - /// let arg = Arg::new("foo"); - /// assert_eq!(true, arg.is_positional()); - /// - /// let arg = Arg::new("foo").long("foo"); - /// assert_eq!(false, arg.is_positional()); - /// ``` - pub fn is_positional(&self) -> bool { - self.long.is_none() && self.short.is_none() - } - - /// Reports whether [`Arg::required`] is set - pub fn is_required_set(&self) -> bool { - self.is_set(ArgSettings::Required) - } - - /// Report whether [`Arg::multiple_values`] is set - pub fn is_multiple_values_set(&self) -> bool { - self.is_set(ArgSettings::MultipleValues) - } - - /// [`Arg::multiple_occurrences`] is going away ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "`multiple_occurrences` away (Issue #3772)") - )] - pub fn is_multiple_occurrences_set(&self) -> bool { - self.is_set(ArgSettings::MultipleOccurrences) - } - - /// Report whether [`Arg::is_takes_value_set`] is set - pub fn is_takes_value_set(&self) -> bool { - self.is_set(ArgSettings::TakesValue) - } - - /// Report whether [`Arg::allow_hyphen_values`] is set - pub fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(ArgSettings::AllowHyphenValues) - } - - /// Deprecated, replaced with [`Arg::get_value_parser()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`") - )] - pub fn is_forbid_empty_values_set(&self) -> bool { - self.is_set(ArgSettings::ForbidEmptyValues) - } - - /// Deprecated, replaced with [`Arg::get_value_parser()` - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`") - )] - pub fn is_allow_invalid_utf8_set(&self) -> bool { - self.is_set(ArgSettings::AllowInvalidUtf8) - } - - /// Behavior when parsing the argument - pub fn get_action(&self) -> &super::ArgAction { - const DEFAULT: super::ArgAction = super::ArgAction::StoreValue; - self.action.as_ref().unwrap_or(&DEFAULT) - } - - /// Configured parser for argument values - /// - /// # Example - /// - /// ```rust - /// let cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("port") - /// .value_parser(clap::value_parser!(usize)) - /// ); - /// let value_parser = cmd.get_arguments() - /// .find(|a| a.get_id() == "port").unwrap() - /// .get_value_parser(); - /// println!("{:?}", value_parser); - /// ``` - pub fn get_value_parser(&self) -> &super::ValueParser { - if let Some(value_parser) = self.value_parser.as_ref() { - value_parser - } else if self.is_allow_invalid_utf8_set() { - static DEFAULT: super::ValueParser = super::ValueParser::os_string(); - &DEFAULT - } else { - static DEFAULT: super::ValueParser = super::ValueParser::string(); - &DEFAULT - } - } - - /// Report whether [`Arg::global`] is set - pub fn is_global_set(&self) -> bool { - self.is_set(ArgSettings::Global) - } - - /// Report whether [`Arg::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(ArgSettings::NextLineHelp) - } - - /// Report whether [`Arg::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(ArgSettings::Hidden) - } - - /// Report whether [`Arg::hide_default_value`] is set - pub fn is_hide_default_value_set(&self) -> bool { - self.is_set(ArgSettings::HideDefaultValue) - } - - /// Report whether [`Arg::hide_possible_values`] is set - pub fn is_hide_possible_values_set(&self) -> bool { - self.is_set(ArgSettings::HidePossibleValues) - } - - /// Report whether [`Arg::hide_env`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_set(&self) -> bool { - self.is_set(ArgSettings::HideEnv) - } - - /// Report whether [`Arg::hide_env_values`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_values_set(&self) -> bool { - self.is_set(ArgSettings::HideEnvValues) - } - - /// Report whether [`Arg::hide_short_help`] is set - pub fn is_hide_short_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenShortHelp) - } - - /// Report whether [`Arg::hide_long_help`] is set - pub fn is_hide_long_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenLongHelp) - } - - /// Report whether [`Arg::use_value_delimiter`] is set - pub fn is_use_value_delimiter_set(&self) -> bool { - self.is_set(ArgSettings::UseValueDelimiter) - } - - /// Report whether [`Arg::require_value_delimiter`] is set - pub fn is_require_value_delimiter_set(&self) -> bool { - self.is_set(ArgSettings::RequireDelimiter) - } - - /// Report whether [`Arg::require_equals`] is set - pub fn is_require_equals_set(&self) -> bool { - self.is_set(ArgSettings::RequireEquals) - } - - /// Reports whether [`Arg::exclusive`] is set - pub fn is_exclusive_set(&self) -> bool { - self.is_set(ArgSettings::Exclusive) - } - - /// Reports whether [`Arg::last`] is set - pub fn is_last_set(&self) -> bool { - self.is_set(ArgSettings::Last) - } - - /// Reports whether [`Arg::ignore_case`] is set - pub fn is_ignore_case_set(&self) -> bool { - self.is_set(ArgSettings::IgnoreCase) - } -} - -/// # Deprecated -impl<'help> Arg<'help> { - /// Deprecated, replaced with [`Arg::new`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::new`") - )] - #[doc(hidden)] - pub fn with_name>(n: S) -> Self { - Self::new(n) - } - - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - #[cfg(feature = "yaml")] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) - )] - #[doc(hidden)] - pub fn from_yaml(y: &'help Yaml) -> Self { - #![allow(deprecated)] - let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); - // We WANT this to panic on error...so expect() is good. - let (name_yaml, yaml) = yaml_file_hash - .iter() - .next() - .expect("There must be one arg in the YAML file"); - let name_str = name_yaml.as_str().expect("Arg name must be a string"); - let mut a = Arg::new(name_str); - - for (k, v) in yaml.as_hash().expect("Arg must be a hash") { - a = match k.as_str().expect("Arg fields must be strings") { - "short" => yaml_to_char!(a, v, short), - "long" => yaml_to_str!(a, v, long), - "aliases" => yaml_vec_or_str!(a, v, alias), - "help" => yaml_to_str!(a, v, help), - "long_help" => yaml_to_str!(a, v, long_help), - "required" => yaml_to_bool!(a, v, required), - "required_if" => yaml_tuple2!(a, v, required_if_eq), - "required_ifs" => yaml_tuple2!(a, v, required_if_eq), - "takes_value" => yaml_to_bool!(a, v, takes_value), - "index" => yaml_to_usize!(a, v, index), - "global" => yaml_to_bool!(a, v, global), - "multiple" => yaml_to_bool!(a, v, multiple), - "hidden" => yaml_to_bool!(a, v, hide), - "next_line_help" => yaml_to_bool!(a, v, next_line_help), - "group" => yaml_to_str!(a, v, group), - "number_of_values" => yaml_to_usize!(a, v, number_of_values), - "max_values" => yaml_to_usize!(a, v, max_values), - "min_values" => yaml_to_usize!(a, v, min_values), - "value_name" => yaml_to_str!(a, v, value_name), - "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), - "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), - "last" => yaml_to_bool!(a, v, last), - "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), - "value_delimiter" => yaml_to_char!(a, v, value_delimiter), - "required_unless" => yaml_to_str!(a, v, required_unless_present), - "display_order" => yaml_to_usize!(a, v, display_order), - "default_value" => yaml_to_str!(a, v, default_value), - "default_value_if" => yaml_tuple3!(a, v, default_value_if), - "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), - #[cfg(feature = "env")] - "env" => yaml_to_str!(a, v, env), - "value_names" => yaml_vec_or_str!(a, v, value_name), - "groups" => yaml_vec_or_str!(a, v, group), - "requires" => yaml_vec_or_str!(a, v, requires), - "requires_if" => yaml_tuple2!(a, v, requires_if), - "requires_ifs" => yaml_tuple2!(a, v, requires_if), - "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), - "overrides_with" => yaml_to_str!(a, v, overrides_with), - "possible_values" => yaml_vec_or_str!(a, v, possible_value), - "case_insensitive" => yaml_to_bool!(a, v, ignore_case), - "required_unless_one" => yaml_vec!(a, v, required_unless_present_any), - "required_unless_all" => yaml_vec!(a, v, required_unless_present_all), - s => { - panic!( - "Unknown setting '{}' in YAML file for arg '{}'", - s, name_str - ) - } - } - } - - a - } - - /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") - )] - #[doc(hidden)] - pub fn from_usage(u: &'help str) -> Self { - UsageParser::from_usage(u).parse() - } - - /// Deprecated, replaced with [`Arg::required_unless_present`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`") - )] - #[doc(hidden)] - #[must_use] - pub fn required_unless(self, arg_id: T) -> Self { - self.required_unless_present(arg_id) - } - - /// Deprecated, replaced with [`Arg::required_unless_present_all`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `Arg::required_unless_present_all`" - ) - )] - #[doc(hidden)] - #[must_use] - pub fn required_unless_all(self, names: I) -> Self - where - I: IntoIterator, - T: Key, - { - self.required_unless_present_all(names) - } - - /// Deprecated, replaced with [`Arg::required_unless_present_any`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `Arg::required_unless_present_any`" - ) - )] - #[doc(hidden)] - #[must_use] - pub fn required_unless_one(self, names: I) -> Self - where - I: IntoIterator, - T: Key, - { - self.required_unless_present_any(names) - } - - /// Deprecated, replaced with [`Arg::required_if_eq`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`") - )] - #[doc(hidden)] - #[must_use] - pub fn required_if(self, arg_id: T, val: &'help str) -> Self { - self.required_if_eq(arg_id, val) - } - - /// Deprecated, replaced with [`Arg::required_if_eq_any`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`") - )] - #[doc(hidden)] - #[must_use] - pub fn required_ifs(self, ifs: &[(T, &'help str)]) -> Self { - self.required_if_eq_any(ifs) - } - - /// Deprecated, replaced with [`Arg::hide`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`") - )] - #[doc(hidden)] - #[inline] - #[must_use] - pub fn hidden(self, yes: bool) -> Self { - self.hide(yes) - } - - /// Deprecated, replaced with [`Arg::ignore_case`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`") - )] - #[doc(hidden)] - #[inline] - #[must_use] - pub fn case_insensitive(self, yes: bool) -> Self { - self.ignore_case(yes) - } - - /// Deprecated, replaced with [`Arg::forbid_empty_values`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`") - )] - #[doc(hidden)] - #[must_use] - pub fn empty_values(self, yes: bool) -> Self { - self.forbid_empty_values(!yes) - } - - /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and - /// [`Arg::multiple_values`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" - ) - )] - #[doc(hidden)] - #[must_use] - pub fn multiple(self, yes: bool) -> Self { - self.multiple_occurrences(yes).multiple_values(yes) - } - - /// Deprecated, replaced with [`Arg::hide_short_help`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`") - )] - #[doc(hidden)] - #[inline] - #[must_use] - pub fn hidden_short_help(self, yes: bool) -> Self { - self.hide_short_help(yes) - } - - /// Deprecated, replaced with [`Arg::hide_long_help`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`") - )] - #[doc(hidden)] - #[inline] - #[must_use] - pub fn hidden_long_help(self, yes: bool) -> Self { - self.hide_long_help(yes) - } - - /// Deprecated, replaced with [`Arg::setting`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`") - )] - #[doc(hidden)] - #[must_use] - pub fn set(self, s: ArgSettings) -> Self { - self.setting(s) - } - - /// Deprecated, replaced with [`Arg::unset_setting`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`") - )] - #[doc(hidden)] - #[must_use] - pub fn unset(self, s: ArgSettings) -> Self { - self.unset_setting(s) - } -} - -/// # Internally used only -impl<'help> Arg<'help> { - pub(crate) fn _build(&mut self) { - if self.is_positional() { - self.settings.set(ArgSettings::TakesValue); - } - if let Some(action) = self.action.as_ref() { - if let Some(default_value) = action.default_value() { - if self.default_vals.is_empty() { - self.default_vals = vec![default_value]; - } - } - if action.takes_values() { - self.settings.set(ArgSettings::TakesValue); - } else { - self.settings.unset(ArgSettings::TakesValue); - } - match action { - ArgAction::StoreValue - | ArgAction::IncOccurrence - | ArgAction::Help - | ArgAction::Version => {} - ArgAction::Set - | ArgAction::Append - | ArgAction::SetTrue - | ArgAction::SetFalse - | ArgAction::Count => { - if !self.is_positional() { - self.settings.set(ArgSettings::MultipleOccurrences); - } - } - } - } - - if self.value_parser.is_none() { - if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { - self.value_parser = Some(default); - } else if self.is_allow_invalid_utf8_set() { - self.value_parser = Some(super::ValueParser::os_string()); - } else { - self.value_parser = Some(super::ValueParser::string()); - } - } - - if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set()) - && self.val_delim.is_none() - { - self.val_delim = Some(','); - } - - let val_names_len = self.val_names.len(); - - if val_names_len > 1 { - self.settings.set(ArgSettings::MultipleValues); - - if self.num_vals.is_none() { - self.num_vals = Some(val_names_len); - } - } - - let self_id = self.id.clone(); - if self.is_positional() || self.is_multiple_occurrences_set() { - // Remove self-overrides where they don't make sense. - // - // We can evaluate switching this to a debug assert at a later time (though it will - // require changing propagation of `AllArgsOverrideSelf`). Being conservative for now - // due to where we are at in the release. - self.overrides.retain(|e| *e != self_id); - } - } - - pub(crate) fn generated(mut self) -> Self { - self.provider = ArgProvider::Generated; - self - } - - pub(crate) fn longest_filter(&self) -> bool { - self.is_takes_value_set() || self.long.is_some() || self.short.is_none() - } - - // Used for positionals when printing - pub(crate) fn multiple_str(&self) -> &str { - let mult_vals = self.val_names.len() > 1; - if (self.is_multiple_values_set() || self.is_multiple_occurrences_set()) && !mult_vals { - "..." - } else { - "" - } - } - - // Used for positionals when printing - pub(crate) fn name_no_brackets(&self) -> Cow { - debug!("Arg::name_no_brackets:{}", self.name); - let delim = if self.is_require_value_delimiter_set() { - self.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - } - .to_string(); - if !self.val_names.is_empty() { - debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); - - if self.val_names.len() > 1 { - Cow::Owned( - self.val_names - .iter() - .map(|n| format!("<{}>", n)) - .collect::>() - .join(&*delim), - ) - } else { - Cow::Borrowed(self.val_names.get(0).expect(INTERNAL_ERROR_MSG)) - } - } else { - debug!("Arg::name_no_brackets: just name"); - Cow::Borrowed(self.name) - } - } - - /// Either multiple values or occurrences - pub(crate) fn is_multiple(&self) -> bool { - self.is_multiple_values_set() | self.is_multiple_occurrences_set() - } - - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.get_explicit() - } -} - -impl<'help> From<&'_ Arg<'help>> for Arg<'help> { - fn from(a: &Arg<'help>) -> Self { - a.clone() - } -} - -impl<'help> PartialEq for Arg<'help> { - fn eq(&self, other: &Arg<'help>) -> bool { - self.name == other.name - } -} - -impl<'help> PartialOrd for Arg<'help> { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl<'help> Ord for Arg<'help> { - fn cmp(&self, other: &Arg) -> Ordering { - self.name.cmp(other.name) - } -} - -impl<'help> Eq for Arg<'help> {} - -impl<'help> Display for Arg<'help> { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // Write the name such --long or -l - if let Some(l) = self.long { - write!(f, "--{}", l)?; - } else if let Some(s) = self.short { - write!(f, "-{}", s)?; - } - let mut need_closing_bracket = false; - if !self.is_positional() && self.is_takes_value_set() { - let is_optional_val = self.min_vals == Some(0); - let sep = if self.is_require_equals_set() { - if is_optional_val { - need_closing_bracket = true; - "[=" - } else { - "=" - } - } else if is_optional_val { - need_closing_bracket = true; - " [" - } else { - " " - }; - f.write_str(sep)?; - } - if self.is_takes_value_set() || self.is_positional() { - display_arg_val(self, |s, _| f.write_str(s))?; - } - if need_closing_bracket { - f.write_str("]")?; - } - - Ok(()) - } -} - -impl<'help> fmt::Debug for Arg<'help> { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - let mut ds = f.debug_struct("Arg"); - - #[allow(unused_mut)] - let mut ds = ds - .field("id", &self.id) - .field("provider", &self.provider) - .field("name", &self.name) - .field("help", &self.help) - .field("long_help", &self.long_help) - .field("action", &self.action) - .field("value_parser", &self.value_parser) - .field("blacklist", &self.blacklist) - .field("settings", &self.settings) - .field("overrides", &self.overrides) - .field("groups", &self.groups) - .field("requires", &self.requires) - .field("r_ifs", &self.r_ifs) - .field("r_unless", &self.r_unless) - .field("short", &self.short) - .field("long", &self.long) - .field("aliases", &self.aliases) - .field("short_aliases", &self.short_aliases) - .field("disp_ord", &self.disp_ord) - .field("possible_vals", &self.possible_vals) - .field("val_names", &self.val_names) - .field("num_vals", &self.num_vals) - .field("max_vals", &self.max_vals) - .field("min_vals", &self.min_vals) - .field( - "validator", - &self.validator.as_ref().map_or("None", |_| "Some(FnMut)"), - ) - .field( - "validator_os", - &self.validator_os.as_ref().map_or("None", |_| "Some(FnMut)"), - ) - .field("val_delim", &self.val_delim) - .field("default_vals", &self.default_vals) - .field("default_vals_ifs", &self.default_vals_ifs) - .field("terminator", &self.terminator) - .field("index", &self.index) - .field("help_heading", &self.help_heading) - .field("value_hint", &self.value_hint) - .field("default_missing_vals", &self.default_missing_vals); - - #[cfg(feature = "env")] - { - ds = ds.field("env", &self.env); - } - - ds.finish() - } -} - -type Validator<'a> = dyn FnMut(&str) -> Result<(), Box> + Send + 'a; -type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box> + Send + 'a; - -#[derive(Debug, Clone, Eq, PartialEq)] -pub(crate) enum ArgProvider { - Generated, - GeneratedMutated, - User, -} - -impl Default for ArgProvider { - fn default() -> Self { - ArgProvider::User - } -} - -/// Write the values such as -pub(crate) fn display_arg_val(arg: &Arg, mut write: F) -> Result<(), E> -where - F: FnMut(&str, bool) -> Result, -{ - let mult_val = arg.is_multiple_values_set(); - let mult_occ = arg.is_multiple_occurrences_set(); - let delim = if arg.is_require_value_delimiter_set() { - arg.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - } - .to_string(); - if !arg.val_names.is_empty() { - // If have val_name. - match (arg.val_names.len(), arg.num_vals) { - (1, Some(num_vals)) => { - // If single value name with multiple num_of_vals, display all - // the values with the single value name. - let arg_name = format!("<{}>", arg.val_names.get(0).unwrap()); - for n in 1..=num_vals { - write(&arg_name, true)?; - if n != num_vals { - write(&delim, false)?; - } - } - } - (num_val_names, _) => { - // If multiple value names, display them sequentially(ignore num of vals). - let mut it = arg.val_names.iter().peekable(); - while let Some(val) = it.next() { - write(&format!("<{}>", val), true)?; - if it.peek().is_some() { - write(&delim, false)?; - } - } - if (num_val_names == 1 && mult_val) - || (arg.is_positional() && mult_occ) - || num_val_names < arg.num_vals.unwrap_or(0) - { - write("...", true)?; - } - } - } - } else if let Some(num_vals) = arg.num_vals { - // If number_of_values is specified, display the value multiple times. - let arg_name = format!("<{}>", arg.name); - for n in 1..=num_vals { - write(&arg_name, true)?; - if n != num_vals { - write(&delim, false)?; - } - } - } else if arg.is_positional() { - // Value of positional argument with no num_vals and val_names. - write(&format!("<{}>", arg.name), true)?; - - if mult_val || mult_occ { - write("...", true)?; - } - } else { - // value of flag argument with no num_vals and val_names. - write(&format!("<{}>", arg.name), true)?; - if mult_val { - write("...", true)?; - } - } - Ok(()) -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub(crate) enum DisplayOrder { - None, - Implicit(usize), - Explicit(usize), -} - -impl DisplayOrder { - pub(crate) fn set_explicit(&mut self, explicit: usize) { - *self = Self::Explicit(explicit) - } - - pub(crate) fn set_implicit(&mut self, implicit: usize) { - *self = (*self).max(Self::Implicit(implicit)) - } - - pub(crate) fn make_explicit(&mut self) { - match *self { - Self::None | Self::Explicit(_) => {} - Self::Implicit(disp) => self.set_explicit(disp), - } - } - - pub(crate) fn get_explicit(self) -> usize { - match self { - Self::None | Self::Implicit(_) => 999, - Self::Explicit(disp) => disp, - } - } -} - -impl Default for DisplayOrder { - fn default() -> Self { - Self::None - } -} - -// Flags -#[cfg(test)] -mod test { - use super::Arg; - - #[test] - fn flag_display() { - let mut f = Arg::new("flg").multiple_occurrences(true); - f.long = Some("flag"); - - assert_eq!(f.to_string(), "--flag"); - - let mut f2 = Arg::new("flg"); - f2.short = Some('f'); - - assert_eq!(f2.to_string(), "-f"); - } - - #[test] - fn flag_display_single_alias() { - let mut f = Arg::new("flg"); - f.long = Some("flag"); - f.aliases = vec![("als", true)]; - - assert_eq!(f.to_string(), "--flag") - } - - #[test] - fn flag_display_multiple_aliases() { - let mut f = Arg::new("flg"); - f.short = Some('f'); - f.aliases = vec![ - ("alias_not_visible", false), - ("f2", true), - ("f3", true), - ("f4", true), - ]; - assert_eq!(f.to_string(), "-f"); - } - - #[test] - fn flag_display_single_short_alias() { - let mut f = Arg::new("flg"); - f.short = Some('a'); - f.short_aliases = vec![('b', true)]; - - assert_eq!(f.to_string(), "-a") - } - - #[test] - fn flag_display_multiple_short_aliases() { - let mut f = Arg::new("flg"); - f.short = Some('a'); - f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; - assert_eq!(f.to_string(), "-a"); - } - - // Options - - #[test] - fn option_display_multiple_occurrences() { - let o = Arg::new("opt") - .long("option") - .takes_value(true) - .multiple_occurrences(true); - - assert_eq!(o.to_string(), "--option "); - } - - #[test] - fn option_display_multiple_values() { - let o = Arg::new("opt") - .long("option") - .takes_value(true) - .multiple_values(true); - - assert_eq!(o.to_string(), "--option ..."); - } - - #[test] - fn option_display2() { - let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]); - - assert_eq!(o2.to_string(), "-o "); - } - - #[test] - fn option_display3() { - let o2 = Arg::new("opt") - .short('o') - .takes_value(true) - .multiple_values(true) - .value_names(&["file", "name"]); - - assert_eq!(o2.to_string(), "-o "); - } - - #[test] - fn option_display_single_alias() { - let o = Arg::new("opt") - .takes_value(true) - .long("option") - .visible_alias("als"); - - assert_eq!(o.to_string(), "--option "); - } - - #[test] - fn option_display_multiple_aliases() { - let o = Arg::new("opt") - .long("option") - .takes_value(true) - .visible_aliases(&["als2", "als3", "als4"]) - .alias("als_not_visible"); - - assert_eq!(o.to_string(), "--option "); - } - - #[test] - fn option_display_single_short_alias() { - let o = Arg::new("opt") - .takes_value(true) - .short('a') - .visible_short_alias('b'); - - assert_eq!(o.to_string(), "-a "); - } - - #[test] - fn option_display_multiple_short_aliases() { - let o = Arg::new("opt") - .short('a') - .takes_value(true) - .visible_short_aliases(&['b', 'c', 'd']) - .short_alias('e'); - - assert_eq!(o.to_string(), "-a "); - } - - // Positionals - - #[test] - fn positional_display_multiple_values() { - let p = Arg::new("pos") - .index(1) - .takes_value(true) - .multiple_values(true); - - assert_eq!(p.to_string(), "..."); - } - - #[test] - fn positional_display_multiple_occurrences() { - let p = Arg::new("pos") - .index(1) - .takes_value(true) - .multiple_occurrences(true); - - assert_eq!(p.to_string(), "..."); - } - - #[test] - fn positional_display_required() { - let p2 = Arg::new("pos").index(1).required(true); - - assert_eq!(p2.to_string(), ""); - } - - #[test] - fn positional_display_val_names() { - let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]); - - assert_eq!(p2.to_string(), " "); - } - - #[test] - fn positional_display_val_names_req() { - let p2 = Arg::new("pos") - .index(1) - .required(true) - .value_names(&["file1", "file2"]); - - assert_eq!(p2.to_string(), " "); - } -} diff --git a/vendor/clap/src/builder/arg_group.rs b/vendor/clap/src/builder/arg_group.rs deleted file mode 100644 index 0fe317109..000000000 --- a/vendor/clap/src/builder/arg_group.rs +++ /dev/null @@ -1,633 +0,0 @@ -// Internal -use crate::util::{Id, Key}; - -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -/// Family of related [arguments]. -/// -/// By placing arguments in a logical group, you can create easier requirement and -/// exclusion rules instead of having to list each argument individually, or when you want a rule -/// to apply "any but not all" arguments. -/// -/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is -/// set, this means that at least one argument from that group must be present. If -/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. -/// -/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for -/// another argument, meaning any of the arguments that belong to that group will cause a failure -/// if present, or must be present respectively. -/// -/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -/// present out of a given set. Imagine that you had multiple arguments, and you want one of them -/// to be required, but making all of them required isn't feasible because perhaps they conflict -/// with each other. For example, lets say that you were building an application where one could -/// set a given version number by supplying a string with an option argument, i.e. -/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number -/// and simply incrementing one of the three numbers. So you create three flags `--major`, -/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to -/// specify that *at least one* of them is used. For this, you can create a group. -/// -/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care -/// exactly which argument was actually used at runtime. -/// -/// # Examples -/// -/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of -/// the arguments from the specified group is present at runtime. -/// -/// ```rust -/// # use clap::{Command, arg, ArgGroup, ErrorKind}; -/// let result = Command::new("cmd") -/// .arg(arg!(--"set-ver" "set the version manually").required(false)) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(&["set-ver", "major", "minor", "patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); -/// // Because we used two args in the group it's an error -/// assert!(result.is_err()); -/// let err = result.unwrap_err(); -/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); -/// ``` -/// This next example shows a passing parse of the same scenario -/// -/// ```rust -/// # use clap::{Command, arg, ArgGroup}; -/// let result = Command::new("cmd") -/// .arg(arg!(--"set-ver" "set the version manually").required(false)) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(&["set-ver", "major", "minor","patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major"]); -/// assert!(result.is_ok()); -/// let matches = result.unwrap(); -/// // We may not know which of the args was used, so we can test for the group... -/// assert!(matches.contains_id("vers")); -/// // we could also alternatively check each arg individually (not shown here) -/// ``` -/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() -/// -/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() -/// [arguments]: crate::Arg -/// [conflict]: crate::Arg::conflicts_with() -/// [requirement]: crate::Arg::requires() -#[derive(Default, Debug, PartialEq, Eq)] -pub struct ArgGroup<'help> { - pub(crate) id: Id, - pub(crate) name: &'help str, - pub(crate) args: Vec, - pub(crate) required: bool, - pub(crate) requires: Vec, - pub(crate) conflicts: Vec, - pub(crate) multiple: bool, -} - -impl<'help> ArgGroup<'help> { - pub(crate) fn with_id(id: Id) -> Self { - ArgGroup { - id, - ..ArgGroup::default() - } - } - - /// Create a `ArgGroup` using a unique name. - /// - /// The name will be used to get values from the group or refer to the group inside of conflict - /// and requirement rules. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::new("config") - /// # ; - /// ``` - pub fn new>(n: S) -> Self { - ArgGroup::default().id(n) - } - - /// Sets the group name. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::default().name("config") - /// # ; - /// ``` - #[must_use] - pub fn id>(mut self, n: S) -> Self { - self.name = n.into(); - self.id = Id::from(self.name); - self - } - - /// Deprecated, replaced with [`ArgGroup::id`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `ArgGroup::id`") - )] - pub fn name>(self, n: S) -> Self { - self.id(n) - } - - /// Adds an [argument] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .group(ArgGroup::new("req_flags") - /// .arg("flag") - /// .arg("color")) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [argument]: crate::Arg - #[must_use] - pub fn arg(mut self, arg_id: T) -> Self { - self.args.push(arg_id.into()); - self - } - - /// Adds multiple [arguments] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"])) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [arguments]: crate::Arg - #[must_use] - pub fn args(mut self, ns: &[T]) -> Self { - for n in ns { - self = self.arg(n); - } - self - } - - /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) - /// - /// # Examples - /// - /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the - /// group - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .multiple(true)) - /// .get_matches_from(vec!["myprog", "-f", "-c"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// ``` - /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw - /// an error if more than one of the args in the group was used. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"])) - /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); - /// // Because we used both args in the group it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg`]: crate::Arg - #[inline] - #[must_use] - pub fn multiple(mut self, yes: bool) -> Self { - self.multiple = yes; - self - } - - /// Require an argument from the group to be present when parsing. - /// - /// This is unless conflicting with another argument. A required group will be displayed in - /// the usage string of the application in the format ``. - /// - /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not - /// globally. - /// - /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with - /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. - /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which - /// states, '*At least* one arg from this group must be used. Using multiple is OK." - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .required(true)) - /// .try_get_matches_from(vec!["myprog"]); - /// // Because we didn't use any of the args in the group, it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`ArgGroup::multiple`]: ArgGroup::multiple() - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn required(mut self, yes: bool) -> Self { - self.required = yes; - self - } - - /// Specify an argument or group that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when any one of the arguments from this group is used. - /// - /// **NOTE:** The name provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .arg(Arg::new("debug") - /// .short('d')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .requires("debug")) - /// .try_get_matches_from(vec!["myprog", "-c"]); - /// // because we used an arg from the group, and the group requires "-d" to be used, it's an - /// // error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires() - #[must_use] - pub fn requires(mut self, id: T) -> Self { - self.requires.push(id.into()); - self - } - - /// Specify arguments or groups that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when one of the arguments from this group is used. - /// - /// **NOTE:** The names provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .arg(Arg::new("debug") - /// .short('d')) - /// .arg(Arg::new("verb") - /// .short('v')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .requires_all(&["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, - /// // yet we only used "-d" it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires_all() - #[must_use] - pub fn requires_all(mut self, ns: &[&'help str]) -> Self { - for n in ns { - self = self.requires(n); - } - self - } - - /// Specify an argument or group that must **not** be present when this group is. - /// - /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name - /// other arguments or groups that must *not* be present when one of the arguments from this - /// group are used. - /// - /// **NOTE:** The name provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .arg(Arg::new("debug") - /// .short('d')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .conflicts_with("debug")) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group conflicts with "-d", it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [argument exclusion rules]: crate::Arg::conflicts_with() - #[must_use] - pub fn conflicts_with(mut self, id: T) -> Self { - self.conflicts.push(id.into()); - self - } - - /// Specify arguments or groups that must **not** be present when this group is. - /// - /// Exclusion rules function just like [argument exclusion rules], you can name other arguments - /// or groups that must *not* be present when one of the arguments from this group are used. - /// - /// **NOTE:** The names provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("color") - /// .short('c')) - /// .arg(Arg::new("debug") - /// .short('d')) - /// .arg(Arg::new("verb") - /// .short('v')) - /// .group(ArgGroup::new("req_flags") - /// .args(&["flag", "color"]) - /// .conflicts_with_all(&["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); - /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" - /// // it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [argument exclusion rules]: crate::Arg::conflicts_with_all() - #[must_use] - pub fn conflicts_with_all(mut self, ns: &[&'help str]) -> Self { - for n in ns { - self = self.conflicts_with(n); - } - self - } - - /// Deprecated, replaced with [`ArgGroup::new`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgGroup::new`") - )] - #[doc(hidden)] - pub fn with_name>(n: S) -> Self { - Self::new(n) - } - - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - #[cfg(feature = "yaml")] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Maybe clap::Parser would fit your use case? (Issue #3087)" - ) - )] - #[doc(hidden)] - pub fn from_yaml(yaml: &'help Yaml) -> Self { - Self::from(yaml) - } -} - -impl<'help> From<&'_ ArgGroup<'help>> for ArgGroup<'help> { - fn from(g: &ArgGroup<'help>) -> Self { - ArgGroup { - id: g.id.clone(), - name: g.name, - required: g.required, - args: g.args.clone(), - requires: g.requires.clone(), - conflicts: g.conflicts.clone(), - multiple: g.multiple, - } - } -} - -/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? -#[cfg(feature = "yaml")] -impl<'help> From<&'help Yaml> for ArgGroup<'help> { - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - fn from(y: &'help Yaml) -> Self { - let b = y.as_hash().expect("ArgGroup::from:: expects a table"); - // We WANT this to panic on error...so expect() is good. - let mut a = ArgGroup::default(); - let group_settings = if b.len() == 1 { - let name_yaml = b.keys().next().expect("failed to get name"); - let name_str = name_yaml - .as_str() - .expect("failed to convert arg YAML name to str"); - a.name = name_str; - a.id = Id::from(&a.name); - b.get(name_yaml) - .expect("failed to get name_str") - .as_hash() - .expect("failed to convert to a hash") - } else { - b - }; - - for (k, v) in group_settings { - a = match k.as_str().unwrap() { - "required" => a.required(v.as_bool().unwrap()), - "multiple" => a.multiple(v.as_bool().unwrap()), - "args" => yaml_vec_or_str!(a, v, arg), - "arg" => { - if let Some(ys) = v.as_str() { - a = a.arg(ys); - } - a - } - "requires" => yaml_vec_or_str!(a, v, requires), - "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), - "name" => { - if let Some(ys) = v.as_str() { - a = a.id(ys); - } - a - } - s => panic!( - "Unknown ArgGroup setting '{}' in YAML file for \ - ArgGroup '{}'", - s, a.name - ), - } - } - - a - } -} - -#[cfg(test)] -mod test { - use super::ArgGroup; - #[cfg(feature = "yaml")] - use yaml_rust::YamlLoader; - - #[test] - fn groups() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(&["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(&["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(&["r2", "r3"]) - .requires("r4"); - - let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - assert_eq!(g.args, args); - assert_eq!(g.requires, reqs); - assert_eq!(g.conflicts, confs); - } - - #[test] - fn test_from() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(&["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(&["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(&["r2", "r3"]) - .requires("r4"); - - let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - let g2 = ArgGroup::from(&g); - assert_eq!(g2.args, args); - assert_eq!(g2.requires, reqs); - assert_eq!(g2.conflicts, confs); - } - - #[cfg(feature = "yaml")] - #[test] - fn test_yaml() { - let g_yaml = "name: test -args: -- a1 -- a4 -- a2 -- a3 -conflicts_with: -- c1 -- c2 -- c3 -- c4 -requires: -- r1 -- r2 -- r3 -- r4"; - let yaml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; - let g = ArgGroup::from(yaml); - let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - assert_eq!(g.args, args); - assert_eq!(g.requires, reqs); - assert_eq!(g.conflicts, confs); - } - - // This test will *fail to compile* if ArgGroup is not Send + Sync - #[test] - fn arg_group_send_sync() { - fn foo(_: T) {} - foo(ArgGroup::new("test")) - } -} - -impl Clone for ArgGroup<'_> { - fn clone(&self) -> Self { - ArgGroup { - id: self.id.clone(), - name: self.name, - required: self.required, - args: self.args.clone(), - requires: self.requires.clone(), - conflicts: self.conflicts.clone(), - multiple: self.multiple, - } - } -} diff --git a/vendor/clap/src/builder/arg_predicate.rs b/vendor/clap/src/builder/arg_predicate.rs deleted file mode 100644 index 58eb5494c..000000000 --- a/vendor/clap/src/builder/arg_predicate.rs +++ /dev/null @@ -1,14 +0,0 @@ -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum ArgPredicate<'help> { - IsPresent, - Equals(&'help std::ffi::OsStr), -} - -impl<'help> From> for ArgPredicate<'help> { - fn from(other: Option<&'help std::ffi::OsStr>) -> Self { - match other { - Some(other) => Self::Equals(other), - None => Self::IsPresent, - } - } -} diff --git a/vendor/clap/src/builder/arg_settings.rs b/vendor/clap/src/builder/arg_settings.rs deleted file mode 100644 index 3b7faf7bf..000000000 --- a/vendor/clap/src/builder/arg_settings.rs +++ /dev/null @@ -1,457 +0,0 @@ -#![allow(deprecated)] - -// Std -use std::ops::BitOr; -#[cfg(feature = "yaml")] -use std::str::FromStr; - -// Third party -use bitflags::bitflags; - -#[allow(unused)] -use crate::Arg; - -#[doc(hidden)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ArgFlags(Flags); - -impl Default for ArgFlags { - fn default() -> Self { - Self::empty() - } -} - -/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter -/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the -/// [`Arg`] methods which accept a `bool` use internally. -/// -/// [`Arg`]: crate::Arg -/// [`Arg::setting`]: crate::Arg::setting() -/// [`Arg::unset_setting`]: crate::Arg::unset_setting() -/// [`Arg::is_set`]: crate::Arg::is_set() -#[derive(Debug, PartialEq, Copy, Clone)] -#[non_exhaustive] -pub enum ArgSettings { - /// Deprecated, replaced with [`Arg::required`] and [`Arg::is_required_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::required` and `Arg::is_required_set`" - ) - )] - Required, - /// Deprecated, replaced with [`Arg::multiple_values`] and [`Arg::is_multiple_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::multiple_values` and `Arg::`is_multiple_values_set`" - ) - )] - MultipleValues, - /// Deprecated, replaced with [`Arg::multiple_occurrences`] and - /// [`Arg::is_multiple_occurrences_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::multiple_occurrences` and `Arg::is_multiple_occurrences_set`" - ) - )] - MultipleOccurrences, - /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and - /// [`ArgSettings::MultipleValues`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Split into `ArgSettings::MultipleOccurrences` (most likely what you want) and `ArgSettings::MultipleValues`" - ) - )] - #[doc(hidden)] - Multiple, - /// Deprecated, replaced with [`Arg::forbid_empty_values`] and - /// [`Arg::is_forbid_empty_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::forbid_empty_values` and `Arg::is_forbid_empty_values_set`" - ) - )] - ForbidEmptyValues, - /// Deprecated, replaced with [`Arg::global`] and [`Arg::is_global_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::global` and `Arg::is_global_set`" - ) - )] - Global, - /// Deprecated, replaced with [`Arg::hide`] and [`Arg::is_hide_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide` and `Arg::is_hide_set`" - ) - )] - Hidden, - /// Deprecated, replaced with [`Arg::takes_value`] and [`Arg::is_takes_value_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::takes_value` and `Arg::is_takes_value_set`" - ) - )] - TakesValue, - /// Deprecated, replaced with [`Arg::use_value_delimiter`] and - /// [`Arg::is_use_value_delimiter_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::use_value_delimiter` and `Arg::is_use_value_delimiter_set`" - ) - )] - UseValueDelimiter, - /// Deprecated, replaced with [`Arg::next_line_help`] and [`Arg::is_next_line_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::next_line_help` and `Arg::is_next_line_help_set`" - ) - )] - NextLineHelp, - /// Deprecated, replaced with [`Arg::require_value_delimiter`] and - /// [`Arg::is_require_value_delimiter_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::require_value_delimiter` and `Arg::is_require_value_delimiter_set`" - ) - )] - RequireDelimiter, - /// Deprecated, replaced with [`Arg::hide_possible_values`] and - /// [`Arg::is_hide_possible_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_possible_values` and `Arg::is_hide_possible_values_set`" - ) - )] - HidePossibleValues, - /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and - /// [`Arg::is_allow_hyphen_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" - ) - )] - AllowHyphenValues, - /// Deprecated, replaced with [`ArgSettings::AllowHyphenValues`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `ArgSettings::AllowHyphenValues`" - ) - )] - #[doc(hidden)] - AllowLeadingHyphen, - /// Deprecated, replaced with [`Arg::require_equals`] and [`Arg::is_require_equals_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::require_equals` and `Arg::is_require_equals_set`" - ) - )] - RequireEquals, - /// Deprecated, replaced with [`Arg::last`] and [`Arg::is_last_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::last` and `Arg::is_last_set`" - ) - )] - Last, - /// Deprecated, replaced with [`Arg::hide_default_value`] and [`Arg::is_hide_default_value_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_default_value` and `Arg::is_hide_default_value_set`" - ) - )] - HideDefaultValue, - /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`" - ) - )] - IgnoreCase, - /// Deprecated, replaced with [`ArgSettings::IgnoreCase`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgSettings::IgnoreCase`") - )] - #[doc(hidden)] - CaseInsensitive, - /// Deprecated, replaced with [`Arg::hide_env`] and [`Arg::is_hide_env_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_env` and `Arg::is_hide_env_set`" - ) - )] - #[cfg(feature = "env")] - HideEnv, - /// Deprecated, replaced with [`Arg::hide_env_values`] and [`Arg::is_hide_env_values_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_env_values` and `Arg::is_hide_env_values_set`" - ) - )] - #[cfg(feature = "env")] - HideEnvValues, - /// Deprecated, replaced with [`Arg::hide_short_help`] and [`Arg::is_hide_short_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_short_help` and `Arg::is_hide_short_help_set`" - ) - )] - HiddenShortHelp, - /// Deprecated, replaced with [`Arg::hide_long_help`] and [`Arg::is_hide_long_help_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::hide_long_help` and `Arg::is_hide_long_help_set`" - ) - )] - HiddenLongHelp, - /// Deprecated, replaced with [`Arg::allow_invalid_utf8`] and [`Arg::is_allow_invalid_utf8_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::allow_invalid_utf8` and `Arg::is_allow_invalid_utf8_set`" - ) - )] - AllowInvalidUtf8, - /// Deprecated, replaced with [`Arg::exclusive`] and [`Arg::is_exclusive_set`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::exclusive` and `Arg::is_exclusive_set`" - ) - )] - Exclusive, -} - -bitflags! { - struct Flags: u32 { - const REQUIRED = 1; - const MULTIPLE_OCC = 1 << 1; - const NO_EMPTY_VALS = 1 << 2; - const GLOBAL = 1 << 3; - const HIDDEN = 1 << 4; - const TAKES_VAL = 1 << 5; - const USE_DELIM = 1 << 6; - const NEXT_LINE_HELP = 1 << 7; - const REQ_DELIM = 1 << 9; - const DELIM_NOT_SET = 1 << 10; - const HIDE_POS_VALS = 1 << 11; - const ALLOW_TAC_VALS = 1 << 12; - const REQUIRE_EQUALS = 1 << 13; - const LAST = 1 << 14; - const HIDE_DEFAULT_VAL = 1 << 15; - const CASE_INSENSITIVE = 1 << 16; - #[cfg(feature = "env")] - const HIDE_ENV_VALS = 1 << 17; - const HIDDEN_SHORT_H = 1 << 18; - const HIDDEN_LONG_H = 1 << 19; - const MULTIPLE_VALS = 1 << 20; - const MULTIPLE = Self::MULTIPLE_OCC.bits | Self::MULTIPLE_VALS.bits; - #[cfg(feature = "env")] - const HIDE_ENV = 1 << 21; - const UTF8_NONE = 1 << 22; - const EXCLUSIVE = 1 << 23; - const NO_OP = 0; - } -} - -impl_settings! { ArgSettings, ArgFlags, - Required => Flags::REQUIRED, - MultipleOccurrences => Flags::MULTIPLE_OCC, - MultipleValues => Flags::MULTIPLE_VALS, - Multiple => Flags::MULTIPLE, - ForbidEmptyValues => Flags::NO_EMPTY_VALS, - Global => Flags::GLOBAL, - Hidden => Flags::HIDDEN, - TakesValue => Flags::TAKES_VAL, - UseValueDelimiter => Flags::USE_DELIM, - NextLineHelp => Flags::NEXT_LINE_HELP, - RequireDelimiter => Flags::REQ_DELIM, - HidePossibleValues => Flags::HIDE_POS_VALS, - AllowHyphenValues => Flags::ALLOW_TAC_VALS, - AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, - RequireEquals => Flags::REQUIRE_EQUALS, - Last => Flags::LAST, - IgnoreCase => Flags::CASE_INSENSITIVE, - CaseInsensitive => Flags::CASE_INSENSITIVE, - #[cfg(feature = "env")] - HideEnv => Flags::HIDE_ENV, - #[cfg(feature = "env")] - HideEnvValues => Flags::HIDE_ENV_VALS, - HideDefaultValue => Flags::HIDE_DEFAULT_VAL, - HiddenShortHelp => Flags::HIDDEN_SHORT_H, - HiddenLongHelp => Flags::HIDDEN_LONG_H, - AllowInvalidUtf8 => Flags::UTF8_NONE, - Exclusive => Flags::EXCLUSIVE -} - -/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? -#[cfg(feature = "yaml")] -impl FromStr for ArgSettings { - type Err = String; - fn from_str(s: &str) -> Result::Err> { - #[allow(deprecated)] - #[allow(unreachable_patterns)] - match &*s.to_ascii_lowercase() { - "required" => Ok(ArgSettings::Required), - "multipleoccurrences" => Ok(ArgSettings::MultipleOccurrences), - "multiplevalues" => Ok(ArgSettings::MultipleValues), - "multiple" => Ok(ArgSettings::Multiple), - "forbidemptyvalues" => Ok(ArgSettings::ForbidEmptyValues), - "global" => Ok(ArgSettings::Global), - "hidden" => Ok(ArgSettings::Hidden), - "takesvalue" => Ok(ArgSettings::TakesValue), - "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), - "nextlinehelp" => Ok(ArgSettings::NextLineHelp), - "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), - "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), - "allowhyphenvalues" => Ok(ArgSettings::AllowHyphenValues), - "allowleadinghypyhen" => Ok(ArgSettings::AllowLeadingHyphen), - "requireequals" => Ok(ArgSettings::RequireEquals), - "last" => Ok(ArgSettings::Last), - "ignorecase" => Ok(ArgSettings::IgnoreCase), - "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), - #[cfg(feature = "env")] - "hideenv" => Ok(ArgSettings::HideEnv), - #[cfg(feature = "env")] - "hideenvvalues" => Ok(ArgSettings::HideEnvValues), - "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), - "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), - "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), - "allowinvalidutf8" => Ok(ArgSettings::AllowInvalidUtf8), - "exclusive" => Ok(ArgSettings::Exclusive), - _ => Err(format!("unknown AppSetting: `{}`", s)), - } - } -} - -#[cfg(test)] -mod test { - #[test] - #[cfg(feature = "yaml")] - fn arg_settings_fromstr() { - use super::ArgSettings; - - assert_eq!( - "allowhyphenvalues".parse::().unwrap(), - ArgSettings::AllowHyphenValues - ); - assert_eq!( - "forbidemptyvalues".parse::().unwrap(), - ArgSettings::ForbidEmptyValues - ); - assert_eq!( - "hidepossiblevalues".parse::().unwrap(), - ArgSettings::HidePossibleValues - ); - assert_eq!( - "hidden".parse::().unwrap(), - ArgSettings::Hidden - ); - assert_eq!( - "nextlinehelp".parse::().unwrap(), - ArgSettings::NextLineHelp - ); - assert_eq!( - "requiredelimiter".parse::().unwrap(), - ArgSettings::RequireDelimiter - ); - assert_eq!( - "required".parse::().unwrap(), - ArgSettings::Required - ); - assert_eq!( - "takesvalue".parse::().unwrap(), - ArgSettings::TakesValue - ); - assert_eq!( - "usevaluedelimiter".parse::().unwrap(), - ArgSettings::UseValueDelimiter - ); - assert_eq!( - "requireequals".parse::().unwrap(), - ArgSettings::RequireEquals - ); - assert_eq!("last".parse::().unwrap(), ArgSettings::Last); - assert_eq!( - "hidedefaultvalue".parse::().unwrap(), - ArgSettings::HideDefaultValue - ); - assert_eq!( - "ignorecase".parse::().unwrap(), - ArgSettings::IgnoreCase - ); - #[cfg(feature = "env")] - assert_eq!( - "hideenv".parse::().unwrap(), - ArgSettings::HideEnv - ); - #[cfg(feature = "env")] - assert_eq!( - "hideenvvalues".parse::().unwrap(), - ArgSettings::HideEnvValues - ); - assert_eq!( - "hiddenshorthelp".parse::().unwrap(), - ArgSettings::HiddenShortHelp - ); - assert_eq!( - "hiddenlonghelp".parse::().unwrap(), - ArgSettings::HiddenLongHelp - ); - assert_eq!( - "allowinvalidutf8".parse::().unwrap(), - ArgSettings::AllowInvalidUtf8 - ); - assert_eq!( - "exclusive".parse::().unwrap(), - ArgSettings::Exclusive - ); - assert!("hahahaha".parse::().is_err()); - } -} diff --git a/vendor/clap/src/builder/command.rs b/vendor/clap/src/builder/command.rs deleted file mode 100644 index 1fcb64ecc..000000000 --- a/vendor/clap/src/builder/command.rs +++ /dev/null @@ -1,5109 +0,0 @@ -#![allow(deprecated)] - -// Std -use std::collections::HashMap; -use std::env; -use std::ffi::OsString; -use std::fmt; -use std::io; -use std::ops::Index; -use std::path::Path; - -// Third Party -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -// Internal -use crate::builder::app_settings::{AppFlags, AppSettings}; -use crate::builder::arg_settings::ArgSettings; -use crate::builder::{arg::ArgProvider, Arg, ArgGroup, ArgPredicate}; -use crate::error::ErrorKind; -use crate::error::Result as ClapResult; -use crate::mkeymap::MKeyMap; -use crate::output::fmt::Stream; -use crate::output::{fmt::Colorizer, Help, HelpWriter, Usage}; -use crate::parser::{ArgMatcher, ArgMatches, Parser}; -use crate::util::ChildGraph; -use crate::util::{color::ColorChoice, Id, Key}; -use crate::PossibleValue; -use crate::{Error, INTERNAL_ERROR_MSG}; - -#[cfg(debug_assertions)] -use crate::builder::debug_asserts::assert_app; - -/// Build a command-line interface. -/// -/// This includes defining arguments, subcommands, parser behavior, and help output. -/// Once all configuration is complete, -/// the [`Command::get_matches`] family of methods starts the runtime-parsing -/// process. These methods then return information about the user supplied -/// arguments (or lack thereof). -/// -/// When deriving a [`Parser`][crate::Parser], you can use -/// [`CommandFactory::command`][crate::CommandFactory::command] to access the -/// `Command`. -/// -/// - [Basic API][crate::App#basic-api] -/// - [Application-wide Settings][crate::App#application-wide-settings] -/// - [Command-specific Settings][crate::App#command-specific-settings] -/// - [Subcommand-specific Settings][crate::App#subcommand-specific-settings] -/// - [Reflection][crate::App#reflection] -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{Command, Arg}; -/// let m = Command::new("My Program") -/// .author("Me, me@mail.com") -/// .version("1.0.2") -/// .about("Explains in brief what the program does") -/// .arg( -/// Arg::new("in_file") -/// ) -/// .after_help("Longer explanation to appear after the options when \ -/// displaying the help information from --help or -h") -/// .get_matches(); -/// -/// // Your program logic starts here... -/// ``` -/// [`App::get_matches`]: Command::get_matches() -pub type Command<'help> = App<'help>; - -/// Deprecated, replaced with [`Command`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Command`") -)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct App<'help> { - id: Id, - name: String, - long_flag: Option<&'help str>, - short_flag: Option, - display_name: Option, - bin_name: Option, - author: Option<&'help str>, - version: Option<&'help str>, - long_version: Option<&'help str>, - about: Option<&'help str>, - long_about: Option<&'help str>, - before_help: Option<&'help str>, - before_long_help: Option<&'help str>, - after_help: Option<&'help str>, - after_long_help: Option<&'help str>, - aliases: Vec<(&'help str, bool)>, // (name, visible) - short_flag_aliases: Vec<(char, bool)>, // (name, visible) - long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible) - usage_str: Option<&'help str>, - usage_name: Option, - help_str: Option<&'help str>, - disp_ord: Option, - term_w: Option, - max_w: Option, - template: Option<&'help str>, - settings: AppFlags, - g_settings: AppFlags, - args: MKeyMap<'help>, - subcommands: Vec>, - replacers: HashMap<&'help str, &'help [&'help str]>, - groups: Vec>, - current_help_heading: Option<&'help str>, - current_disp_ord: Option, - subcommand_value_name: Option<&'help str>, - subcommand_heading: Option<&'help str>, -} - -/// # Basic API -impl<'help> App<'help> { - /// Creates a new instance of an `Command`. - /// - /// It is common, but not required, to use binary name as the `name`. This - /// name will only be displayed to the user when they request to print - /// version or help and usage information. - /// - /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// # ; - /// ``` - pub fn new>(name: S) -> Self { - /// The actual implementation of `new`, non-generic to save code size. - /// - /// If we don't do this rustc will unnecessarily generate multiple versions - /// of this code. - fn new_inner<'help>(name: String) -> App<'help> { - App { - id: Id::from(&*name), - name, - ..Default::default() - } - .arg( - Arg::new("help") - .long("help") - .help("Print help information") - .global(true) - .generated(), - ) - .arg( - Arg::new("version") - .long("version") - .help("Print version information") - .global(true) - .generated(), - ) - } - - new_inner(name.into()) - } - - /// Adds an [argument] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// // Adding a single "flag" argument with a short and help text, using Arg::new() - /// .arg( - /// Arg::new("debug") - /// .short('d') - /// .help("turns on debugging mode") - /// ) - /// // Adding a single "option" argument with a short, a long, and help text using the less - /// // verbose Arg::from() - /// .arg( - /// arg!(-c --config "Optionally sets a config file to use") - /// ) - /// # ; - /// ``` - /// [argument]: Arg - #[must_use] - pub fn arg>>(mut self, a: A) -> Self { - let mut arg = a.into(); - if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { - if !arg.is_positional() && arg.provider != ArgProvider::Generated { - let current = *current_disp_ord; - arg.disp_ord.set_implicit(current); - *current_disp_ord = current + 1; - } - } - - arg.help_heading.get_or_insert(self.current_help_heading); - self.args.push(arg); - self - } - - /// Adds multiple [arguments] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// .args(&[ - /// arg!("[debug] -d 'turns on debugging info'"), - /// Arg::new("input").help("the input file to use") - /// ]) - /// # ; - /// ``` - /// [arguments]: Arg - #[must_use] - pub fn args(mut self, args: I) -> Self - where - I: IntoIterator, - T: Into>, - { - let args = args.into_iter(); - let (lower, _) = args.size_hint(); - self.args.reserve(lower); - - for arg in args { - self = self.arg(arg); - } - self - } - - /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. - /// - /// This can be useful for modifying the auto-generated help or version arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// - /// let mut cmd = Command::new("foo") - /// .arg(Arg::new("bar") - /// .short('b')) - /// .mut_arg("bar", |a| a.short('B')); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); - /// - /// // Since we changed `bar`'s short to "B" this should err as there - /// // is no `-b` anymore, only `-B` - /// - /// assert!(res.is_err()); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); - /// assert!(res.is_ok()); - /// ``` - #[must_use] - pub fn mut_arg(mut self, arg_id: T, f: F) -> Self - where - F: FnOnce(Arg<'help>) -> Arg<'help>, - T: Key + Into<&'help str>, - { - let arg_id: &str = arg_id.into(); - let id = Id::from(arg_id); - - let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg { - id, - name: arg_id, - ..Arg::default() - }); - - if a.provider == ArgProvider::Generated { - a.provider = ArgProvider::GeneratedMutated; - } - - self.args.push(f(a)); - self - } - - /// Adds an [`ArgGroup`] to the application. - /// - /// [`ArgGroup`]s are a family of related arguments. - /// By placing them in a logical group, you can build easier requirement and exclusion rules. - /// - /// Example use cases: - /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* - /// one) argument from that group must be present at runtime. - /// - Name an [`ArgGroup`] as a conflict to another argument. - /// Meaning any of the arguments that belong to that group will cause a failure if present with - /// the conflicting argument. - /// - Ensure exclusion between arguments. - /// - Extract a value from a group instead of determining exactly which argument was used. - /// - /// # Examples - /// - /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, - /// of the arguments from the specified group is present at runtime. - /// - /// ```no_run - /// # use clap::{Command, arg, ArgGroup}; - /// Command::new("cmd") - /// .arg(arg!("--set-ver [ver] 'set the version manually'")) - /// .arg(arg!("--major 'auto increase major'")) - /// .arg(arg!("--minor 'auto increase minor'")) - /// .arg(arg!("--patch 'auto increase patch'")) - /// .group(ArgGroup::new("vers") - /// .args(&["set-ver", "major", "minor","patch"]) - /// .required(true)) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn group>>(mut self, group: G) -> Self { - self.groups.push(group.into()); - self - } - - /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, ArgGroup}; - /// Command::new("cmd") - /// .arg(arg!("--set-ver [ver] 'set the version manually'")) - /// .arg(arg!("--major 'auto increase major'")) - /// .arg(arg!("--minor 'auto increase minor'")) - /// .arg(arg!("--patch 'auto increase patch'")) - /// .arg(arg!("-c [FILE] 'a config file'")) - /// .arg(arg!("-i [IFACE] 'an interface'")) - /// .groups(&[ - /// ArgGroup::new("vers") - /// .args(&["set-ver", "major", "minor","patch"]) - /// .required(true), - /// ArgGroup::new("input") - /// .args(&["c", "i"]) - /// ]) - /// # ; - /// ``` - #[must_use] - pub fn groups(mut self, groups: I) -> Self - where - I: IntoIterator, - T: Into>, - { - for g in groups.into_iter() { - self = self.group(g.into()); - } - self - } - - /// Adds a subcommand to the list of valid possibilities. - /// - /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, - /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get - /// their own auto generated help, version, and usage. - /// - /// A subcommand's [`Command::name`] will be used for: - /// - The argument the user passes in - /// - Programmatically looking up the subcommand - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("config") - /// .about("Controls configuration features") - /// .arg(arg!(" 'Required configuration file to use'"))) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn subcommand>>(mut self, subcmd: S) -> Self { - self.subcommands.push(subcmd.into()); - self - } - - /// Adds multiple subcommands to the list of valid possibilities. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// # Command::new("myprog") - /// .subcommands( vec![ - /// Command::new("config").about("Controls configuration functionality") - /// .arg(Arg::new("config_file")), - /// Command::new("debug").about("Controls debug functionality")]) - /// # ; - /// ``` - /// [`IntoIterator`]: std::iter::IntoIterator - #[must_use] - pub fn subcommands(mut self, subcmds: I) -> Self - where - I: IntoIterator, - T: Into>, - { - for subcmd in subcmds.into_iter() { - self.subcommands.push(subcmd.into()); - } - self - } - - /// Catch problems earlier in the development cycle. - /// - /// Most error states are handled as asserts under the assumption they are programming mistake - /// and not something to handle at runtime. Rather than relying on tests (manual or automated) - /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those - /// asserts in a way convenient for running as a test. - /// - /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive - /// testing of your CLI. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// fn cmd() -> Command<'static> { - /// Command::new("foo") - /// .arg( - /// Arg::new("bar").short('b').action(ArgAction::SetTrue) - /// ) - /// } - /// - /// #[test] - /// fn verify_app() { - /// cmd().debug_assert(); - /// } - /// - /// fn main() { - /// let m = cmd().get_matches_from(vec!["foo", "-b"]); - /// println!("{}", *m.get_one::("bar").expect("defaulted by clap")); - /// } - /// ``` - pub fn debug_assert(mut self) { - self._build_all(); - } - - /// Custom error message for post-parsing validation - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let mut cmd = Command::new("myprog"); - /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); - /// ``` - pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { - Error::raw(kind, message).format(self) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`App::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() - #[inline] - pub fn get_matches(self) -> ArgMatches { - self.get_matches_from(&mut env::args_os()) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// Like [`App::get_matches`] but doesn't consume the `Command`. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let mut cmd = Command::new("myprog") - /// // Args and options go here... - /// ; - /// let matches = cmd.get_matches_mut(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`App::get_matches`]: Command::get_matches() - pub fn get_matches_mut(&mut self) -> ArgMatches { - self.try_get_matches_from_mut(&mut env::args_os()) - .unwrap_or_else(|e| e.exit()) - } - - /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a - /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call - /// [`Error::exit`] or perform a [`std::process::exit`]. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches() - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion - #[inline] - pub fn try_get_matches(self) -> ClapResult { - // Start the parsing - self.try_get_matches_from(&mut env::args_os()) - } - - /// Parse the specified arguments, exiting on failure. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches_from(arg_vec); - /// ``` - /// [`App::get_matches`]: Command::get_matches() - /// [`clap::Result`]: Result - /// [`Vec`]: std::vec::Vec - pub fn get_matches_from(mut self, itr: I) -> ArgMatches - where - I: IntoIterator, - T: Into + Clone, - { - self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { - drop(self); - e.exit() - }) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches_from(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`App::get_matches_from`]: Command::get_matches_from() - /// [`App::try_get_matches`]: Command::try_get_matches() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Error`]: crate::Error - /// [`Error::exit`]: crate::Error::exit() - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion - /// [`clap::Result`]: Result - pub fn try_get_matches_from(mut self, itr: I) -> ClapResult - where - I: IntoIterator, - T: Into + Clone, - { - self.try_get_matches_from_mut(itr) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// Like [`App::try_get_matches_from`] but doesn't consume the `Command`. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let mut cmd = Command::new("myprog"); - /// // Args and options go here... - /// let matches = cmd.try_get_matches_from_mut(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`App::try_get_matches_from`]: Command::try_get_matches_from() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - pub fn try_get_matches_from_mut(&mut self, itr: I) -> ClapResult - where - I: IntoIterator, - T: Into + Clone, - { - let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); - let mut cursor = raw_args.cursor(); - - if self.settings.is_set(AppSettings::Multicall) { - if let Some(argv0) = raw_args.next_os(&mut cursor) { - let argv0 = Path::new(&argv0); - if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { - // Stop borrowing command so we can get another mut ref to it. - let command = command.to_owned(); - debug!( - "Command::try_get_matches_from_mut: Parsed command {} from argv", - command - ); - - debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); - raw_args.insert(&cursor, &[&command]); - debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); - self.name.clear(); - self.bin_name = None; - return self._do_parse(&mut raw_args, cursor); - } - } - }; - - // Get the name of the program (argument 1 of env::args()) and determine the - // actual file - // that was used to execute the program. This is because a program called - // ./target/release/my_prog -a - // will have two arguments, './target/release/my_prog', '-a' but we don't want - // to display - // the full path when displaying help messages and such - if !self.settings.is_set(AppSettings::NoBinaryName) { - if let Some(name) = raw_args.next_os(&mut cursor) { - let p = Path::new(name); - - if let Some(f) = p.file_name() { - if let Some(s) = f.to_str() { - if self.bin_name.is_none() { - self.bin_name = Some(s.to_owned()); - } - } - } - } - } - - self._do_parse(&mut raw_args, cursor) - } - - /// Prints the short help message (`-h`) to [`io::stdout()`]. - /// - /// See also [`Command::print_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - pub fn print_help(&mut self) -> io::Result<()> { - self._build_self(); - let color = self.get_color(); - - let mut c = Colorizer::new(Stream::Stdout, color); - let usage = Usage::new(self); - Help::new(HelpWriter::Buffer(&mut c), self, &usage, false).write_help()?; - c.print() - } - - /// Prints the long help message (`--help`) to [`io::stdout()`]. - /// - /// See also [`Command::print_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_long_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - /// [`BufWriter`]: std::io::BufWriter - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn print_long_help(&mut self) -> io::Result<()> { - self._build_self(); - let color = self.get_color(); - - let mut c = Colorizer::new(Stream::Stdout, color); - let usage = Usage::new(self); - Help::new(HelpWriter::Buffer(&mut c), self, &usage, true).write_help()?; - c.print() - } - - /// Writes the short help message (`-h`) to a [`io::Write`] object. - /// - /// See also [`Command::write_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// cmd.write_help(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn write_help(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(); - - let usage = Usage::new(self); - Help::new(HelpWriter::Normal(w), self, &usage, false).write_help()?; - w.flush() - } - - /// Writes the long help message (`--help`) to a [`io::Write`] object. - /// - /// See also [`Command::write_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// cmd.write_long_help(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn write_long_help(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(); - - let usage = Usage::new(self); - Help::new(HelpWriter::Normal(w), self, &usage, true).write_help()?; - w.flush() - } - - /// Version message rendered as if the user ran `-V`. - /// - /// See also [`Command::render_long_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_version(&self) -> String { - self._render_version(false) - } - - /// Version message rendered as if the user ran `--version`. - /// - /// See also [`Command::render_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_long_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_long_version(&self) -> String { - self._render_version(true) - } - - /// Usage statement - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// println!("{}", cmd.render_usage()); - /// ``` - pub fn render_usage(&mut self) -> String { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - self._build_self(); - - Usage::new(self).create_usage_with_title(&[]) - } -} - -/// # Application-wide Settings -/// -/// These settings will apply to the top-level command and all subcommands, by default. Some -/// settings can be overridden in subcommands. -impl<'help> App<'help> { - /// Specifies that the parser should not assume the first argument passed is the binary name. - /// - /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see - /// [`Command::multicall`][App::multicall]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .no_binary_name(true) - /// .arg(arg!( ... "commands to run")) - /// .get_matches_from(vec!["command", "set"]); - /// - /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); - /// assert_eq!(cmds, ["command", "set"]); - /// ``` - /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() - #[inline] - pub fn no_binary_name(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NoBinaryName) - } else { - self.unset_global_setting(AppSettings::NoBinaryName) - } - } - - /// Try not to fail on parse errors, like missing option values. - /// - /// **Note:** Make sure you apply it as `global_setting` if you want this setting - /// to be propagated to subcommands and sub-subcommands! - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let cmd = Command::new("cmd") - /// .ignore_errors(true) - /// .arg(arg!(-c --config "Sets a custom config file").required(false)) - /// .arg(arg!(-x --stuff "Sets a custom stuff file").required(false)) - /// .arg(arg!(f: -f "Flag")); - /// - /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); - /// - /// assert!(r.is_ok(), "unexpected error: {:?}", r); - /// let m = r.unwrap(); - /// assert_eq!(m.value_of("config"), Some("file")); - /// assert!(m.is_present("f")); - /// assert_eq!(m.value_of("stuff"), None); - /// ``` - #[inline] - pub fn ignore_errors(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::IgnoreErrors) - } else { - self.unset_global_setting(AppSettings::IgnoreErrors) - } - } - - /// Deprecated, replaced with [`ArgAction::Set`][super::ArgAction::Set] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `Arg::action(ArgAction::Set)`") - )] - pub fn args_override_self(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::AllArgsOverrideSelf) - } else { - self.unset_global_setting(AppSettings::AllArgsOverrideSelf) - } - } - - /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] - /// was used. - /// - /// **NOTE:** The same thing can be done manually by setting the final positional argument to - /// [`Arg::use_value_delimiter(false)`]. Using this setting is safer, because it's easier to locate - /// when making changes. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .dont_delimit_trailing_values(true) - /// .get_matches(); - /// ``` - /// - /// [`Arg::use_value_delimiter(false)`]: crate::Arg::use_value_delimiter() - #[inline] - pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DontDelimitTrailingValues) - } else { - self.unset_global_setting(AppSettings::DontDelimitTrailingValues) - } - } - - /// Sets when to color output. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Never) - /// .get_matches(); - /// ``` - /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto - #[cfg(feature = "color")] - #[inline] - #[must_use] - pub fn color(self, color: ColorChoice) -> Self { - #![allow(deprecated)] - let cmd = self - .unset_global_setting(AppSettings::ColorAuto) - .unset_global_setting(AppSettings::ColorAlways) - .unset_global_setting(AppSettings::ColorNever); - match color { - ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), - ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), - ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), - } - } - - /// Sets the terminal width at which to wrap help messages. - /// - /// Using `0` will ignore terminal widths and use source formatting. - /// - /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag - /// is disabled or it cannot be determined, the default is 100. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .term_width(80) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn term_width(mut self, width: usize) -> Self { - self.term_w = Some(width); - self - } - - /// Sets the maximum terminal width at which to wrap help messages. - /// - /// This only applies when setting the current terminal width. See [`Command::term_width`] for - /// more details. - /// - /// Using `0` will ignore terminal widths and use source formatting. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .max_term_width(100) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn max_term_width(mut self, w: usize) -> Self { - self.max_w = Some(w); - self - } - - /// Disables `-V` and `--version` flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_version_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - #[inline] - pub fn disable_version_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableVersionFlag) - } else { - self.unset_global_setting(AppSettings::DisableVersionFlag) - } - } - - /// Specifies to use the version of the current command for all [`subcommands`]. - /// - /// Defaults to `false`; subcommands have independent version strings from their parents. - /// - /// **Note:** Make sure you apply it as `global_setting` if you want this setting - /// to be propagated to subcommands and sub-subcommands! - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .version("v1.1") - /// .propagate_version(true) - /// .subcommand(Command::new("test")) - /// .get_matches(); - /// // running `$ myprog test --version` will display - /// // "myprog-test v1.1" - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - #[inline] - pub fn propagate_version(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::PropagateVersion) - } else { - self.unset_global_setting(AppSettings::PropagateVersion) - } - } - - /// Places the help string for all arguments and subcommands on the line after them. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .next_line_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NextLineHelp) - } else { - self.unset_global_setting(AppSettings::NextLineHelp) - } - } - - /// Disables `-h` and `--help` flag. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - #[inline] - pub fn disable_help_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpFlag) - } else { - self.unset_global_setting(AppSettings::DisableHelpFlag) - } - } - - /// Disables the `help` [`subcommand`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_subcommand(true) - /// // Normally, creating a subcommand causes a `help` subcommand to automatically - /// // be generated as well - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "help" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn disable_help_subcommand(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpSubcommand) - } else { - self.unset_global_setting(AppSettings::DisableHelpSubcommand) - } - } - - /// Disables colorized help messages. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .disable_colored_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn disable_colored_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableColoredHelp) - } else { - self.unset_global_setting(AppSettings::DisableColoredHelp) - } - } - - /// Panic if help descriptions are omitted. - /// - /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at - /// compile-time with `#![deny(missing_docs)]` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo").help("It does foo stuff") - /// // As required via `help_expected`, a help message was supplied - /// ) - /// # .get_matches(); - /// ``` - /// - /// # Panics - /// - /// ```rust,no_run - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo") - /// // Someone forgot to put .about("...") here - /// // Since the setting `help_expected` is activated, this will lead to - /// // a panic (if you are in debug mode) - /// ) - /// # .get_matches(); - ///``` - #[inline] - pub fn help_expected(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HelpExpected) - } else { - self.unset_global_setting(AppSettings::HelpExpected) - } - } - - /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .dont_collapse_args_in_usage(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn dont_collapse_args_in_usage(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DontCollapseArgsInUsage) - } else { - self.unset_global_setting(AppSettings::DontCollapseArgsInUsage) - } - } - - /// Tells `clap` *not* to print possible values when displaying help information. - /// - /// This can be useful if there are many values, or they are explained elsewhere. - /// - /// To set this per argument, see - /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - #[inline] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HidePossibleValues) - } else { - self.unset_global_setting(AppSettings::HidePossibleValues) - } - } - - /// Allow partial matches of long arguments or their [aliases]. - /// - /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and - /// `--test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match - /// `--te` to `--test` there could not also be another argument or alias `--temp` because both - /// start with `--te` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_long_args(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferLongArgs) - } else { - self.unset_global_setting(AppSettings::InferLongArgs) - } - } - - /// Allow partial matches of [subcommand] names and their [aliases]. - /// - /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and - /// `test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` - /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` - /// - /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when - /// designing CLIs which allow inferred subcommands and have potential positional/free - /// arguments whose values could start with the same characters as subcommands. If this is the - /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in - /// conjunction with this setting. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .infer_subcommands(true) - /// .subcommand(Command::new("test")) - /// .get_matches_from(vec![ - /// "prog", "te" - /// ]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// - /// [subcommand]: crate::Command::subcommand() - /// [positional/free arguments]: crate::Arg::index() - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_subcommands(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferSubcommands) - } else { - self.unset_global_setting(AppSettings::InferSubcommands) - } - } -} - -/// # Command-specific Settings -/// -/// These apply only to the current command and are not inherited by subcommands. -impl<'help> App<'help> { - /// (Re)Sets the program's name. - /// - /// See [`Command::new`] for more details. - /// - /// # Examples - /// - /// ```ignore - /// # use clap::{Command, load_yaml}; - /// let yaml = load_yaml!("cmd.yaml"); - /// let cmd = Command::from(yaml) - /// .name(crate_name!()); - /// - /// // continued logic goes here, such as `cmd.get_matches()` etc. - /// ``` - #[must_use] - pub fn name>(mut self, name: S) -> Self { - self.name = name.into(); - self - } - - /// Overrides the runtime-determined name of the binary for help and error messages. - /// - /// This should only be used when absolutely necessary, such as when the binary name for your - /// application is misleading, or perhaps *not* how the user should invoke your program. - /// - /// **Pro-tip:** When building things such as third party `cargo` - /// subcommands, this setting **should** be used! - /// - /// **NOTE:** This *does not* change or set the name of the binary file on - /// disk. It only changes what clap thinks the name is for the purposes of - /// error or help messages. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// .bin_name("my_binary") - /// # ; - /// ``` - #[must_use] - pub fn bin_name>(mut self, name: S) -> Self { - self.bin_name = Some(name.into()); - self - } - - /// Overrides the runtime-determined display name of the program for help and error messages. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// .display_name("my_program") - /// # ; - /// ``` - #[must_use] - pub fn display_name>(mut self, name: S) -> Self { - self.display_name = Some(name.into()); - self - } - - /// Sets the author(s) for the help message. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to - /// automatically set your application's author(s) to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .author("Me, me@mymain.com") - /// # ; - /// ``` - /// [`crate_authors!`]: ./macro.crate_authors!.html - #[must_use] - pub fn author>(mut self, author: S) -> Self { - self.author = Some(author.into()); - self - } - - /// Sets the program's description for the short help (`-h`). - /// - /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Command::about` (short format) is used in completion - /// script generation in order to be concise. - /// - /// See also [`crate_description!`](crate::crate_description!). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .about("Does really amazing things for great people") - /// # ; - /// ``` - #[must_use] - pub fn about>>(mut self, about: O) -> Self { - self.about = about.into(); - self - } - - /// Sets the program's description for the long help (`--help`). - /// - /// If [`Command::about`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Command::about`] (short format) is used in completion - /// script generation in order to be concise. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .long_about( - /// "Does really amazing things to great people. Now let's talk a little - /// more in depth about how this subcommand really works. It may take about - /// a few lines of text, but that's ok!") - /// # ; - /// ``` - /// [`App::about`]: Command::about() - #[must_use] - pub fn long_about>>(mut self, long_about: O) -> Self { - self.long_about = long_about.into(); - self - } - - /// Free-form help text for after auto-generated short help (`-h`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .after_help("Does really amazing things for great people... but be careful with -R!") - /// # ; - /// ``` - /// - #[must_use] - pub fn after_help>(mut self, help: S) -> Self { - self.after_help = Some(help.into()); - self - } - - /// Free-form help text for after auto-generated long help (`--help`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ - /// like, for real, be careful with this!") - /// # ; - /// ``` - #[must_use] - pub fn after_long_help>(mut self, help: S) -> Self { - self.after_long_help = Some(help.into()); - self - } - - /// Free-form help text for before auto-generated short help (`-h`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .before_help("Some info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_help>(mut self, help: S) -> Self { - self.before_help = Some(help.into()); - self - } - - /// Free-form help text for before auto-generated long help (`--help`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .before_long_help("Some verbose and long info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_long_help>(mut self, help: S) -> Self { - self.before_long_help = Some(help.into()); - self - } - - /// Sets the version for the short version (`-V`) and help messages. - /// - /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .version("v0.1.24") - /// # ; - /// ``` - /// [`crate_version!`]: ./macro.crate_version!.html - #[must_use] - pub fn version>(mut self, ver: S) -> Self { - self.version = Some(ver.into()); - self - } - - /// Sets the version for the long version (`--version`) and help messages. - /// - /// If [`Command::version`] is not specified, this message will be displayed for `-V`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .long_version( - /// "v0.1.24 - /// commit: abcdef89726d - /// revision: 123 - /// release: 2 - /// binary: myprog") - /// # ; - /// ``` - /// [`crate_version!`]: ./macro.crate_version!.html - #[must_use] - pub fn long_version>(mut self, ver: S) -> Self { - self.long_version = Some(ver.into()); - self - } - - /// Overrides the `clap` generated usage string for help and error messages. - /// - /// **NOTE:** Using this setting disables `clap`s "context-aware" usage - /// strings. After this setting is set, this will be *the only* usage string - /// displayed to the user! - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .override_usage("myapp [-clDas] ") - /// # ; - /// ``` - /// [`ArgMatches::usage`]: ArgMatches::usage() - #[must_use] - pub fn override_usage>(mut self, usage: S) -> Self { - self.usage_str = Some(usage.into()); - self - } - - /// Overrides the `clap` generated help message (both `-h` and `--help`). - /// - /// This should only be used when the auto-generated message does not suffice. - /// - /// **NOTE:** This **only** replaces the help message for the current - /// command, meaning if you are using subcommands, those help messages will - /// still be auto-generated unless you specify a [`Command::override_help`] for - /// them as well. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .override_help("myapp v1.0\n\ - /// Does awesome things\n\ - /// (C) me@mail.com\n\n\ - /// - /// USAGE: myapp \n\n\ - /// - /// Options:\n\ - /// -h, --help Display this message\n\ - /// -V, --version Display version info\n\ - /// -s Do something with stuff\n\ - /// -v Be verbose\n\n\ - /// - /// Commands:\n\ - /// help Print this message\n\ - /// work Do some work") - /// # ; - /// ``` - #[must_use] - pub fn override_help>(mut self, help: S) -> Self { - self.help_str = Some(help.into()); - self - } - - /// Sets the help template to be used, overriding the default format. - /// - /// **NOTE:** The template system is by design very simple. Therefore, the - /// tags have to be written in the lowercase and without spacing. - /// - /// Tags are given inside curly brackets. - /// - /// Valid tags are: - /// - /// * `{name}` - Display name for the (sub-)command. - /// * `{bin}` - Binary name. - /// * `{version}` - Version number. - /// * `{author}` - Author information. - /// * `{author-with-newline}` - Author followed by `\n`. - /// * `{author-section}` - Author preceded and followed by `\n`. - /// * `{about}` - General description (from [`Command::about`] or - /// [`Command::long_about`]). - /// * `{about-with-newline}` - About followed by `\n`. - /// * `{about-section}` - About preceded and followed by '\n'. - /// * `{usage-heading}` - Automatically generated usage heading. - /// * `{usage}` - Automatically generated or given usage string. - /// * `{all-args}` - Help for all arguments (options, flags, positional - /// arguments, and subcommands) including titles. - /// * `{options}` - Help for options. - /// * `{positionals}` - Help for positional arguments. - /// * `{subcommands}` - Help for subcommands. - /// * `{after-help}` - Help from [`App::after_help`] or [`Command::after_long_help`]. - /// * `{before-help}` - Help from [`App::before_help`] or [`Command::before_long_help`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .version("1.0") - /// .help_template("{bin} ({version}) - {usage}") - /// # ; - /// ``` - /// [`App::about`]: Command::about() - /// [`App::long_about`]: Command::long_about() - /// [`App::after_help`]: Command::after_help() - /// [`App::after_long_help`]: Command::after_long_help() - /// [`App::before_help`]: Command::before_help() - /// [`App::before_long_help`]: Command::before_long_help() - #[must_use] - pub fn help_template>(mut self, s: S) -> Self { - self.template = Some(s.into()); - self - } - - /// Apply a setting for the current command or subcommand. - /// - /// See [`Command::global_setting`] to apply a setting to this command and all subcommands. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .setting(AppSettings::SubcommandRequired) - /// .setting(AppSettings::AllowLeadingHyphen) - /// # ; - /// ``` - /// or - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn setting(mut self, setting: F) -> Self - where - F: Into, - { - self.settings.insert(setting.into()); - self - } - - /// Remove a setting for the current command or subcommand. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .unset_setting(AppSettings::SubcommandRequired) - /// .setting(AppSettings::AllowLeadingHyphen) - /// # ; - /// ``` - /// or - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn unset_setting(mut self, setting: F) -> Self - where - F: Into, - { - self.settings.remove(setting.into()); - self - } - - /// Apply a setting for the current command and all subcommands. - /// - /// See [`Command::setting`] to apply a setting only to this command. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .global_setting(AppSettings::AllowNegativeNumbers) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn global_setting(mut self, setting: AppSettings) -> Self { - self.settings.set(setting); - self.g_settings.set(setting); - self - } - - /// Remove a setting and stop propagating down to subcommands. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, AppSettings}; - /// Command::new("myprog") - /// .unset_global_setting(AppSettings::AllowNegativeNumbers) - /// # ; - /// ``` - /// [global]: Command::global_setting() - #[inline] - #[must_use] - pub fn unset_global_setting(mut self, setting: AppSettings) -> Self { - self.settings.unset(setting); - self.g_settings.unset(setting); - self - } - - /// Deprecated, replaced with [`Command::next_help_heading`] - #[inline] - #[must_use] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `App::next_help_heading`") - )] - pub fn help_heading(self, heading: O) -> Self - where - O: Into>, - { - self.next_help_heading(heading) - } - - /// Set the default section heading for future args. - /// - /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. - /// - /// This is useful if the default `OPTIONS` or `ARGS` headings are - /// not specific enough for one's use case. - /// - /// For subcommands, see [`Command::subcommand_help_heading`] - /// - /// [`App::arg`]: Command::arg() - /// [`Arg::help_heading`]: crate::Arg::help_heading() - #[inline] - #[must_use] - pub fn next_help_heading(mut self, heading: O) -> Self - where - O: Into>, - { - self.current_help_heading = heading.into(); - self - } - - /// Change the starting value for assigning future display orders for ags. - /// - /// This will be used for any arg that hasn't had [`Arg::display_order`] called. - #[inline] - #[must_use] - pub fn next_display_order(mut self, disp_ord: impl Into>) -> Self { - self.current_disp_ord = disp_ord.into(); - self - } - - /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. - /// - /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) - /// - /// When this method is used, `name` is removed from the CLI, and `target` - /// is inserted in its place. Parsing continues as if the user typed - /// `target` instead of `name`. - /// - /// This can be used to create "shortcuts" for subcommands, or if a - /// particular argument has the semantic meaning of several other specific - /// arguments and values. - /// - /// # Examples - /// - /// We'll start with the "subcommand short" example. In this example, let's - /// assume we have a program with a subcommand `module` which can be invoked - /// via `cmd module`. Now let's also assume `module` also has a subcommand - /// called `install` which can be invoked `cmd module install`. If for some - /// reason users needed to be able to reach `cmd module install` via the - /// short-hand `cmd install`, we'd have several options. - /// - /// We *could* create another sibling subcommand to `module` called - /// `install`, but then we would need to manage another subcommand and manually - /// dispatch to `cmd module install` handling code. This is error prone and - /// tedious. - /// - /// We could instead use [`Command::replace`] so that, when the user types `cmd - /// install`, `clap` will replace `install` with `module install` which will - /// end up getting parsed as if the user typed the entire incantation. - /// - /// ```rust - /// # use clap::Command; - /// let m = Command::new("cmd") - /// .subcommand(Command::new("module") - /// .subcommand(Command::new("install"))) - /// .replace("install", &["module", "install"]) - /// .get_matches_from(vec!["cmd", "install"]); - /// - /// assert!(m.subcommand_matches("module").is_some()); - /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); - /// ``` - /// - /// Now let's show an argument example! - /// - /// Let's assume we have an application with two flags `--save-context` and - /// `--save-runtime`. But often users end up needing to do *both* at the - /// same time. We can add a third flag `--save-all` which semantically means - /// the same thing as `cmd --save-context --save-runtime`. To implement that, - /// we have several options. - /// - /// We could create this third argument and manually check if that argument - /// and in our own consumer code handle the fact that both `--save-context` - /// and `--save-runtime` *should* have been used. But again this is error - /// prone and tedious. If we had code relying on checking `--save-context` - /// and we forgot to update that code to *also* check `--save-all` it'd mean - /// an error! - /// - /// Luckily we can use [`Command::replace`] so that when the user types - /// `--save-all`, `clap` will replace that argument with `--save-context - /// --save-runtime`, and parsing will continue like normal. Now all our code - /// that was originally checking for things like `--save-context` doesn't - /// need to change! - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("cmd") - /// .arg(Arg::new("save-context") - /// .long("save-context") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("save-runtime") - /// .long("save-runtime") - /// .action(ArgAction::SetTrue)) - /// .replace("--save-all", &["--save-context", "--save-runtime"]) - /// .get_matches_from(vec!["cmd", "--save-all"]); - /// - /// assert!(*m.get_one::("save-context").expect("defaulted by clap")); - /// assert!(*m.get_one::("save-runtime").expect("defaulted by clap")); - /// ``` - /// - /// This can also be used with options, for example if our application with - /// `--save-*` above also had a `--format=TYPE` option. Let's say it - /// accepted `txt` or `json` values. However, when `--save-all` is used, - /// only `--format=json` is allowed, or valid. We could change the example - /// above to enforce this: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("cmd") - /// .arg(Arg::new("save-context") - /// .long("save-context") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("save-runtime") - /// .long("save-runtime") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("format") - /// .long("format") - /// .takes_value(true) - /// .value_parser(["txt", "json"])) - /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) - /// .get_matches_from(vec!["cmd", "--save-all"]); - /// - /// assert!(*m.get_one::("save-context").expect("defaulted by clap")); - /// assert!(*m.get_one::("save-runtime").expect("defaulted by clap")); - /// assert_eq!(m.value_of("format"), Some("json")); - /// ``` - /// - /// [`App::replace`]: Command::replace() - #[inline] - #[cfg(feature = "unstable-replace")] - #[must_use] - pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self { - self.replacers.insert(name, target); - self - } - - /// Exit gracefully if no arguments are present (e.g. `$ myprog`). - /// - /// **NOTE:** [`subcommands`] count as arguments - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command}; - /// Command::new("myprog") - /// .arg_required_else_help(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - /// [`Arg::default_value`]: crate::Arg::default_value() - #[inline] - pub fn arg_required_else_help(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgRequiredElseHelp) - } else { - self.unset_setting(AppSettings::ArgRequiredElseHelp) - } - } - - /// Specifies that leading hyphens are allowed in all argument *values* (e.g. `-10`). - /// - /// Otherwise they will be parsed as another flag or option. See also - /// [`Command::allow_negative_numbers`]. - /// - /// **NOTE:** Use this setting with caution as it silences certain circumstances which would - /// otherwise be an error (such as accidentally forgetting to specify a value for leading - /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Arg, Command}; - /// // Imagine you needed to represent negative numbers as well, such as -10 - /// let m = Command::new("nums") - /// .allow_hyphen_values(true) - /// .arg(Arg::new("neg")) - /// .get_matches_from(vec![ - /// "nums", "-20" - /// ]); - /// - /// assert_eq!(m.value_of("neg"), Some("-20")); - /// # ; - /// ``` - /// [`Arg::allow_hyphen_values`]: crate::Arg::allow_hyphen_values() - #[inline] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowHyphenValues) - } else { - self.unset_setting(AppSettings::AllowHyphenValues) - } - } - - /// Allows negative numbers to pass as values. - /// - /// This is similar to [`Command::allow_hyphen_values`] except that it only allows numbers, - /// all other undefined leading hyphens will fail to parse. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("myprog") - /// .allow_negative_numbers(true) - /// .arg(Arg::new("num")) - /// .try_get_matches_from(vec![ - /// "myprog", "-20" - /// ]); - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.value_of("num").unwrap(), "-20"); - /// ``` - #[inline] - pub fn allow_negative_numbers(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowNegativeNumbers) - } else { - self.unset_setting(AppSettings::AllowNegativeNumbers) - } - } - - /// Specifies that the final positional argument is a "VarArg" and that `clap` should not - /// attempt to parse any further args. - /// - /// The values of the trailing positional argument will contain all args from itself on. - /// - /// **NOTE:** The final positional argument **must** have [`Arg::multiple_values(true)`] or the usage - /// string equivalent. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .trailing_var_arg(true) - /// .arg(arg!( ... "commands to run")) - /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); - /// - /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); - /// assert_eq!(trail, ["arg1", "-r", "val1"]); - /// ``` - /// [`Arg::multiple_values(true)`]: crate::Arg::multiple_values() - pub fn trailing_var_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::TrailingVarArg) - } else { - self.unset_setting(AppSettings::TrailingVarArg) - } - } - - /// Allows one to implement two styles of CLIs where positionals can be used out of order. - /// - /// The first example is a CLI where the second to last positional argument is optional, but - /// the final positional argument is required. Such as `$ prog [optional] ` where one - /// of the two following usages is allowed: - /// - /// * `$ prog [optional] ` - /// * `$ prog ` - /// - /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. - /// - /// **Note:** when using this style of "missing positionals" the final positional *must* be - /// [required] if `--` will not be used to skip to the final positional argument. - /// - /// **Note:** This style also only allows a single positional argument to be "skipped" without - /// the use of `--`. To skip more than one, see the second example. - /// - /// The second example is when one wants to skip multiple optional positional arguments, and use - /// of the `--` operator is OK (but not required if all arguments will be specified anyways). - /// - /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where - /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). - /// - /// With this setting the following invocations are posisble: - /// - /// * `$ prog foo bar baz1 baz2 baz3` - /// * `$ prog foo -- baz1 baz2 baz3` - /// * `$ prog -- baz1 baz2 baz3` - /// - /// # Examples - /// - /// Style number one from above: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.value_of("arg1"), None); - /// assert_eq!(m.value_of("arg2"), Some("other")); - /// ``` - /// - /// Now the same example, but using a default value for the first optional positional argument - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1") - /// .default_value("something")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.value_of("arg1"), Some("something")); - /// assert_eq!(m.value_of("arg2"), Some("other")); - /// ``` - /// - /// Style number two from above: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) - /// .get_matches_from(vec![ - /// "prog", "foo", "bar", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.value_of("foo"), Some("foo")); - /// assert_eq!(m.value_of("bar"), Some("bar")); - /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) - /// .get_matches_from(vec![ - /// "prog", "--", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.value_of("foo"), None); - /// assert_eq!(m.value_of("bar"), None); - /// assert_eq!(m.values_of("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// [required]: crate::Arg::required() - #[inline] - pub fn allow_missing_positional(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowMissingPositional) - } else { - self.unset_setting(AppSettings::AllowMissingPositional) - } - } -} - -/// # Subcommand-specific Settings -impl<'help> App<'help> { - /// Sets the short version of the subcommand flag without the preceding `-`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::short`]. - /// - /// # Examples - /// - /// ``` - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").short_flag('S').arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "-Ss"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(*sync_matches.get_one::("search").expect("defaulted by clap")); - /// ``` - /// [`Arg::short`]: Arg::short() - #[must_use] - pub fn short_flag(mut self, short: char) -> Self { - self.short_flag = Some(short); - self - } - - /// Sets the long version of the subcommand flag without the preceding `--`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::long`]. - /// - /// **NOTE:** Any leading `-` characters will be stripped. - /// - /// # Examples - /// - /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading - /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, - /// will *not* be stripped (i.e. `sync-file` is allowed). - /// - /// ``` - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").long_flag("sync").arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "--sync", "--search"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(*sync_matches.get_one::("search").expect("defaulted by clap")); - /// ``` - /// - /// [`Arg::long`]: Arg::long() - #[must_use] - pub fn long_flag(mut self, long: &'help str) -> Self { - #[cfg(feature = "unstable-v4")] - { - self.long_flag = Some(long); - } - #[cfg(not(feature = "unstable-v4"))] - { - self.long_flag = Some(long.trim_start_matches(|c| c == '-')); - } - self - } - - /// Sets a hidden alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name, or this given - /// alias. This is more efficient and easier than creating multiple hidden subcommands as one - /// only needs to check for the existence of this command, and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If you're looking for aliases that will be displayed in the help - /// message, see [`Command::visible_alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::visible_alias`]: Command::visible_alias() - #[must_use] - pub fn alias>(mut self, name: S) -> Self { - self.aliases.push((name.into(), false)); - self - } - - /// Add an alias, which functions as "hidden" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_alias(mut self, name: char) -> Self { - assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, false)); - self - } - - /// Add an alias, which functions as a "hidden" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_alias(mut self, name: &'help str) -> Self { - self.long_flag_aliases.push((name, false)); - self - } - - /// Sets multiple hidden aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name or any of the - /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands - /// as one only needs to check for the existence of this command and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If looking for aliases that will be displayed in the help - /// message, see [`Command::visible_aliases`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .aliases(&["do-stuff", "do-tests", "tests"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "do-tests"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::visible_aliases`]: Command::visible_aliases() - #[must_use] - pub fn aliases(mut self, names: &[&'help str]) -> Self { - self.aliases.extend(names.iter().map(|n| (*n, false))); - self - } - - /// Add aliases, which function as "hidden" short flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_aliases(&['a', 'b', 'c'])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "-a"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_aliases(mut self, names: &[char]) -> Self { - for s in names { - assert!(s != &'-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((*s, false)); - } - self - } - - /// Add aliases, which function as "hidden" long flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_aliases(&["testing", "testall", "test_all"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self { - for s in names { - self.long_flag_aliases.push((s, false)); - } - self - } - - /// Sets a visible alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or the given alias. This is more efficient and easier - /// than creating hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::alias`]: Command::alias() - #[must_use] - pub fn visible_alias>(mut self, name: S) -> Self { - self.aliases.push((name.into(), true)); - self - } - - /// Add an alias, which functions as "visible" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::short_flag_alias`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .visible_short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::short_flag_alias`]: Command::short_flag_alias() - #[must_use] - pub fn visible_short_flag_alias(mut self, name: char) -> Self { - assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, true)); - self - } - - /// Add an alias, which functions as a "visible" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::long_flag_alias`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::long_flag_alias`]: Command::long_flag_alias() - #[must_use] - pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self { - self.long_flag_aliases.push((name, true)); - self - } - - /// Sets multiple visible aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or any of the given aliases. This is more efficient and easier - /// than creating multiple hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases, and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_aliases(&["do-stuff", "tests"])) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::alias`]: Command::alias() - #[must_use] - pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { - self.aliases.extend(names.iter().map(|n| (*n, true))); - self - } - - /// Add aliases, which function as *visible* short flag subcommands. - /// - /// See [`Command::short_flag_aliases`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('b') - /// .visible_short_flag_aliases(&['t'])) - /// .get_matches_from(vec!["myprog", "-t"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::short_flag_aliases`]: Command::short_flag_aliases() - #[must_use] - pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self { - for s in names { - assert!(s != &'-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((*s, true)); - } - self - } - - /// Add aliases, which function as *visible* long flag subcommands. - /// - /// See [`Command::long_flag_aliases`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_aliases(&["testing", "testall", "test_all"])) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`App::long_flag_aliases`]: Command::long_flag_aliases() - #[must_use] - pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self { - for s in names { - self.long_flag_aliases.push((s, true)); - } - self - } - - /// Set the placement of this subcommand within the help. - /// - /// Subcommands with a lower value will be displayed first in the help message. Subcommands - /// with duplicate display orders will be displayed in alphabetical order. - /// - /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize - /// those towards the top of the list. - /// - /// **NOTE:** The default is 999 for all subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, }; - /// let m = Command::new("cust-ord") - /// .subcommand(Command::new("alpha") // typically subcommands are grouped - /// // alphabetically by name. Subcommands - /// // without a display_order have a value of - /// // 999 and are displayed alphabetically with - /// // all other 999 subcommands - /// .about("Some help and text")) - /// .subcommand(Command::new("beta") - /// .display_order(1) // In order to force this subcommand to appear *first* - /// // all we have to do is give it a value lower than 999. - /// // Any other subcommands with a value of 1 will be displayed - /// // alphabetically with this one...then 2 values, then 3, etc. - /// .about("I should be first!")) - /// .get_matches_from(vec![ - /// "cust-ord", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// cust-ord - /// - /// USAGE: - /// cust-ord [OPTIONS] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// - /// SUBCOMMANDS: - /// beta I should be first! - /// alpha Some help and text - /// ``` - #[inline] - #[must_use] - pub fn display_order(mut self, ord: usize) -> Self { - self.disp_ord = Some(ord); - self - } - - /// Specifies that this [`subcommand`] should be hidden from help messages - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand( - /// Command::new("test").hide(true) - /// ) - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Hidden) - } else { - self.unset_setting(AppSettings::Hidden) - } - } - - /// If no [`subcommand`] is present at runtime, error and exit gracefully. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - pub fn subcommand_required(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandRequired) - } else { - self.unset_setting(AppSettings::SubcommandRequired) - } - } - - /// Assume unexpected positional arguments are a [`subcommand`]. - /// - /// Arguments will be stored in the `""` argument in the [`ArgMatches`] - /// - /// **NOTE:** Use this setting with caution, - /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) - /// will **not** cause an error and instead be treated as a potential subcommand. - /// One should check for such cases manually and inform the user appropriately. - /// - /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with - /// `--`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - /// [`ArgMatches`]: crate::ArgMatches - /// [`ErrorKind::UnknownArgument`]: crate::ErrorKind::UnknownArgument - pub fn allow_external_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowExternalSubcommands) - } else { - self.unset_setting(AppSettings::AllowExternalSubcommands) - } - } - - /// Specifies that external subcommands that are invalid UTF-8 should *not* be treated as an error. - /// - /// **NOTE:** Using external subcommand argument values with invalid UTF-8 requires using - /// [`ArgMatches::values_of_os`] or [`ArgMatches::values_of_lossy`] for those particular - /// arguments which may contain invalid UTF-8 values - /// - /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] - /// - /// # Platform Specific - /// - /// Non Windows systems only - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_invalid_utf8_for_external_subcommands(true) - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os() - /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy() - /// [`subcommands`]: crate::Command::subcommand() - pub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) - } else { - self.unset_setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) - } - } - - /// Specifies that use of an argument prevents the use of [`subcommands`]. - /// - /// By default `clap` allows arguments between subcommands such - /// as ` [cmd_args] [subcmd_args] [subsubcmd_args]`. - /// - /// This setting disables that functionality and says that arguments can - /// only follow the *final* subcommand. For instance using this setting - /// makes only the following invocations possible: - /// - /// * ` [subsubcmd_args]` - /// * ` [subcmd_args]` - /// * ` [cmd_args]` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// Command::new("myprog") - /// .args_conflicts_with_subcommands(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgsNegateSubcommands) - } else { - self.unset_setting(AppSettings::ArgsNegateSubcommands) - } - } - - /// Prevent subcommands from being consumed as an arguments value. - /// - /// By default, if an option taking multiple values is followed by a subcommand, the - /// subcommand will be parsed as another value. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values another value - /// ``` - /// - /// This setting instructs the parser to stop when encountering a subcommand instead of - /// greedily consuming arguments. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values subcommand - /// ``` - /// - /// **Note:** Make sure you apply it as `global_setting` if you want this setting - /// to be propagated to subcommands and sub-subcommands! - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( - /// Arg::new("arg") - /// .long("arg") - /// .multiple_values(true) - /// .takes_value(true), - /// ); - /// - /// let matches = cmd - /// .clone() - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.values_of("arg").unwrap().collect::>(), - /// &["1", "2", "3", "sub"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_none()); - /// - /// let matches = cmd - /// .subcommand_precedence_over_arg(true) - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.values_of("arg").unwrap().collect::>(), - /// &["1", "2", "3"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_some()); - /// ``` - pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandPrecedenceOverArg) - } else { - self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) - } - } - - /// Allows [`subcommands`] to override all requirements of the parent command. - /// - /// For example, if you had a subcommand or top level application with a required argument - /// that is only required as long as there is no subcommand present, - /// using this setting would allow you to set those arguments to [`Arg::required(true)`] - /// and yet receive no error so long as the user uses a valid subcommand instead. - /// - /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) - /// - /// # Examples - /// - /// This first example shows that it is an error to not use a required argument - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog" - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// # ; - /// ``` - /// - /// This next example shows that it is no longer error to not use a required argument if a - /// valid subcommand is used. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let noerr = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "test" - /// ]); - /// assert!(noerr.is_ok()); - /// # ; - /// ``` - /// - /// [`Arg::required(true)`]: crate::Arg::required() - /// [`subcommands`]: crate::Command::subcommand() - pub fn subcommand_negates_reqs(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandsNegateReqs) - } else { - self.unset_setting(AppSettings::SubcommandsNegateReqs) - } - } - - /// Multiple-personality program dispatched on the binary name (`argv[0]`) - /// - /// A "multicall" executable is a single executable - /// that contains a variety of applets, - /// and decides which applet to run based on the name of the file. - /// The executable can be called from different names by creating hard links - /// or symbolic links to it. - /// - /// This is desirable for: - /// - Easy distribution, a single binary that can install hardlinks to access the different - /// personalities. - /// - Minimal binary size by sharing common code (e.g. standard library, clap) - /// - Custom shells or REPLs where there isn't a single top-level command - /// - /// Setting `multicall` will cause - /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if - /// [`Command::no_binary_name`][App::no_binary_name] was set. - /// - Help and errors to report subcommands as if they were the top-level command - /// - /// When the subcommand is not present, there are several strategies you may employ, depending - /// on your needs: - /// - Let the error percolate up normally - /// - Print a specialized error message using the - /// [`Error::context`][crate::Error::context] - /// - Print the [help][App::write_help] but this might be ambiguous - /// - Disable `multicall` and re-parse it - /// - Disable `multicall` and re-parse it with a specific subcommand - /// - /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand - /// might report the same error. Enable - /// [`allow_external_subcommands`][App::allow_external_subcommands] if you want to specifically - /// get the unrecognized binary name. - /// - /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret - /// the command name in incompatible ways. - /// - /// **NOTE:** The multicall command cannot have arguments. - /// - /// **NOTE:** Applets are slightly semantically different from subcommands, - /// so it's recommended to use [`Command::subcommand_help_heading`] and - /// [`Command::subcommand_value_name`] to change the descriptive text as above. - /// - /// # Examples - /// - /// `hostname` is an example of a multicall executable. - /// Both `hostname` and `dnsdomainname` are provided by the same executable - /// and which behaviour to use is based on the executable file name. - /// - /// This is desirable when the executable has a primary purpose - /// but there is related functionality that would be convenient to provide - /// and implement it to be in the same executable. - /// - /// The name of the cmd is essentially unused - /// and may be the same as the name of a subcommand. - /// - /// The names of the immediate subcommands of the Command - /// are matched against the basename of the first argument, - /// which is conventionally the path of the executable. - /// - /// This does not allow the subcommand to be passed as the first non-path argument. - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let mut cmd = Command::new("hostname") - /// .multicall(true) - /// .subcommand(Command::new("hostname")) - /// .subcommand(Command::new("dnsdomainname")); - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); - /// assert!(m.is_err()); - /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); - /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); - /// ``` - /// - /// Busybox is another common example of a multicall executable - /// with a subcommmand for each applet that can be run directly, - /// e.g. with the `cat` applet being run by running `busybox cat`, - /// or with `cat` as a link to the `busybox` binary. - /// - /// This is desirable when the launcher program has additional options - /// or it is useful to run the applet without installing a symlink - /// e.g. to test the applet without installing it - /// or there may already be a command of that name installed. - /// - /// To make an applet usable as both a multicall link and a subcommand - /// the subcommands must be defined both in the top-level Command - /// and as subcommands of the "main" applet. - /// - /// ```rust - /// # use clap::Command; - /// fn applet_commands() -> [Command<'static>; 2] { - /// [Command::new("true"), Command::new("false")] - /// } - /// let mut cmd = Command::new("busybox") - /// .multicall(true) - /// .subcommand( - /// Command::new("busybox") - /// .subcommand_value_name("APPLET") - /// .subcommand_help_heading("APPLETS") - /// .subcommands(applet_commands()), - /// ) - /// .subcommands(applet_commands()); - /// // When called from the executable's canonical name - /// // its applets can be matched as subcommands. - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); - /// assert_eq!(m.subcommand_name(), Some("busybox")); - /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); - /// // When called from a link named after an applet that applet is matched. - /// let m = cmd.get_matches_from(&["/usr/bin/true"]); - /// assert_eq!(m.subcommand_name(), Some("true")); - /// ``` - /// - /// [`no_binary_name`]: crate::Command::no_binary_name - /// [`App::subcommand_value_name`]: crate::Command::subcommand_value_name - /// [`App::subcommand_help_heading`]: crate::Command::subcommand_help_heading - #[inline] - pub fn multicall(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Multicall) - } else { - self.unset_setting(AppSettings::Multicall) - } - } - - /// Sets the value name used for subcommands when printing usage and help. - /// - /// By default, this is "SUBCOMMAND". - /// - /// See also [`Command::subcommand_help_heading`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// USAGE: - /// myprog [SUBCOMMAND] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// - /// SUBCOMMANDS: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// ``` - /// - /// but usage of `subcommand_value_name` - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_value_name("THING") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// USAGE: - /// myprog [THING] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// - /// SUBCOMMANDS: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// ``` - #[must_use] - pub fn subcommand_value_name(mut self, value_name: S) -> Self - where - S: Into<&'help str>, - { - self.subcommand_value_name = Some(value_name.into()); - self - } - - /// Sets the help heading used for subcommands when printing usage and help. - /// - /// By default, this is "SUBCOMMANDS". - /// - /// See also [`Command::subcommand_value_name`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// USAGE: - /// myprog [SUBCOMMAND] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// - /// SUBCOMMANDS: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// ``` - /// - /// but usage of `subcommand_help_heading` - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_help_heading("THINGS") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// USAGE: - /// myprog [SUBCOMMAND] - /// - /// OPTIONS: - /// -h, --help Print help information - /// -V, --version Print version information - /// - /// THINGS: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// ``` - #[must_use] - pub fn subcommand_help_heading(mut self, heading: T) -> Self - where - T: Into<&'help str>, - { - self.subcommand_heading = Some(heading.into()); - self - } -} - -/// # Reflection -impl<'help> App<'help> { - #[inline] - pub(crate) fn get_usage_name(&self) -> Option<&str> { - self.usage_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub fn get_display_name(&self) -> Option<&str> { - self.display_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub fn get_bin_name(&self) -> Option<&str> { - self.bin_name.as_deref() - } - - /// Set binary name. Uses `&mut self` instead of `self`. - pub fn set_bin_name>(&mut self, name: S) { - self.bin_name = Some(name.into()); - } - - /// Get the name of the cmd. - #[inline] - pub fn get_name(&self) -> &str { - &self.name - } - - /// Get the version of the cmd. - #[inline] - pub fn get_version(&self) -> Option<&'help str> { - self.version - } - - /// Get the long version of the cmd. - #[inline] - pub fn get_long_version(&self) -> Option<&'help str> { - self.long_version - } - - /// Get the authors of the cmd. - #[inline] - pub fn get_author(&self) -> Option<&'help str> { - self.author - } - - /// Get the short flag of the subcommand. - #[inline] - pub fn get_short_flag(&self) -> Option { - self.short_flag - } - - /// Get the long flag of the subcommand. - #[inline] - pub fn get_long_flag(&self) -> Option<&'help str> { - self.long_flag - } - - /// Get the help message specified via [`Command::about`]. - /// - /// [`App::about`]: Command::about() - #[inline] - pub fn get_about(&self) -> Option<&'help str> { - self.about - } - - /// Get the help message specified via [`Command::long_about`]. - /// - /// [`App::long_about`]: Command::long_about() - #[inline] - pub fn get_long_about(&self) -> Option<&'help str> { - self.long_about - } - - /// Deprecated, replaced with [`Command::get_next_help_heading`] - #[inline] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `App::get_next_help_heading`") - )] - pub fn get_help_heading(&self) -> Option<&'help str> { - self.get_next_help_heading() - } - - /// Get the custom section heading specified via [`Command::help_heading`]. - /// - /// [`App::help_heading`]: Command::help_heading() - #[inline] - pub fn get_next_help_heading(&self) -> Option<&'help str> { - self.current_help_heading - } - - /// Iterate through the *visible* aliases for this subcommand. - #[inline] - pub fn get_visible_aliases(&self) -> impl Iterator + '_ { - self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0) - } - - /// Iterate through the *visible* short aliases for this subcommand. - #[inline] - pub fn get_visible_short_flag_aliases(&self) -> impl Iterator + '_ { - self.short_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0) - } - - /// Iterate through the *visible* long aliases for this subcommand. - #[inline] - pub fn get_visible_long_flag_aliases(&self) -> impl Iterator + '_ { - self.long_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0) - } - - /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_aliases(&self) -> impl Iterator + '_ { - self.aliases.iter().map(|a| a.0) - } - - /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_short_flag_aliases(&self) -> impl Iterator + '_ { - self.short_flag_aliases.iter().map(|a| a.0) - } - - /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_long_flag_aliases(&self) -> impl Iterator + '_ { - self.long_flag_aliases.iter().map(|a| a.0) - } - - /// Check if the given [`AppSettings`] variant is currently set on the `Command`. - /// - /// This checks both [local] and [global settings]. - /// - /// [local]: Command::setting() - /// [global settings]: Command::global_setting() - #[inline] - pub fn is_set(&self, s: AppSettings) -> bool { - self.settings.is_set(s) || self.g_settings.is_set(s) - } - - /// Should we color the output? - #[inline(never)] - pub fn get_color(&self) -> ColorChoice { - debug!("Command::color: Color setting..."); - - if cfg!(feature = "color") { - #[allow(deprecated)] - if self.is_set(AppSettings::ColorNever) { - debug!("Never"); - ColorChoice::Never - } else if self.is_set(AppSettings::ColorAlways) { - debug!("Always"); - ColorChoice::Always - } else { - debug!("Auto"); - ColorChoice::Auto - } - } else { - ColorChoice::Never - } - } - - /// Iterate through the set of subcommands, getting a reference to each. - #[inline] - pub fn get_subcommands(&self) -> impl Iterator> { - self.subcommands.iter() - } - - /// Iterate through the set of subcommands, getting a mutable reference to each. - #[inline] - pub fn get_subcommands_mut(&mut self) -> impl Iterator> { - self.subcommands.iter_mut() - } - - /// Returns `true` if this `Command` has subcommands. - #[inline] - pub fn has_subcommands(&self) -> bool { - !self.subcommands.is_empty() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_subcommand_help_heading(&self) -> Option<&str> { - self.subcommand_heading - } - - /// Deprecated, replaced with [`App::get_subcommand_help_heading`] - #[inline] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `App::get_subcommand_help_heading`" - ) - )] - pub fn get_subommand_help_heading(&self) -> Option<&str> { - self.get_subcommand_help_heading() - } - - /// Returns the subcommand value name. - #[inline] - pub fn get_subcommand_value_name(&self) -> Option<&str> { - self.subcommand_value_name - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_help(&self) -> Option<&str> { - self.before_help - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_long_help(&self) -> Option<&str> { - self.before_long_help - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_help(&self) -> Option<&str> { - self.after_help - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_long_help(&self) -> Option<&str> { - self.after_long_help - } - - /// Find subcommand such that its name or one of aliases equals `name`. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand(&self, name: &T) -> Option<&App<'help>> - where - T: PartialEq + ?Sized, - { - self.get_subcommands().find(|s| s.aliases_to(name)) - } - - /// Find subcommand such that its name or one of aliases equals `name`, returning - /// a mutable reference to the subcommand. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand_mut(&mut self, name: &T) -> Option<&mut App<'help>> - where - T: PartialEq + ?Sized, - { - self.get_subcommands_mut().find(|s| s.aliases_to(name)) - } - - /// Iterate through the set of groups. - #[inline] - pub fn get_groups(&self) -> impl Iterator> { - self.groups.iter() - } - - /// Iterate through the set of arguments. - #[inline] - pub fn get_arguments(&self) -> impl Iterator> { - self.args.args() - } - - /// Iterate through the *positionals* arguments. - #[inline] - pub fn get_positionals(&self) -> impl Iterator> { - self.get_arguments().filter(|a| a.is_positional()) - } - - /// Iterate through the *options*. - pub fn get_opts(&self) -> impl Iterator> { - self.get_arguments() - .filter(|a| a.is_takes_value_set() && !a.is_positional()) - } - - /// Get a list of all arguments the given argument conflicts with. - /// - /// If the provided argument is declared as global, the conflicts will be determined - /// based on the propagation rules of global arguments. - /// - /// ### Panics - /// - /// If the given arg contains a conflict with an argument that is unknown to - /// this `Command`. - pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator - { - if arg.is_global_set() { - self.get_global_arg_conflicts_with(arg) - } else { - arg.blacklist - .iter() - .map(|id| { - self.args.args().find(|arg| arg.id == *id).expect( - "Command::get_arg_conflicts_with: \ - The passed arg conflicts with an arg unknown to the cmd", - ) - }) - .collect() - } - } - - // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. - // - // This behavior follows the propagation rules of global arguments. - // It is useful for finding conflicts for arguments declared as global. - // - // ### Panics - // - // If the given arg contains a conflict with an argument that is unknown to - // this `App`. - fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator - { - arg.blacklist - .iter() - .map(|id| { - self.args - .args() - .chain( - self.get_subcommands_containing(arg) - .iter() - .flat_map(|x| x.args.args()), - ) - .find(|arg| arg.id == *id) - .expect( - "Command::get_arg_conflicts_with: \ - The passed arg conflicts with an arg unknown to the cmd", - ) - }) - .collect() - } - - // Get a list of subcommands which contain the provided Argument - // - // This command will only include subcommands in its list for which the subcommands - // parent also contains the Argument. - // - // This search follows the propagation rules of global arguments. - // It is useful to finding subcommands, that have inherited a global argument. - // - // **NOTE:** In this case only Sucommand_1 will be included - // Subcommand_1 (contains Arg) - // Subcommand_1.1 (doesn't contain Arg) - // Subcommand_1.1.1 (contains Arg) - // - fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&App<'help>> { - let mut vec = std::vec::Vec::new(); - for idx in 0..self.subcommands.len() { - if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) { - vec.push(&self.subcommands[idx]); - vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); - } - } - vec - } - - /// Report whether [`Command::no_binary_name`] is set - pub fn is_no_binary_name_set(&self) -> bool { - self.is_set(AppSettings::NoBinaryName) - } - - /// Report whether [`Command::ignore_errors`] is set - pub(crate) fn is_ignore_errors_set(&self) -> bool { - self.is_set(AppSettings::IgnoreErrors) - } - - /// Report whether [`Command::dont_delimit_trailing_values`] is set - pub fn is_dont_delimit_trailing_values_set(&self) -> bool { - self.is_set(AppSettings::DontDelimitTrailingValues) - } - - /// Report whether [`Command::disable_version_flag`] is set - pub fn is_disable_version_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableVersionFlag) - } - - /// Report whether [`Command::propagate_version`] is set - pub fn is_propagate_version_set(&self) -> bool { - self.is_set(AppSettings::PropagateVersion) - } - - /// Report whether [`Command::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(AppSettings::NextLineHelp) - } - - /// Report whether [`Command::disable_help_flag`] is set - pub fn is_disable_help_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpFlag) - } - - /// Report whether [`Command::disable_help_subcommand`] is set - pub fn is_disable_help_subcommand_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpSubcommand) - } - - /// Report whether [`Command::disable_colored_help`] is set - pub fn is_disable_colored_help_set(&self) -> bool { - self.is_set(AppSettings::DisableColoredHelp) - } - - /// Report whether [`Command::help_expected`] is set - #[cfg(debug_assertions)] - pub(crate) fn is_help_expected_set(&self) -> bool { - self.is_set(AppSettings::HelpExpected) - } - - /// Report whether [`Command::dont_collapse_args_in_usage`] is set - pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { - self.is_set(AppSettings::DontCollapseArgsInUsage) - } - - /// Report whether [`Command::infer_long_args`] is set - pub(crate) fn is_infer_long_args_set(&self) -> bool { - self.is_set(AppSettings::InferLongArgs) - } - - /// Report whether [`Command::infer_subcommands`] is set - pub(crate) fn is_infer_subcommands_set(&self) -> bool { - self.is_set(AppSettings::InferSubcommands) - } - - /// Report whether [`Command::arg_required_else_help`] is set - pub fn is_arg_required_else_help_set(&self) -> bool { - self.is_set(AppSettings::ArgRequiredElseHelp) - } - - /// Report whether [`Command::allow_hyphen_values`] is set - pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(AppSettings::AllowHyphenValues) - } - - /// Report whether [`Command::allow_negative_numbers`] is set - pub fn is_allow_negative_numbers_set(&self) -> bool { - self.is_set(AppSettings::AllowNegativeNumbers) - } - - /// Report whether [`Command::trailing_var_arg`] is set - pub fn is_trailing_var_arg_set(&self) -> bool { - self.is_set(AppSettings::TrailingVarArg) - } - - /// Report whether [`Command::allow_missing_positional`] is set - pub fn is_allow_missing_positional_set(&self) -> bool { - self.is_set(AppSettings::AllowMissingPositional) - } - - /// Report whether [`Command::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(AppSettings::Hidden) - } - - /// Report whether [`Command::subcommand_required`] is set - pub fn is_subcommand_required_set(&self) -> bool { - self.is_set(AppSettings::SubcommandRequired) - } - - /// Report whether [`Command::allow_external_subcommands`] is set - pub fn is_allow_external_subcommands_set(&self) -> bool { - self.is_set(AppSettings::AllowExternalSubcommands) - } - - /// Report whether [`Command::allow_invalid_utf8_for_external_subcommands`] is set - pub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool { - self.is_set(AppSettings::AllowInvalidUtf8ForExternalSubcommands) - } - - /// Configured parser for values passed to an external subcommand - /// - /// # Example - /// - /// ```rust - /// let cmd = clap::Command::new("raw") - /// .allow_external_subcommands(true) - /// .allow_invalid_utf8_for_external_subcommands(true); - /// let value_parser = cmd.get_external_subcommand_value_parser(); - /// println!("{:?}", value_parser); - /// ``` - pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { - if !self.is_allow_external_subcommands_set() { - None - } else if self.is_allow_invalid_utf8_for_external_subcommands_set() { - static DEFAULT: super::ValueParser = super::ValueParser::os_string(); - Some(&DEFAULT) - } else { - static DEFAULT: super::ValueParser = super::ValueParser::string(); - Some(&DEFAULT) - } - } - - /// Report whether [`Command::args_conflicts_with_subcommands`] is set - pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { - self.is_set(AppSettings::ArgsNegateSubcommands) - } - - /// Report whether [`Command::subcommand_precedence_over_arg`] is set - pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { - self.is_set(AppSettings::SubcommandPrecedenceOverArg) - } - - /// Report whether [`Command::subcommand_negates_reqs`] is set - pub fn is_subcommand_negates_reqs_set(&self) -> bool { - self.is_set(AppSettings::SubcommandsNegateReqs) - } - - /// Report whether [`Command::multicall`] is set - pub fn is_multicall_set(&self) -> bool { - self.is_set(AppSettings::Multicall) - } -} - -/// Deprecated -impl<'help> App<'help> { - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - #[cfg(feature = "yaml")] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) - )] - #[doc(hidden)] - pub fn from_yaml(y: &'help Yaml) -> Self { - #![allow(deprecated)] - let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); - // We WANT this to panic on error...so expect() is good. - let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() { - (App::new(name), yaml_file_hash, "cmd".into()) - } else { - let (name_yaml, value_yaml) = yaml_file_hash - .iter() - .next() - .expect("There must be one subcommand in the YAML file"); - let name_str = name_yaml - .as_str() - .expect("Subcommand name must be a string"); - - ( - App::new(name_str), - value_yaml.as_hash().expect("Subcommand must be a hash"), - format!("subcommand '{}'", name_str), - ) - }; - - for (k, v) in yaml { - a = match k.as_str().expect("App fields must be strings") { - "version" => yaml_to_str!(a, v, version), - "long_version" => yaml_to_str!(a, v, long_version), - "author" => yaml_to_str!(a, v, author), - "bin_name" => yaml_to_str!(a, v, bin_name), - "about" => yaml_to_str!(a, v, about), - "long_about" => yaml_to_str!(a, v, long_about), - "before_help" => yaml_to_str!(a, v, before_help), - "after_help" => yaml_to_str!(a, v, after_help), - "template" => yaml_to_str!(a, v, help_template), - "usage" => yaml_to_str!(a, v, override_usage), - "help" => yaml_to_str!(a, v, override_help), - "help_message" => yaml_to_str!(a, v, help_message), - "version_message" => yaml_to_str!(a, v, version_message), - "alias" => yaml_to_str!(a, v, alias), - "aliases" => yaml_vec_or_str!(a, v, alias), - "visible_alias" => yaml_to_str!(a, v, visible_alias), - "visible_aliases" => yaml_vec_or_str!(a, v, visible_alias), - "display_order" => yaml_to_usize!(a, v, display_order), - "args" => { - if let Some(vec) = v.as_vec() { - for arg_yaml in vec { - a = a.arg(Arg::from_yaml(arg_yaml)); - } - } else { - panic!("Failed to convert YAML value {:?} to a vec", v); - } - a - } - "subcommands" => { - if let Some(vec) = v.as_vec() { - for sc_yaml in vec { - a = a.subcommand(App::from_yaml(sc_yaml)); - } - } else { - panic!("Failed to convert YAML value {:?} to a vec", v); - } - a - } - "groups" => { - if let Some(vec) = v.as_vec() { - for ag_yaml in vec { - a = a.group(ArgGroup::from(ag_yaml)); - } - } else { - panic!("Failed to convert YAML value {:?} to a vec", v); - } - a - } - "setting" | "settings" => { - yaml_to_setting!(a, v, setting, AppSettings, "AppSetting", err) - } - "global_setting" | "global_settings" => { - yaml_to_setting!(a, v, global_setting, AppSettings, "AppSetting", err) - } - _ => a, - } - } - - a - } - - /// Deprecated, replaced with [`Command::override_usage`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::override_usage`") - )] - #[doc(hidden)] - #[must_use] - pub fn usage>(self, usage: S) -> Self { - self.override_usage(usage) - } - - /// Deprecated, replaced with [`Command::override_help`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::override_help`") - )] - #[doc(hidden)] - #[must_use] - pub fn help>(self, help: S) -> Self { - self.override_help(help) - } - - /// Deprecated, replaced with [`Command::mut_arg`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") - )] - #[doc(hidden)] - #[must_use] - pub fn help_short(self, c: char) -> Self { - self.mut_arg("help", |a| a.short(c)) - } - - /// Deprecated, replaced with [`Command::mut_arg`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") - )] - #[doc(hidden)] - #[must_use] - pub fn version_short(self, c: char) -> Self { - self.mut_arg("version", |a| a.short(c)) - } - - /// Deprecated, replaced with [`Command::mut_arg`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") - )] - #[doc(hidden)] - #[must_use] - pub fn help_message(self, s: impl Into<&'help str>) -> Self { - self.mut_arg("help", |a| a.help(s.into())) - } - - /// Deprecated, replaced with [`Command::mut_arg`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`") - )] - #[doc(hidden)] - #[must_use] - pub fn version_message(self, s: impl Into<&'help str>) -> Self { - self.mut_arg("version", |a| a.help(s.into())) - } - - /// Deprecated, replaced with [`Command::help_template`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::help_template`") - )] - #[doc(hidden)] - #[must_use] - pub fn template>(self, s: S) -> Self { - self.help_template(s) - } - - /// Deprecated, replaced with [`Command::setting(a| b)`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::setting(a | b)`") - )] - #[doc(hidden)] - #[must_use] - pub fn settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.settings.insert((*s).into()); - } - self - } - - /// Deprecated, replaced with [`Command::unset_setting(a| b)`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::unset_setting(a | b)`") - )] - #[doc(hidden)] - #[must_use] - pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.settings.remove((*s).into()); - } - self - } - - /// Deprecated, replaced with [`Command::global_setting(a| b)`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::global_setting(a | b)`") - )] - #[doc(hidden)] - #[must_use] - pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.settings.insert((*s).into()); - self.g_settings.insert((*s).into()); - } - self - } - - /// Deprecated, replaced with [`Command::term_width`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::term_width`") - )] - #[doc(hidden)] - #[must_use] - pub fn set_term_width(self, width: usize) -> Self { - self.term_width(width) - } - - /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") - )] - #[doc(hidden)] - #[must_use] - pub fn arg_from_usage(self, usage: &'help str) -> Self { - #![allow(deprecated)] - self.arg(Arg::from_usage(usage)) - } - - /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!") - )] - #[doc(hidden)] - #[must_use] - pub fn args_from_usage(mut self, usage: &'help str) -> Self { - #![allow(deprecated)] - for line in usage.lines() { - let l = line.trim(); - if l.is_empty() { - continue; - } - self = self.arg(Arg::from_usage(l)); - } - self - } - - /// Deprecated, replaced with [`Command::render_version`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::render_version`") - )] - #[doc(hidden)] - pub fn write_version(&self, w: &mut W) -> ClapResult<()> { - write!(w, "{}", self.render_version()).map_err(From::from) - } - - /// Deprecated, replaced with [`Command::render_long_version`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::render_long_version`") - )] - #[doc(hidden)] - pub fn write_long_version(&self, w: &mut W) -> ClapResult<()> { - write!(w, "{}", self.render_long_version()).map_err(From::from) - } - - /// Deprecated, replaced with [`Command::try_get_matches`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches`") - )] - #[doc(hidden)] - pub fn get_matches_safe(self) -> ClapResult { - self.try_get_matches() - } - - /// Deprecated, replaced with [`Command::try_get_matches_from`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches_from`") - )] - #[doc(hidden)] - pub fn get_matches_from_safe(self, itr: I) -> ClapResult - where - I: IntoIterator, - T: Into + Clone, - { - self.try_get_matches_from(itr) - } - - /// Deprecated, replaced with [`Command::try_get_matches_from_mut`] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `App::try_get_matches_from_mut`" - ) - )] - #[doc(hidden)] - pub fn get_matches_from_safe_borrow(&mut self, itr: I) -> ClapResult - where - I: IntoIterator, - T: Into + Clone, - { - self.try_get_matches_from_mut(itr) - } -} - -// Internally used only -impl<'help> App<'help> { - pub(crate) fn get_id(&self) -> Id { - self.id.clone() - } - - pub(crate) fn get_override_usage(&self) -> Option<&str> { - self.usage_str - } - - pub(crate) fn get_override_help(&self) -> Option<&str> { - self.help_str - } - - pub(crate) fn get_help_template(&self) -> Option<&str> { - self.template - } - - pub(crate) fn get_term_width(&self) -> Option { - self.term_w - } - - pub(crate) fn get_max_term_width(&self) -> Option { - self.max_w - } - - pub(crate) fn get_replacement(&self, key: &str) -> Option<&[&str]> { - self.replacers.get(key).copied() - } - - pub(crate) fn get_keymap(&self) -> &MKeyMap<'help> { - &self.args - } - - fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec) { - global_arg_vec.extend( - self.args - .args() - .filter(|a| a.is_global_set()) - .map(|ga| ga.id.clone()), - ); - if let Some((id, matches)) = matches.subcommand() { - if let Some(used_sub) = self.find_subcommand(id) { - used_sub.get_used_global_args(matches, global_arg_vec); - } - } - } - - fn _do_parse( - &mut self, - raw_args: &mut clap_lex::RawArgs, - args_cursor: clap_lex::ArgCursor, - ) -> ClapResult { - debug!("Command::_do_parse"); - - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing in case we run into a subcommand - self._build_self(); - - let mut matcher = ArgMatcher::new(self); - - // do the real parsing - let mut parser = Parser::new(self); - if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { - if self.is_set(AppSettings::IgnoreErrors) { - debug!("Command::_do_parse: ignoring error: {}", error); - } else { - return Err(error); - } - } - - let mut global_arg_vec = Default::default(); - self.get_used_global_args(&matcher, &mut global_arg_vec); - - matcher.propagate_globals(&global_arg_vec); - - Ok(matcher.into_inner()) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.10", note = "Replaced with `Command::build`") - )] - pub fn _build_all(&mut self) { - self.build(); - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.10", note = "Replaced with `Command::build`") - )] - pub fn _build(&mut self) { - self._build_self() - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.13", note = "Replaced with `Command::build`") - )] - pub fn _build_bin_names(&mut self) { - self._build_bin_names_internal(); - } - - /// Prepare for introspecting on all included [`Command`]s - /// - /// Call this on the top-level [`Command`] when done building and before reading state for - /// cases like completions, custom help output, etc. - pub fn build(&mut self) { - self._build_recursive(); - self._build_bin_names_internal(); - } - - pub(crate) fn _build_recursive(&mut self) { - self._build_self(); - for subcmd in self.get_subcommands_mut() { - subcmd._build_recursive(); - } - } - - pub(crate) fn _build_self(&mut self) { - debug!("Command::_build: name={:?}", self.get_name()); - if !self.settings.is_set(AppSettings::Built) { - // Make sure all the globally set flags apply to us as well - self.settings = self.settings | self.g_settings; - - if self.is_multicall_set() { - self.settings.insert(AppSettings::SubcommandRequired.into()); - self.settings.insert(AppSettings::DisableHelpFlag.into()); - self.settings.insert(AppSettings::DisableVersionFlag.into()); - } - - self._propagate(); - self._check_help_and_version(); - self._propagate_global_args(); - self._derive_display_order(); - - let mut pos_counter = 1; - let self_override = self.is_set(AppSettings::AllArgsOverrideSelf); - let hide_pv = self.is_set(AppSettings::HidePossibleValues); - let auto_help = - !self.is_set(AppSettings::NoAutoHelp) && !self.is_disable_help_flag_set(); - let auto_version = - !self.is_set(AppSettings::NoAutoVersion) && !self.is_disable_version_flag_set(); - for a in self.args.args_mut() { - // Fill in the groups - for g in &a.groups { - if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { - ag.args.push(a.id.clone()); - } else { - let mut ag = ArgGroup::with_id(g.clone()); - ag.args.push(a.id.clone()); - self.groups.push(ag); - } - } - - // Figure out implied settings - if a.is_last_set() { - // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args - // in the usage string don't get confused or left out. - self.settings.set(AppSettings::DontCollapseArgsInUsage); - } - if hide_pv && a.is_takes_value_set() { - a.settings.set(ArgSettings::HidePossibleValues); - } - if self_override { - let self_id = a.id.clone(); - a.overrides.push(self_id); - } - a._build(); - // HACK: Setting up action at this level while auto-help / disable help flag is - // required. Otherwise, most of this won't be needed because when we can break - // compat, actions will reign supreme (default to `Store`) - if a.action.is_none() { - if a.get_id() == "help" && auto_help && !a.is_takes_value_set() { - let action = super::ArgAction::Help; - a.action = Some(action); - } else if a.get_id() == "version" && auto_version && !a.is_takes_value_set() { - let action = super::ArgAction::Version; - a.action = Some(action); - } else if a.is_takes_value_set() { - let action = super::ArgAction::StoreValue; - a.action = Some(action); - } else { - let action = super::ArgAction::IncOccurrence; - a.action = Some(action); - } - } - if a.is_positional() && a.index.is_none() { - a.index = Some(pos_counter); - pos_counter += 1; - } - } - - self.args._build(); - - #[cfg(debug_assertions)] - assert_app(self); - self.settings.set(AppSettings::Built); - } else { - debug!("Command::_build: already built"); - } - } - - pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { - use std::fmt::Write; - - let mut mid_string = String::from(" "); - if !self.is_subcommand_negates_reqs_set() { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(s); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let sc = self.subcommands.iter_mut().find(|s| s.name == name)?; - - // Display subcommand name, short and long in usage - let mut sc_names = sc.name.clone(); - let mut flag_subcmd = false; - if let Some(l) = sc.long_flag { - write!(sc_names, "|--{}", l).unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.short_flag { - write!(sc_names, "|-{}", s).unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{}}}", sc_names); - } - - let usage_name = self - .bin_name - .as_ref() - .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) - .unwrap_or(sc_names); - sc.usage_name = Some(usage_name); - - // bin_name should be parent's bin_name + [] + the sc's name separated by - // a space - let bin_name = format!( - "{}{}{}", - self.bin_name.as_ref().unwrap_or(&String::new()), - if self.bin_name.is_some() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } - - // Ensure all args are built and ready to parse - sc._build_self(); - - Some(sc) - } - - fn _build_bin_names_internal(&mut self) { - debug!("Command::_build_bin_names"); - - if !self.is_set(AppSettings::BinNameBuilt) { - let mut mid_string = String::from(" "); - if !self.is_subcommand_negates_reqs_set() { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(s); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let self_bin_name = if is_multicall_set { - self.bin_name.as_deref().unwrap_or("") - } else { - self.bin_name.as_deref().unwrap_or(&self.name) - } - .to_owned(); - - for mut sc in &mut self.subcommands { - debug!("Command::_build_bin_names:iter: bin_name set..."); - - if sc.usage_name.is_none() { - use std::fmt::Write; - // Display subcommand name, short and long in usage - let mut sc_names = sc.name.clone(); - let mut flag_subcmd = false; - if let Some(l) = sc.long_flag { - write!(sc_names, "|--{}", l).unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.short_flag { - write!(sc_names, "|-{}", s).unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{}}}", sc_names); - } - - let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names); - debug!( - "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", - sc.name, usage_name - ); - sc.usage_name = Some(usage_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", - sc.name, sc.usage_name - ); - } - - if sc.bin_name.is_none() { - let bin_name = format!( - "{}{}{}", - self_bin_name, - if !self_bin_name.is_empty() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", - sc.name, sc.bin_name - ); - } - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", - sc.name, sc.display_name - ); - } - - sc._build_bin_names_internal(); - } - self.set(AppSettings::BinNameBuilt); - } else { - debug!("Command::_build_bin_names: already built"); - } - } - - pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { - if self.is_set(AppSettings::HelpExpected) || help_required_globally { - let args_missing_help: Vec = self - .args - .args() - .filter(|arg| arg.help.is_none() && arg.long_help.is_none()) - .map(|arg| String::from(arg.name)) - .collect(); - - assert!(args_missing_help.is_empty(), - "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", - self.name, - args_missing_help.join(", ") - ); - } - - for sub_app in &self.subcommands { - sub_app._panic_on_missing_help(help_required_globally); - } - } - - #[cfg(debug_assertions)] - pub(crate) fn two_args_of(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)> - where - F: Fn(&Arg) -> bool, - { - two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) - } - - // just in case - #[allow(unused)] - fn two_groups_of(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> - where - F: Fn(&ArgGroup) -> bool, - { - two_elements_of(self.groups.iter().filter(|a| condition(a))) - } - - /// Propagate global args - pub(crate) fn _propagate_global_args(&mut self) { - debug!("Command::_propagate_global_args:{}", self.name); - - for sc in &mut self.subcommands { - for a in self.args.args().filter(|a| a.is_global_set()) { - let mut propagate = false; - let is_generated = matches!( - a.provider, - ArgProvider::Generated | ArgProvider::GeneratedMutated - ); - - // Remove generated help and version args in the subcommand - // - // Don't remove if those args are further mutated - if is_generated { - let generated_pos = sc - .args - .args() - .position(|x| x.id == a.id && x.provider == ArgProvider::Generated); - - if let Some(index) = generated_pos { - debug!( - "Command::_propagate removing {}'s {:?}", - sc.get_name(), - a.id - ); - sc.args.remove(index); - propagate = true; - } - } - - if propagate || sc.find(&a.id).is_none() { - debug!( - "Command::_propagate pushing {:?} to {}", - a.id, - sc.get_name(), - ); - sc.args.push(a.clone()); - } - } - } - } - - /// Propagate settings - pub(crate) fn _propagate(&mut self) { - debug!("Command::_propagate:{}", self.name); - let mut subcommands = std::mem::take(&mut self.subcommands); - for sc in &mut subcommands { - self._propagate_subcommand(sc); - } - self.subcommands = subcommands; - } - - fn _propagate_subcommand(&self, sc: &mut Self) { - // We have to create a new scope in order to tell rustc the borrow of `sc` is - // done and to recursively call this method - { - if self.settings.is_set(AppSettings::PropagateVersion) { - if sc.version.is_none() && self.version.is_some() { - sc.version = Some(self.version.unwrap()); - } - if sc.long_version.is_none() && self.long_version.is_some() { - sc.long_version = Some(self.long_version.unwrap()); - } - } - - sc.settings = sc.settings | self.g_settings; - sc.g_settings = sc.g_settings | self.g_settings; - sc.term_w = self.term_w; - sc.max_w = self.max_w; - } - } - - #[allow(clippy::blocks_in_if_conditions)] - pub(crate) fn _check_help_and_version(&mut self) { - debug!("Command::_check_help_and_version: {}", self.name); - - if self.is_set(AppSettings::DisableHelpFlag) - || self.args.args().any(|x| { - x.provider == ArgProvider::User - && (x.long == Some("help") || x.id == Id::help_hash()) - }) - || self - .subcommands - .iter() - .any(|sc| sc.long_flag == Some("help")) - { - debug!("Command::_check_help_and_version: Removing generated help"); - - let generated_help_pos = self - .args - .args() - .position(|x| x.id == Id::help_hash() && x.provider == ArgProvider::Generated); - - if let Some(index) = generated_help_pos { - self.args.remove(index); - } - } else { - let help = self - .args - .args() - .find(|x| x.id == Id::help_hash()) - .expect(INTERNAL_ERROR_MSG); - assert_ne!(help.provider, ArgProvider::User); - - if help.short.is_some() { - if help.short == Some('h') { - if let Some(other_arg) = self - .args - .args() - .find(|x| x.id != Id::help_hash() && x.short == Some('h')) - { - panic!( - "`help`s `-h` conflicts with `{}`. - -To change `help`s short, call `cmd.arg(Arg::new(\"help\")...)`.", - other_arg.name - ); - } - } - } else if !(self.args.args().any(|x| x.short == Some('h')) - || self.subcommands.iter().any(|sc| sc.short_flag == Some('h'))) - { - let help = self - .args - .args_mut() - .find(|x| x.id == Id::help_hash()) - .expect(INTERNAL_ERROR_MSG); - help.short = Some('h'); - } else { - debug!("Command::_check_help_and_version: Removing `-h` from help"); - } - } - - // Determine if we should remove the generated --version flag - // - // Note that if only mut_arg() was used, the first expression will evaluate to `true` - // however inside the condition block, we only check for Generated args, not - // GeneratedMutated args, so the `mut_arg("version", ..) will be skipped and fall through - // to the following condition below (Adding the short `-V`) - if self.settings.is_set(AppSettings::DisableVersionFlag) - || (self.version.is_none() && self.long_version.is_none()) - || self.args.args().any(|x| { - x.provider == ArgProvider::User - && (x.long == Some("version") || x.id == Id::version_hash()) - }) - || self - .subcommands - .iter() - .any(|sc| sc.long_flag == Some("version")) - { - debug!("Command::_check_help_and_version: Removing generated version"); - - // This is the check mentioned above that only checks for Generated, not - // GeneratedMutated args by design. - let generated_version_pos = self - .args - .args() - .position(|x| x.id == Id::version_hash() && x.provider == ArgProvider::Generated); - - if let Some(index) = generated_version_pos { - self.args.remove(index); - } - } - - // If we still have a generated --version flag, determine if we can apply the short `-V` - if self.args.args().any(|x| { - x.id == Id::version_hash() - && matches!( - x.provider, - ArgProvider::Generated | ArgProvider::GeneratedMutated - ) - }) { - let other_arg_has_short = self.args.args().any(|x| x.short == Some('V')); - let version = self - .args - .args_mut() - .find(|x| x.id == Id::version_hash()) - .expect(INTERNAL_ERROR_MSG); - - if !(version.short.is_some() - || other_arg_has_short - || self.subcommands.iter().any(|sc| sc.short_flag == Some('V'))) - { - version.short = Some('V'); - } - } - - if !self.is_set(AppSettings::DisableHelpSubcommand) - && self.has_subcommands() - && !self.subcommands.iter().any(|s| s.id == Id::help_hash()) - { - debug!("Command::_check_help_and_version: Building help subcommand"); - let mut help_subcmd = App::new("help") - .about("Print this message or the help of the given subcommand(s)") - .arg( - Arg::new("subcommand") - .index(1) - .takes_value(true) - .multiple_occurrences(true) - .value_name("SUBCOMMAND") - .help("The subcommand whose help message to display"), - ); - self._propagate_subcommand(&mut help_subcmd); - - // The parser acts like this is set, so let's set it so we don't falsely - // advertise it to the user - help_subcmd.version = None; - help_subcmd.long_version = None; - help_subcmd = help_subcmd - .setting(AppSettings::DisableHelpFlag) - .unset_global_setting(AppSettings::PropagateVersion); - - self.subcommands.push(help_subcmd); - } - } - - pub(crate) fn _derive_display_order(&mut self) { - debug!("Command::_derive_display_order:{}", self.name); - - if self.settings.is_set(AppSettings::DeriveDisplayOrder) { - for a in self - .args - .args_mut() - .filter(|a| !a.is_positional()) - .filter(|a| a.provider != ArgProvider::Generated) - { - a.disp_ord.make_explicit(); - } - for (i, sc) in &mut self.subcommands.iter_mut().enumerate() { - sc.disp_ord.get_or_insert(i); - } - } - for sc in &mut self.subcommands { - sc._derive_display_order(); - } - } - - pub(crate) fn _render_version(&self, use_long: bool) -> String { - debug!("Command::_render_version"); - - let ver = if use_long { - self.long_version.or(self.version).unwrap_or("") - } else { - self.version.or(self.long_version).unwrap_or("") - }; - if let Some(bn) = self.bin_name.as_ref() { - if bn.contains(' ') { - // In case we're dealing with subcommands i.e. git mv is translated to git-mv - format!("{} {}\n", bn.replace(' ', "-"), ver) - } else { - format!("{} {}\n", &self.name[..], ver) - } - } else { - format!("{} {}\n", &self.name[..], ver) - } - } - - pub(crate) fn format_group(&self, g: &Id) -> String { - let g_string = self - .unroll_args_in_group(g) - .iter() - .filter_map(|x| self.find(x)) - .map(|x| { - if x.is_positional() { - // Print val_name for positional arguments. e.g. - x.name_no_brackets().to_string() - } else { - // Print usage string for flags arguments, e.g. <--help> - x.to_string() - } - }) - .collect::>() - .join("|"); - format!("<{}>", &*g_string) - } -} - -/// A workaround: -/// -pub(crate) trait Captures<'a> {} -impl<'a, T> Captures<'a> for T {} - -// Internal Query Methods -impl<'help> App<'help> { - /// Iterate through the *flags* & *options* arguments. - pub(crate) fn get_non_positionals(&self) -> impl Iterator> { - self.get_arguments().filter(|a| !a.is_positional()) - } - - /// Iterate through the *positionals* that don't have custom heading. - pub(crate) fn get_positionals_with_no_heading(&self) -> impl Iterator> { - self.get_positionals() - .filter(|a| a.get_help_heading().is_none()) - } - - /// Iterate through the *flags* & *options* that don't have custom heading. - pub(crate) fn get_non_positionals_with_no_heading(&self) -> impl Iterator> { - self.get_non_positionals() - .filter(|a| a.get_help_heading().is_none()) - } - - pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> { - self.args.args().find(|a| a.id == *arg_id) - } - - #[inline] - pub(crate) fn contains_short(&self, s: char) -> bool { - assert!( - self.is_set(AppSettings::Built), - "If App::_build hasn't been called, manually search through Arg shorts" - ); - - self.args.contains(s) - } - - #[inline] - pub(crate) fn set(&mut self, s: AppSettings) { - self.settings.set(s) - } - - #[inline] - pub(crate) fn has_args(&self) -> bool { - !self.args.is_empty() - } - - pub(crate) fn has_positionals(&self) -> bool { - self.args.keys().any(|x| x.is_position()) - } - - pub(crate) fn has_visible_subcommands(&self) -> bool { - self.subcommands - .iter() - .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this subcommand or is one of its aliases. - #[inline] - pub(crate) fn aliases_to(&self, name: &T) -> bool - where - T: PartialEq + ?Sized, - { - *name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. - #[inline] - pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { - Some(flag) == self.short_flag - || self.get_all_short_flag_aliases().any(|alias| flag == alias) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. - #[inline] - pub(crate) fn long_flag_aliases_to(&self, flag: &T) -> bool - where - T: PartialEq + ?Sized, - { - match self.long_flag { - Some(long_flag) => { - flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias) - } - None => self.get_all_long_flag_aliases().any(|alias| flag == alias), - } - } - - #[cfg(debug_assertions)] - pub(crate) fn id_exists(&self, id: &Id) -> bool { - self.args.args().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id) - } - - /// Iterate through the groups this arg is member of. - pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator + 'a { - debug!("Command::groups_for_arg: id={:?}", arg); - let arg = arg.clone(); - self.groups - .iter() - .filter(move |grp| grp.args.iter().any(|a| a == &arg)) - .map(|grp| grp.id.clone()) - } - - pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup<'help>> { - self.groups.iter().find(|g| g.id == *group_id) - } - - /// Iterate through all the names of all subcommands (not recursively), including aliases. - /// Used for suggestions. - pub(crate) fn all_subcommand_names(&self) -> impl Iterator + Captures<'help> { - self.get_subcommands().flat_map(|sc| { - let name = sc.get_name(); - let aliases = sc.get_all_aliases(); - std::iter::once(name).chain(aliases) - }) - } - - pub(crate) fn required_graph(&self) -> ChildGraph { - let mut reqs = ChildGraph::with_capacity(5); - for a in self.args.args().filter(|a| a.is_required_set()) { - reqs.insert(a.id.clone()); - } - for group in &self.groups { - if group.required { - let idx = reqs.insert(group.id.clone()); - for a in &group.requires { - reqs.insert_child(idx, a.clone()); - } - } - } - - reqs - } - - pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec { - debug!("Command::unroll_args_in_group: group={:?}", group); - let mut g_vec = vec![group]; - let mut args = vec![]; - - while let Some(g) = g_vec.pop() { - for n in self - .groups - .iter() - .find(|grp| grp.id == *g) - .expect(INTERNAL_ERROR_MSG) - .args - .iter() - { - debug!("Command::unroll_args_in_group:iter: entity={:?}", n); - if !args.contains(n) { - if self.find(n).is_some() { - debug!("Command::unroll_args_in_group:iter: this is an arg"); - args.push(n.clone()) - } else { - debug!("Command::unroll_args_in_group:iter: this is a group"); - g_vec.push(n); - } - } - } - } - - args - } - - pub(crate) fn unroll_arg_requires(&self, func: F, arg: &Id) -> Vec - where - F: Fn(&(ArgPredicate<'_>, Id)) -> Option, - { - let mut processed = vec![]; - let mut r_vec = vec![arg]; - let mut args = vec![]; - - while let Some(a) = r_vec.pop() { - if processed.contains(&a) { - continue; - } - - processed.push(a); - - if let Some(arg) = self.find(a) { - for r in arg.requires.iter().filter_map(&func) { - if let Some(req) = self.find(&r) { - if !req.requires.is_empty() { - r_vec.push(&req.id) - } - } - args.push(r); - } - } - } - - args - } - - /// Find a flag subcommand name by short flag or an alias - pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.short_flag_aliases_to(c)) - .map(|sc| sc.get_name()) - } - - /// Find a flag subcommand name by long flag or an alias - pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.long_flag_aliases_to(long)) - .map(|sc| sc.get_name()) - } - - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.unwrap_or(999) - } - - pub(crate) fn write_help_err( - &self, - mut use_long: bool, - stream: Stream, - ) -> ClapResult { - debug!( - "Parser::write_help_err: use_long={:?}, stream={:?}", - use_long && self.use_long_help(), - stream - ); - - use_long = use_long && self.use_long_help(); - let usage = Usage::new(self); - - let mut c = Colorizer::new(stream, self.color_help()); - Help::new(HelpWriter::Buffer(&mut c), self, &usage, use_long).write_help()?; - Ok(c) - } - - pub(crate) fn use_long_help(&self) -> bool { - debug!("Command::use_long_help"); - // In this case, both must be checked. This allows the retention of - // original formatting, but also ensures that the actual -h or --help - // specified by the user is sent through. If hide_short_help is not included, - // then items specified with hidden_short_help will also be hidden. - let should_long = |v: &Arg| { - v.long_help.is_some() - || v.is_hide_long_help_set() - || v.is_hide_short_help_set() - || cfg!(feature = "unstable-v4") - && v.get_possible_values2() - .iter() - .any(PossibleValue::should_show_help) - }; - - // Subcommands aren't checked because we prefer short help for them, deferring to - // `cmd subcmd --help` for more. - self.get_long_about().is_some() - || self.get_before_long_help().is_some() - || self.get_after_long_help().is_some() - || self.get_arguments().any(should_long) - } - - // Should we color the help? - pub(crate) fn color_help(&self) -> ColorChoice { - #[cfg(feature = "color")] - if self.is_disable_colored_help_set() { - return ColorChoice::Never; - } - - self.get_color() - } -} - -impl<'help> Default for App<'help> { - fn default() -> Self { - Self { - id: Default::default(), - name: Default::default(), - long_flag: Default::default(), - short_flag: Default::default(), - display_name: Default::default(), - bin_name: Default::default(), - author: Default::default(), - version: Default::default(), - long_version: Default::default(), - about: Default::default(), - long_about: Default::default(), - before_help: Default::default(), - before_long_help: Default::default(), - after_help: Default::default(), - after_long_help: Default::default(), - aliases: Default::default(), - short_flag_aliases: Default::default(), - long_flag_aliases: Default::default(), - usage_str: Default::default(), - usage_name: Default::default(), - help_str: Default::default(), - disp_ord: Default::default(), - term_w: Default::default(), - max_w: Default::default(), - template: Default::default(), - settings: Default::default(), - g_settings: Default::default(), - args: Default::default(), - subcommands: Default::default(), - replacers: Default::default(), - groups: Default::default(), - current_help_heading: Default::default(), - current_disp_ord: Some(0), - subcommand_value_name: Default::default(), - subcommand_heading: Default::default(), - } - } -} - -impl<'help> Index<&'_ Id> for App<'help> { - type Output = Arg<'help>; - - fn index(&self, key: &Id) -> &Self::Output { - self.find(key).expect(INTERNAL_ERROR_MSG) - } -} - -impl fmt::Display for App<'_> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.name) - } -} - -fn two_elements_of(mut iter: I) -> Option<(T, T)> -where - I: Iterator, -{ - let first = iter.next(); - let second = iter.next(); - - match (first, second) { - (Some(first), Some(second)) => Some((first, second)), - _ => None, - } -} diff --git a/vendor/clap/src/builder/debug_asserts.rs b/vendor/clap/src/builder/debug_asserts.rs deleted file mode 100644 index 864b8b479..000000000 --- a/vendor/clap/src/builder/debug_asserts.rs +++ /dev/null @@ -1,851 +0,0 @@ -use std::cmp::Ordering; - -use clap_lex::RawOsStr; - -use crate::builder::arg::ArgProvider; -use crate::mkeymap::KeyType; -use crate::ArgAction; -use crate::{Arg, Command, ValueHint}; - -pub(crate) fn assert_app(cmd: &Command) { - debug!("Command::_debug_asserts"); - - let mut short_flags = vec![]; - let mut long_flags = vec![]; - - // Invalid version flag settings - if cmd.get_version().is_none() && cmd.get_long_version().is_none() { - // PropagateVersion is meaningless if there is no version - assert!( - !cmd.is_propagate_version_set(), - "Command {}: No version information via Command::version or Command::long_version to propagate", - cmd.get_name(), - ); - - // Used `Command::mut_arg("version", ..) but did not provide any version information to display - let version_needed = cmd - .get_arguments() - .filter(|x| { - let action_set = matches!(x.get_action(), ArgAction::Version); - #[cfg(not(feature = "unstable-v4"))] - let provider_set = matches!(x.provider, ArgProvider::GeneratedMutated); - #[cfg(feature = "unstable-v4")] - let provider_set = matches!( - x.provider, - ArgProvider::User | ArgProvider::GeneratedMutated - ); - action_set && provider_set - }) - .map(|x| x.get_id()) - .collect::>(); - - assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" - ,cmd.get_name() - ); - } - - for sc in cmd.get_subcommands() { - if let Some(s) = sc.get_short_flag().as_ref() { - short_flags.push(Flag::Command(format!("-{}", s), sc.get_name())); - } - - for short_alias in sc.get_all_short_flag_aliases() { - short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name())); - } - - if let Some(l) = sc.get_long_flag().as_ref() { - #[cfg(feature = "unstable-v4")] - { - assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); - } - long_flags.push(Flag::Command(format!("--{}", l), sc.get_name())); - } - - for long_alias in sc.get_all_long_flag_aliases() { - long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name())); - } - } - - for arg in cmd.get_arguments() { - assert_arg(arg); - - assert!( - !cmd.is_multicall_set(), - "Command {}: Arguments like {} cannot be set on a multicall command", - cmd.get_name(), - arg.name - ); - - if let Some(s) = arg.short.as_ref() { - short_flags.push(Flag::Arg(format!("-{}", s), &*arg.name)); - } - - for (short_alias, _) in &arg.short_aliases { - short_flags.push(Flag::Arg(format!("-{}", short_alias), arg.name)); - } - - if let Some(l) = arg.long.as_ref() { - #[cfg(feature = "unstable-v4")] - { - assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.name, l); - } - long_flags.push(Flag::Arg(format!("--{}", l), &*arg.name)); - } - - for (long_alias, _) in &arg.aliases { - long_flags.push(Flag::Arg(format!("--{}", long_alias), arg.name)); - } - - // Name conflicts - assert!( - cmd.two_args_of(|x| x.id == arg.id).is_none(), - "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group", - cmd.get_name(), - arg.name, - ); - - // Long conflicts - if let Some(l) = arg.long { - if let Some((first, second)) = cmd.two_args_of(|x| x.long == Some(l)) { - panic!( - "Command {}: Long option names must be unique for each argument, \ - but '--{}' is in use by both '{}' and '{}'", - cmd.get_name(), - l, - first.name, - second.name - ) - } - } - - // Short conflicts - if let Some(s) = arg.short { - if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) { - panic!( - "Command {}: Short option names must be unique for each argument, \ - but '-{}' is in use by both '{}' and '{}'", - cmd.get_name(), - s, - first.name, - second.name - ) - } - } - - // Index conflicts - if let Some(idx) = arg.index { - if let Some((first, second)) = - cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx)) - { - panic!( - "Command {}: Argument '{}' has the same index as '{}' \ - and they are both positional arguments\n\n\t \ - Use Arg::multiple_values(true) to allow one \ - positional argument to take multiple values", - cmd.get_name(), - first.name, - second.name - ) - } - } - - // requires, r_if, r_unless - for req in &arg.requires { - assert!( - cmd.id_exists(&req.1), - "Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist", - cmd.get_name(), - req.1, - arg.name, - ); - } - - for req in &arg.r_ifs { - #[cfg(feature = "unstable-v4")] - { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq*`", - arg.name - ); - } - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.name - ); - } - - for req in &arg.r_ifs_all { - #[cfg(feature = "unstable-v4")] - { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq_all`", - arg.name - ); - } - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.name - ); - } - - for req in &arg.r_unless { - #[cfg(feature = "unstable-v4")] - { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.name - ); - } - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.name, - ); - } - - for req in &arg.r_unless_all { - #[cfg(feature = "unstable-v4")] - { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.name - ); - } - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.name, - ); - } - - // blacklist - for req in &arg.blacklist { - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist", - cmd.get_name(), - req, - arg.name, - ); - } - - if arg.is_last_set() { - assert!( - arg.long.is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", - cmd.get_name(), - arg.name - ); - assert!( - arg.short.is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", - cmd.get_name(), - arg.name - ); - } - - assert!( - !(arg.is_required_set() && arg.is_global_set()), - "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", - cmd.get_name(), - arg.name - ); - - // validators - assert!( - arg.validator.is_none() || arg.validator_os.is_none(), - "Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed", - cmd.get_name(), - arg.name - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_positional(), - "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", - cmd.get_name(), - arg.name - ); - - assert!( - cmd.is_trailing_var_arg_set(), - "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.", - cmd.get_name(), - arg.name - ); - } - } - - for group in cmd.get_groups() { - // Name conflicts - assert!( - cmd.get_groups().filter(|x| x.id == group.id).count() < 2, - "Command {}: Argument group name must be unique\n\n\t'{}' is already in use", - cmd.get_name(), - group.name, - ); - - // Groups should not have naming conflicts with Args - assert!( - !cmd.get_arguments().any(|x| x.id == group.id), - "Command {}: Argument group name '{}' must not conflict with argument name", - cmd.get_name(), - group.name, - ); - - for arg in &group.args { - // Args listed inside groups should exist - assert!( - cmd.get_arguments().any(|x| x.id == *arg), - "Command {}: Argument group '{}' contains non-existent argument '{:?}'", - cmd.get_name(), - group.name, - arg - ); - } - } - - // Conflicts between flags and subcommands - - long_flags.sort_unstable(); - short_flags.sort_unstable(); - - detect_duplicate_flags(&long_flags, "long"); - detect_duplicate_flags(&short_flags, "short"); - - _verify_positionals(cmd); - - if let Some(help_template) = cmd.get_help_template() { - assert!( - !help_template.contains("{flags}"), - "Command {}: {}", - cmd.get_name(), - "`{flags}` template variable was removed in clap3, they are now included in `{options}`", - ); - assert!( - !help_template.contains("{unified}"), - "Command {}: {}", - cmd.get_name(), - "`{unified}` template variable was removed in clap3, use `{options}` instead" - ); - } - - cmd._panic_on_missing_help(cmd.is_help_expected_set()); - assert_app_flags(cmd); -} - -#[derive(Eq)] -enum Flag<'a> { - Command(String, &'a str), - Arg(String, &'a str), -} - -impl PartialEq for Flag<'_> { - fn eq(&self, other: &Flag) -> bool { - self.cmp(other) == Ordering::Equal - } -} - -impl PartialOrd for Flag<'_> { - fn partial_cmp(&self, other: &Flag) -> Option { - use Flag::*; - - match (self, other) { - (Command(s1, _), Command(s2, _)) - | (Arg(s1, _), Arg(s2, _)) - | (Command(s1, _), Arg(s2, _)) - | (Arg(s1, _), Command(s2, _)) => { - if s1 == s2 { - Some(Ordering::Equal) - } else { - s1.partial_cmp(s2) - } - } - } - } -} - -impl Ord for Flag<'_> { - fn cmp(&self, other: &Self) -> Ordering { - self.partial_cmp(other).unwrap() - } -} - -fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { - use Flag::*; - - for (one, two) in find_duplicates(flags) { - match (one, two) { - (Command(flag, one), Command(_, another)) if one != another => panic!( - "the '{}' {} flag is specified for both '{}' and '{}' subcommands", - flag, short_or_long, one, another - ), - - (Arg(flag, one), Arg(_, another)) if one != another => panic!( - "{} option names must be unique, but '{}' is in use by both '{}' and '{}'", - short_or_long, flag, one, another - ), - - (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( - "the '{}' {} flag for the '{}' argument conflicts with the short flag \ - for '{}' subcommand", - flag, short_or_long, arg, sub - ), - - _ => {} - } - } -} - -/// Find duplicates in a sorted array. -/// -/// The algorithm is simple: the array is sorted, duplicates -/// must be placed next to each other, we can check only adjacent elements. -fn find_duplicates(slice: &[T]) -> impl Iterator { - slice.windows(2).filter_map(|w| { - if w[0] == w[1] { - Some((&w[0], &w[1])) - } else { - None - } - }) -} - -fn assert_app_flags(cmd: &Command) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if cmd.$a() { - let mut s = String::new(); - - $( - if !cmd.$b() { - s.push_str(&format!(" AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a))); - } - )+ - - if !s.is_empty() { - panic!("{}", s) - } - } - }; - ($a:ident conflicts $($b:ident)|+) => { - if cmd.$a() { - let mut s = String::new(); - - $( - if cmd.$b() { - s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a))); - } - )+ - - if !s.is_empty() { - panic!("{}\n{}", cmd.get_name(), s) - } - } - }; - } - - checker!(is_allow_invalid_utf8_for_external_subcommands_set requires is_allow_external_subcommands_set); - checker!(is_multicall_set conflicts is_no_binary_name_set); -} - -#[cfg(debug_assertions)] -fn _verify_positionals(cmd: &Command) -> bool { - debug!("Command::_verify_positionals"); - // Because you must wait until all arguments have been supplied, this is the first chance - // to make assertions on positional argument indexes - // - // First we verify that the index highest supplied index, is equal to the number of - // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 - // but no 2) - - let highest_idx = cmd - .get_keymap() - .keys() - .filter_map(|x| { - if let KeyType::Position(n) = x { - Some(*n) - } else { - None - } - }) - .max() - .unwrap_or(0); - - let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); - - assert!( - highest_idx == num_p, - "Found positional argument whose index is {} but there \ - are only {} positional arguments defined", - highest_idx, - num_p - ); - - // Next we verify that only the highest index has takes multiple arguments (if any) - let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx); - if cmd.get_positionals().any(only_highest) { - // First we make sure if there is a positional that allows multiple values - // the one before it (second to last) has one of these: - // * a value terminator - // * ArgSettings::Last - // * The last arg is Required - - // We can't pass the closure (it.next()) to the macro directly because each call to - // find() (iterator, not macro) gets called repeatedly. - let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; - let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; - - // Either the final positional is required - // Or the second to last has a terminator or .last(true) set - let ok = last.is_required_set() - || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) - || last.is_last_set(); - assert!( - ok, - "When using a positional argument with .multiple_values(true) that is *not the \ - last* positional argument, the last positional argument (i.e. the one \ - with the highest index) *must* have .required(true) or .last(true) set." - ); - - // We make sure if the second to last is Multiple the last is ArgSettings::Last - let ok = second_to_last.is_multiple() || last.is_last_set(); - assert!( - ok, - "Only the last positional argument, or second to last positional \ - argument may be set to .multiple_values(true)" - ); - - // Next we check how many have both Multiple and not a specific number of values set - let count = cmd - .get_positionals() - .filter(|p| { - #[allow(deprecated)] - { - p.is_multiple_occurrences_set() - || (p.is_multiple_values_set() && p.num_vals.is_none()) - } - }) - .count(); - let ok = count <= 1 - || (last.is_last_set() - && last.is_multiple() - && second_to_last.is_multiple() - && count == 2); - assert!( - ok, - "Only one positional argument with .multiple_values(true) set is allowed per \ - command, unless the second one also has .last(true) set" - ); - } - - let mut found = false; - - if cmd.is_allow_missing_positional_set() { - // Check that if a required positional argument is found, all positions with a lower - // index are also required. - let mut foundx2 = false; - - for p in cmd.get_positionals() { - if foundx2 && !p.is_required_set() { - assert!( - p.is_required_set(), - "Found non-required positional argument with a lower \ - index than a required positional argument by two or more: {:?} \ - index {:?}", - p.name, - p.index - ); - } else if p.is_required_set() && !p.is_last_set() { - // Args that .last(true) don't count since they can be required and have - // positionals with a lower index that aren't required - // Imagine: prog [opt1] -- - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - if found { - foundx2 = true; - continue; - } - found = true; - continue; - } else { - found = false; - } - } - } else { - // Check that if a required positional argument is found, all positions with a lower - // index are also required - for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { - if found { - assert!( - p.is_required_set(), - "Found non-required positional argument with a lower \ - index than a required positional argument: {:?} index {:?}", - p.name, - p.index - ); - } else if p.is_required_set() && !p.is_last_set() { - // Args that .last(true) don't count since they can be required and have - // positionals with a lower index that aren't required - // Imagine: prog [opt1] -- - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - found = true; - continue; - } - } - } - assert!( - cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, - "Only one positional argument may have last(true) set. Found two." - ); - if cmd - .get_positionals() - .any(|p| p.is_last_set() && p.is_required_set()) - && cmd.has_subcommands() - && !cmd.is_subcommand_negates_reqs_set() - { - panic!( - "Having a required positional argument with .last(true) set *and* child \ - subcommands without setting SubcommandsNegateReqs isn't compatible." - ); - } - - true -} - -fn assert_arg(arg: &Arg) { - debug!("Arg::_debug_asserts:{}", arg.name); - - // Self conflict - // TODO: this check should be recursive - assert!( - !arg.blacklist.iter().any(|x| *x == arg.id), - "Argument '{}' cannot conflict with itself", - arg.name, - ); - - assert_eq!( - arg.get_action().takes_values(), - arg.is_takes_value_set(), - "Argument `{}`'s selected action {:?} contradicts `takes_value`", - arg.name, - arg.get_action() - ); - if let Some(action_type_id) = arg.get_action().value_type_id() { - assert_eq!( - action_type_id, - arg.get_value_parser().type_id(), - "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", - arg.name, - arg.get_action(), - arg.get_value_parser() - ); - } - - if arg.get_value_hint() != ValueHint::Unknown { - assert!( - arg.is_takes_value_set(), - "Argument '{}' has value hint but takes no value", - arg.name - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_multiple_values_set(), - "Argument '{}' uses hint CommandWithArguments and must accept multiple values", - arg.name - ) - } - } - - if arg.index.is_some() { - assert!( - arg.is_positional(), - "Argument '{}' is a positional argument and can't have short or long name versions", - arg.name - ); - assert!( - arg.is_takes_value_set(), - "Argument '{}` is positional, it must take a value", - arg.name - ); - } - - #[cfg(feature = "unstable-v4")] - { - let num_vals = arg.get_num_vals().unwrap_or(usize::MAX); - let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); - if num_vals < num_val_names { - panic!( - "Argument {}: Too many value names ({}) compared to number_of_values ({})", - arg.name, num_val_names, num_vals - ); - } - } - - assert_arg_flags(arg); - - assert_defaults(arg, "default_value", arg.default_vals.iter().copied()); - assert_defaults( - arg, - "default_missing_value", - arg.default_missing_vals.iter().copied(), - ); - assert_defaults( - arg, - "default_value_if", - arg.default_vals_ifs - .iter() - .filter_map(|(_, _, default)| *default), - ); -} - -fn assert_arg_flags(arg: &Arg) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if arg.$a() { - let mut s = String::new(); - - $( - if !arg.$b() { - s.push_str(&format!(" Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a))); - } - )+ - - if !s.is_empty() { - panic!("Argument {:?}\n{}", arg.get_id(), s) - } - } - } - } - - checker!(is_require_value_delimiter_set requires is_takes_value_set); - checker!(is_require_value_delimiter_set requires is_use_value_delimiter_set); - checker!(is_hide_possible_values_set requires is_takes_value_set); - checker!(is_allow_hyphen_values_set requires is_takes_value_set); - checker!(is_require_equals_set requires is_takes_value_set); - checker!(is_last_set requires is_takes_value_set); - checker!(is_hide_default_value_set requires is_takes_value_set); - checker!(is_multiple_values_set requires is_takes_value_set); - checker!(is_ignore_case_set requires is_takes_value_set); - { - #![allow(deprecated)] - checker!(is_forbid_empty_values_set requires is_takes_value_set); - checker!(is_allow_invalid_utf8_set requires is_takes_value_set); - } -} - -fn assert_defaults<'d>( - arg: &Arg, - field: &'static str, - defaults: impl IntoIterator, -) { - for default_os in defaults { - if let Some(default_s) = default_os.to_str() { - if !arg.possible_vals.is_empty() { - if let Some(delim) = arg.get_value_delimiter() { - for part in default_s.split(delim) { - assert!( - arg.possible_vals.iter().any(|possible_val| { - possible_val.matches(part, arg.is_ignore_case_set()) - }), - "Argument `{}`'s {}={} doesn't match possible values", - arg.name, - field, - part - ) - } - } else { - assert!( - arg.possible_vals.iter().any(|possible_val| { - possible_val.matches(default_s, arg.is_ignore_case_set()) - }), - "Argument `{}`'s {}={} doesn't match possible values", - arg.name, - field, - default_s - ); - } - } - - if let Some(validator) = arg.validator.as_ref() { - let mut validator = validator.lock().unwrap(); - if let Some(delim) = arg.get_value_delimiter() { - for part in default_s.split(delim) { - if let Err(err) = validator(part) { - panic!( - "Argument `{}`'s {}={} failed validation: {}", - arg.name, field, part, err - ); - } - } - } else if let Err(err) = validator(default_s) { - panic!( - "Argument `{}`'s {}={} failed validation: {}", - arg.name, field, default_s, err - ); - } - } - } - - if let Some(validator) = arg.validator_os.as_ref() { - let mut validator = validator.lock().unwrap(); - if let Some(delim) = arg.get_value_delimiter() { - let default_os = RawOsStr::new(default_os); - for part in default_os.split(delim) { - if let Err(err) = validator(&part.to_os_str()) { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.name, field, part, err - ); - } - } - } else if let Err(err) = validator(default_os) { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.name, field, default_os, err - ); - } - } - - let value_parser = arg.get_value_parser(); - let assert_cmd = Command::new("assert"); - if let Some(delim) = arg.get_value_delimiter() { - let default_os = RawOsStr::new(default_os); - for part in default_os.split(delim) { - if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str()) - { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.name, - field, - part.to_str_lossy(), - err - ); - } - } - } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.name, field, default_os, err - ); - } - } -} diff --git a/vendor/clap/src/builder/macros.rs b/vendor/clap/src/builder/macros.rs deleted file mode 100644 index 5be4d205e..000000000 --- a/vendor/clap/src/builder/macros.rs +++ /dev/null @@ -1,180 +0,0 @@ -#[cfg(feature = "yaml")] -macro_rules! yaml_tuple2 { - ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(2, tup.len()); - $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); - } else { - panic!("Failed to convert YAML value to vec"); - } - } - } else { - panic!("Failed to convert YAML value to vec"); - } - $a - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_tuple3 { - ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(3, tup.len()); - $a = $a.$c( - yaml_str!(tup[0]), - yaml_opt_str!(tup[1]), - yaml_opt_str!(tup[2]), - ); - } else { - panic!("Failed to convert YAML value to vec"); - } - } - } else { - panic!("Failed to convert YAML value to vec"); - } - $a - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_vec_or_str { - ($a:ident, $v:ident, $c:ident) => {{ - let maybe_vec = $v.as_vec(); - if let Some(vec) = maybe_vec { - for ys in vec { - if let Some(s) = ys.as_str() { - $a = $a.$c(s); - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - } - } else { - if let Some(s) = $v.as_str() { - $a = $a.$c(s); - } else { - panic!( - "Failed to convert YAML value {:?} to either a vec or string", - $v - ); - } - } - $a - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_vec { - ($a:ident, $v:ident, $c:ident) => {{ - let maybe_vec = $v.as_vec(); - if let Some(vec) = maybe_vec { - let content = vec.into_iter().map(|ys| { - if let Some(s) = ys.as_str() { - s - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - }); - $a = $a.$c(content) - } else { - panic!("Failed to convert YAML value {:?} to a vec", $v); - } - $a - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_opt_str { - ($v:expr) => {{ - if !$v.is_null() { - Some( - $v.as_str() - .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), - ) - } else { - None - } - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_char { - ($v:expr) => {{ - $v.as_str() - .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) - .chars() - .next() - .unwrap_or_else(|| panic!("Expected char")) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_str { - ($v:expr) => {{ - $v.as_str() - .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_char { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c(yaml_char!($v)) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_str { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c(yaml_str!($v)) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_bool { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v - .as_bool() - .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_usize { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v - .as_i64() - .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) - as usize) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_setting { - ($a:ident, $v:ident, $c:ident, $s:ident, $t:literal, $n:expr) => {{ - if let Some(v) = $v.as_vec() { - for ys in v { - if let Some(s) = ys.as_str() { - $a = $a.$c(s.parse::<$s>().unwrap_or_else(|_| { - panic!("Unknown {} '{}' found in YAML file for {}", $t, s, $n) - })); - } else { - panic!( - "Failed to convert YAML {:?} value to an array of strings", - $v - ); - } - } - } else if let Some(v) = $v.as_str() { - $a = $a.$c(v - .parse::<$s>() - .unwrap_or_else(|_| panic!("Unknown {} '{}' found in YAML file for {}", $t, v, $n))) - } else { - panic!("Failed to convert YAML {:?} value to a string", $v); - } - $a - }}; -} diff --git a/vendor/clap/src/builder/mod.rs b/vendor/clap/src/builder/mod.rs deleted file mode 100644 index 4f24c74d3..000000000 --- a/vendor/clap/src/builder/mod.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Define [`Command`] line [arguments][`Arg`] - -#[macro_use] -mod macros; - -mod action; -mod app_settings; -mod arg; -mod arg_group; -mod arg_predicate; -mod arg_settings; -mod command; -mod possible_value; -mod usage_parser; -mod value_hint; -mod value_parser; - -#[cfg(feature = "regex")] -mod regex; - -#[cfg(debug_assertions)] -mod debug_asserts; - -#[cfg(test)] -mod tests; - -pub use action::ArgAction; -pub use app_settings::{AppFlags, AppSettings}; -pub use arg::Arg; -pub use arg_group::ArgGroup; -pub use arg_settings::{ArgFlags, ArgSettings}; -pub use command::Command; -pub use possible_value::PossibleValue; -pub use value_hint::ValueHint; -pub use value_parser::PossibleValuesParser; -pub use value_parser::RangedI64ValueParser; -pub use value_parser::RangedU64ValueParser; -pub use value_parser::StringValueParser; -pub use value_parser::TypedValueParser; -pub use value_parser::ValueParser; -pub use value_parser::ValueParserFactory; -pub use value_parser::_AnonymousValueParser; -pub use value_parser::_AutoValueParser; -pub use value_parser::via_prelude; -pub use value_parser::BoolValueParser; -pub use value_parser::BoolishValueParser; -pub use value_parser::EnumValueParser; -pub use value_parser::FalseyValueParser; -pub use value_parser::NonEmptyStringValueParser; -pub use value_parser::OsStringValueParser; -pub use value_parser::PathBufValueParser; - -#[allow(deprecated)] -pub use command::App; - -#[cfg(feature = "regex")] -pub use self::regex::RegexRef; - -pub(crate) use action::CountType; -pub(crate) use arg::display_arg_val; -pub(crate) use arg_predicate::ArgPredicate; diff --git a/vendor/clap/src/builder/possible_value.rs b/vendor/clap/src/builder/possible_value.rs deleted file mode 100644 index 1c14217a6..000000000 --- a/vendor/clap/src/builder/possible_value.rs +++ /dev/null @@ -1,259 +0,0 @@ -use std::{borrow::Cow, iter}; - -use crate::util::eq_ignore_case; - -/// A possible value of an argument. -/// -/// This is used for specifying [possible values] of [Args]. -/// -/// **NOTE:** This struct is likely not needed for most usecases as it is only required to -/// [hide] single values from help messages and shell completions or to attach [help] to possible values. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Arg, PossibleValue}; -/// let cfg = Arg::new("config") -/// .takes_value(true) -/// .value_name("FILE") -/// .value_parser([ -/// PossibleValue::new("fast"), -/// PossibleValue::new("slow").help("slower than fast"), -/// PossibleValue::new("secret speed").hide(true) -/// ]); -/// ``` -/// [Args]: crate::Arg -/// [possible values]: crate::builder::ValueParser::possible_values -/// [hide]: PossibleValue::hide() -/// [help]: PossibleValue::help() -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct PossibleValue<'help> { - name: &'help str, - help: Option<&'help str>, - aliases: Vec<&'help str>, // (name, visible) - hide: bool, -} - -impl<'help> PossibleValue<'help> { - /// Create a [`PossibleValue`] with its name. - /// - /// The name will be used to decide whether this value was provided by the user to an argument. - /// - /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments - /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// PossibleValue::new("fast") - /// # ; - /// ``` - /// [hidden]: PossibleValue::hide - /// [possible value]: crate::Arg::possible_values - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - pub fn new(name: &'help str) -> Self { - PossibleValue { - name, - ..Default::default() - } - } - - /// Sets the help description of the value. - /// - /// This is typically displayed in completions (where supported) and should be a short, one-line - /// description. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// PossibleValue::new("slow") - /// .help("not fast") - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn help(mut self, help: &'help str) -> Self { - self.help = Some(help); - self - } - - /// Hides this value from help and shell completions. - /// - /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only - /// want to hide some values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// PossibleValue::new("secret") - /// .hide(true) - /// # ; - /// ``` - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - #[inline] - #[must_use] - pub fn hide(mut self, yes: bool) -> Self { - self.hide = yes; - self - } - - /// Sets a *hidden* alias for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// PossibleValue::new("slow") - /// .alias("not-fast") - /// # ; - /// ``` - #[must_use] - pub fn alias(mut self, name: &'help str) -> Self { - self.aliases.push(name); - self - } - - /// Sets multiple *hidden* aliases for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// PossibleValue::new("slow") - /// .aliases(["not-fast", "snake-like"]) - /// # ; - /// ``` - #[must_use] - pub fn aliases(mut self, names: I) -> Self - where - I: IntoIterator, - { - self.aliases.extend(names.into_iter()); - self - } -} - -/// Reflection -impl<'help> PossibleValue<'help> { - /// Get the name of the argument value - #[inline] - pub fn get_name(&self) -> &'help str { - self.name - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&'help str> { - self.help - } - - /// Get the help specified for this argument, if any and the argument - /// value is not hidden - #[inline] - #[cfg(feature = "unstable-v4")] - pub(crate) fn get_visible_help(&self) -> Option<&'help str> { - if !self.hide { - self.help - } else { - None - } - } - - /// Deprecated, replaced with [`PossibleValue::is_hide_set`] - #[inline] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `PossibleValue::is_hide_set`") - )] - pub fn is_hidden(&self) -> bool { - self.is_hide_set() - } - - /// Report if [`PossibleValue::hide`] is set - #[inline] - pub fn is_hide_set(&self) -> bool { - self.hide - } - - /// Report if PossibleValue is not hidden and has a help message - pub(crate) fn should_show_help(&self) -> bool { - !self.hide && self.help.is_some() - } - - /// Get the name if argument value is not hidden, `None` otherwise - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.4", - note = "Use `PossibleValue::is_hide_set` and `PossibleValue::get_name`" - ) - )] - pub fn get_visible_name(&self) -> Option<&'help str> { - if self.hide { - None - } else { - Some(self.name) - } - } - - /// Get the name if argument value is not hidden, `None` otherwise, - /// but wrapped in quotes if it contains whitespace - pub(crate) fn get_visible_quoted_name(&self) -> Option> { - if !self.hide { - Some(if self.name.contains(char::is_whitespace) { - format!("{:?}", self.name).into() - } else { - self.name.into() - }) - } else { - None - } - } - - /// Returns all valid values of the argument value. - /// - /// Namely the name and all aliases. - pub fn get_name_and_aliases(&self) -> impl Iterator + '_ { - iter::once(&self.name).chain(&self.aliases).copied() - } - - /// Tests if the value is valid for this argument value - /// - /// The value is valid if it is either the name or one of the aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::PossibleValue; - /// let arg_value = PossibleValue::new("fast").alias("not-slow"); - /// - /// assert!(arg_value.matches("fast", false)); - /// assert!(arg_value.matches("not-slow", false)); - /// - /// assert!(arg_value.matches("FAST", true)); - /// assert!(!arg_value.matches("FAST", false)); - /// ``` - pub fn matches(&self, value: &str, ignore_case: bool) -> bool { - if ignore_case { - self.get_name_and_aliases() - .any(|name| eq_ignore_case(name, value)) - } else { - self.get_name_and_aliases().any(|name| name == value) - } - } -} - -impl<'help> From<&'help str> for PossibleValue<'help> { - fn from(s: &'help str) -> Self { - Self::new(s) - } -} - -impl<'help> From<&'help &'help str> for PossibleValue<'help> { - fn from(s: &'help &'help str) -> Self { - Self::new(s) - } -} diff --git a/vendor/clap/src/builder/regex.rs b/vendor/clap/src/builder/regex.rs deleted file mode 100644 index bf3a78e0c..000000000 --- a/vendor/clap/src/builder/regex.rs +++ /dev/null @@ -1,88 +0,0 @@ -use ::regex::{Error, Regex, RegexSet}; - -use core::{convert::TryFrom, ops::Deref, str::FromStr}; -use std::borrow::Cow; - -/// Contains either a regular expression or a set of them or a reference to one. -/// -/// See [Arg::validator_regex(][crate::Arg::validator_regex] to set this on an argument. -#[derive(Debug, Clone)] -pub enum RegexRef<'a> { - /// Used if the underlying is a regex set - RegexSet(Cow<'a, RegexSet>), - /// Used if the underlying is a regex - Regex(Cow<'a, Regex>), -} - -impl<'a> RegexRef<'a> { - pub(crate) fn is_match(&self, text: &str) -> bool { - match self { - Self::Regex(r) => r.deref().is_match(text), - Self::RegexSet(r) => r.deref().is_match(text), - } - } -} - -impl<'a> From<&'a Regex> for RegexRef<'a> { - fn from(r: &'a Regex) -> Self { - Self::Regex(Cow::Borrowed(r)) - } -} - -impl<'a> From for RegexRef<'a> { - fn from(r: Regex) -> Self { - Self::Regex(Cow::Owned(r)) - } -} - -impl<'a> From<&'a RegexSet> for RegexRef<'a> { - fn from(r: &'a RegexSet) -> Self { - Self::RegexSet(Cow::Borrowed(r)) - } -} - -impl<'a> From for RegexRef<'a> { - fn from(r: RegexSet) -> Self { - Self::RegexSet(Cow::Owned(r)) - } -} - -impl<'a> TryFrom<&'a str> for RegexRef<'a> { - type Error = ::Err; - - fn try_from(r: &'a str) -> Result { - Self::from_str(r) - } -} - -impl<'a> FromStr for RegexRef<'a> { - type Err = Error; - - fn from_str(s: &str) -> Result { - Regex::from_str(s).map(|v| Self::Regex(Cow::Owned(v))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use core::convert::TryInto; - - #[test] - fn test_try_from_with_valid_string() { - let t: Result = "^Hello, World$".try_into(); - assert!(t.is_ok()) - } - - #[test] - fn test_try_from_with_invalid_string() { - let t: Result = "^Hello, World)$".try_into(); - assert!(t.is_err()); - } - - #[test] - fn from_str() { - let t: Result = RegexRef::from_str("^Hello, World"); - assert!(t.is_ok()); - } -} diff --git a/vendor/clap/src/builder/tests.rs b/vendor/clap/src/builder/tests.rs deleted file mode 100644 index 76c8b8785..000000000 --- a/vendor/clap/src/builder/tests.rs +++ /dev/null @@ -1,56 +0,0 @@ -use crate::Arg; -use crate::Command; - -#[test] -fn propagate_version() { - let mut cmd = Command::new("test") - .propagate_version(true) - .version("1.1") - .subcommand(Command::new("sub1")); - cmd._propagate(); - assert_eq!( - cmd.get_subcommands().next().unwrap().get_version(), - Some("1.1") - ); -} - -#[test] -fn global_setting() { - let mut cmd = Command::new("test") - .disable_version_flag(true) - .subcommand(Command::new("subcmd")); - cmd._propagate(); - assert!(cmd - .get_subcommands() - .find(|s| s.get_name() == "subcmd") - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Command is not Send + Sync -#[test] -fn app_send_sync() { - fn foo(_: T) {} - foo(Command::new("test")) -} - -#[test] -fn issue_2090() { - let mut cmd = Command::new("cmd") - .disable_version_flag(true) - .subcommand(Command::new("sub")); - cmd._build_self(); - - assert!(cmd - .get_subcommands() - .next() - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Arg is not Send + Sync -#[test] -fn arg_send_sync() { - fn foo(_: T) {} - foo(Arg::new("test")) -} diff --git a/vendor/clap/src/builder/usage_parser.rs b/vendor/clap/src/builder/usage_parser.rs deleted file mode 100644 index 85d0d304e..000000000 --- a/vendor/clap/src/builder/usage_parser.rs +++ /dev/null @@ -1,1277 +0,0 @@ -#![allow(deprecated)] - -// Internal -use crate::builder::Arg; -use crate::builder::ArgSettings; -use crate::INTERNAL_ERROR_MSG; - -#[derive(PartialEq, Debug)] -enum UsageToken { - Name, - ValName, - Short, - Long, - Help, - Multiple, - Unknown, - Default, -} - -#[derive(Debug)] -pub(crate) struct UsageParser<'help> { - usage: &'help str, - pos: usize, - start: usize, - prev: UsageToken, - explicit_name_set: bool, -} - -impl<'help> UsageParser<'help> { - fn new(usage: &'help str) -> Self { - debug!("new: usage={:?}", usage); - UsageParser { - usage, - pos: 0, - start: 0, - prev: UsageToken::Unknown, - explicit_name_set: false, - } - } - - pub(crate) fn from_usage(usage: &'help str) -> Self { - debug!("UsageParser::from_usage"); - UsageParser::new(usage) - } - - pub(crate) fn parse(mut self) -> Arg<'help> { - debug!("UsageParser::parse"); - let mut arg = Arg::default(); - loop { - debug!("UsageParser::parse:iter: pos={}", self.pos); - self.stop_at(token); - if let Some(&c) = self.usage.as_bytes().get(self.pos) { - match c { - b'-' => self.short_or_long(&mut arg), - b'.' => self.multiple(&mut arg), - b'@' => self.default(&mut arg), - b'\'' => self.help(&mut arg), - _ => self.name(&mut arg), - } - } else { - break; - } - } - - debug!("UsageParser::parse: vals...{:?}", arg.val_names); - arg - } - - fn name(&mut self, arg: &mut Arg<'help>) { - debug!("UsageParser::name"); - if *self - .usage - .as_bytes() - .get(self.pos) - .expect(INTERNAL_ERROR_MSG) - == b'<' - && !self.explicit_name_set - { - arg.settings.set(ArgSettings::Required); - } - self.pos += 1; - self.stop_at(name_end); - let name = &self.usage[self.start..self.pos]; - if self.prev == UsageToken::Unknown { - debug!("UsageParser::name: setting name...{}", name); - arg.id = name.into(); - arg.name = name; - if arg.long.is_none() && arg.short.is_none() { - debug!("name: explicit name set..."); - self.explicit_name_set = true; - self.prev = UsageToken::Name; - } - } else { - debug!("UsageParser::name: setting val name...{}", name); - if arg.val_names.is_empty() { - arg.settings.set(ArgSettings::TakesValue); - } - let len = arg.val_names.len(); - arg.val_names.insert(len, name); - self.prev = UsageToken::ValName; - } - } - - fn stop_at(&mut self, f: F) - where - F: Fn(u8) -> bool, - { - debug!("UsageParser::stop_at"); - self.start = self.pos; - self.pos += self.usage[self.start..] - .bytes() - .take_while(|&b| f(b)) - .count(); - } - - fn short_or_long(&mut self, arg: &mut Arg<'help>) { - debug!("UsageParser::short_or_long"); - self.pos += 1; - if *self - .usage - .as_bytes() - .get(self.pos) - .expect(INTERNAL_ERROR_MSG) - == b'-' - { - self.pos += 1; - self.long(arg); - return; - } - self.short(arg) - } - - fn long(&mut self, arg: &mut Arg<'help>) { - debug!("UsageParser::long"); - self.stop_at(long_end); - let name = &self.usage[self.start..self.pos]; - if !self.explicit_name_set { - debug!("UsageParser::long: setting name...{}", name); - arg.id = name.into(); - arg.name = name; - } - debug!("UsageParser::long: setting long...{}", name); - arg.long = Some(name); - self.prev = UsageToken::Long; - } - - fn short(&mut self, arg: &mut Arg<'help>) { - debug!("UsageParser::short"); - let start = &self.usage[self.pos..]; - let short = start.chars().next().expect(INTERNAL_ERROR_MSG); - debug!("UsageParser::short: setting short...{}", short); - arg.short = Some(short); - if arg.name.is_empty() { - // --long takes precedence but doesn't set self.explicit_name_set - let name = &start[..short.len_utf8()]; - debug!("UsageParser::short: setting name...{}", name); - arg.id = name.into(); - arg.name = name; - } - self.prev = UsageToken::Short; - } - - // "something..." - fn multiple(&mut self, arg: &mut Arg) { - debug!("UsageParser::multiple"); - let mut dot_counter = 1; - let start = self.pos; - let mut bytes = self.usage[start..].bytes(); - while bytes.next() == Some(b'.') { - dot_counter += 1; - self.pos += 1; - if dot_counter == 3 { - debug!("UsageParser::multiple: setting multiple"); - arg.settings.set(ArgSettings::MultipleOccurrences); - if arg.is_takes_value_set() { - arg.settings.set(ArgSettings::MultipleValues); - arg.settings.set(ArgSettings::UseValueDelimiter); - arg.val_delim.get_or_insert(','); - } - self.prev = UsageToken::Multiple; - self.pos += 1; - break; - } - } - } - - fn help(&mut self, arg: &mut Arg<'help>) { - debug!("UsageParser::help"); - self.stop_at(help_start); - self.start = self.pos + 1; - self.pos = self.usage.len() - 1; - debug!( - "UsageParser::help: setting help...{}", - &self.usage[self.start..self.pos] - ); - arg.help = Some(&self.usage[self.start..self.pos]); - self.pos += 1; // Move to next byte to keep from thinking ending ' is a start - self.prev = UsageToken::Help; - } - - fn default(&mut self, arg: &mut Arg<'help>) { - debug!( - "UsageParser::default: from=\"{}\"", - &self.usage[self.pos..self.usage.len()] - ); - self.pos += 1; // Skip @ - self.stop_at(default_value_end); // Find first space after value - debug!( - "UsageParser::default: setting default...\"{}\"", - &self.usage[self.start..self.pos] - ); - arg.settings.set(ArgSettings::TakesValue); - arg.default_vals = vec![std::ffi::OsStr::new(&self.usage[self.start..self.pos])]; - self.prev = UsageToken::Default; - } -} - -#[inline] -fn name_end(b: u8) -> bool { - b != b']' && b != b'>' -} - -#[inline] -fn token(b: u8) -> bool { - b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' && b != b'@' -} - -#[inline] -fn long_end(b: u8) -> bool { - b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' ' -} - -#[inline] -fn help_start(b: u8) -> bool { - b != b'\'' -} - -#[inline] -fn default_value_end(b: u8) -> bool { - b != b' ' -} - -#[cfg(test)] -mod test { - #![allow(deprecated)] - - use crate::builder::{Arg, ArgSettings}; - - #[allow(clippy::cognitive_complexity)] - #[test] - fn create_flag_usage() { - let a = Arg::from_usage("[flag] -f 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.long.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flag] --flag 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.long.unwrap(), "flag"); - assert!(a.short.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("--flag 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.long.unwrap(), "flag"); - assert!(a.short.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flag] -f --flag 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.short.unwrap(), 'f'); - assert_eq!(a.long.unwrap(), "flag"); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flag] -f... 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.long.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flag] -f --flag... 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.long.unwrap(), "flag"); - assert_eq!(a.short.unwrap(), 'f'); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("-f --flag... 'some help info'"); - assert_eq!(a.name, "flag"); - assert_eq!(a.long.unwrap(), "flag"); - assert_eq!(a.short.unwrap(), 'f'); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("--flags"); - assert_eq!(a.name, "flags"); - assert_eq!(a.long.unwrap(), "flags"); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("--flags..."); - assert_eq!(a.name, "flags"); - assert_eq!(a.long.unwrap(), "flags"); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flags] -f"); - assert_eq!(a.name, "flags"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("[flags] -f..."); - assert_eq!(a.name, "flags"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("-f 'some help info'"); - assert_eq!(a.name, "f"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.long.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("-f"); - assert_eq!(a.name, "f"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.val_names.is_empty()); - - let a = Arg::from_usage("-f..."); - assert_eq!(a.name, "f"); - assert_eq!(a.short.unwrap(), 'f'); - assert!(a.is_multiple_occurrences_set()); - assert!(a.val_names.is_empty()); - } - - #[test] - fn create_option_usage0() { - // Short only - let a = Arg::from_usage("[option] -o [opt] 'some help info'"); - assert_eq!(a.name, "option"); - assert_eq!(a.short.unwrap(), 'o'); - assert!(a.long.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(!a.is_multiple_values_set()); - assert!(a.is_takes_value_set()); - assert!(!a.is_required_set()); - assert_eq!(a.val_names.iter().collect::>(), [&"opt"]); - } - - #[test] - fn create_option_usage1() { - let a = Arg::from_usage("-o [opt] 'some help info'"); - assert_eq!(a.name, "o"); - assert_eq!(a.short.unwrap(), 'o'); - assert!(a.long.is_none()); - assert_eq!(a.help.unwrap(), "some help info"); - assert!(!a.is_multiple_occurrences_set()); - assert!(!a.is_multiple_values_set()); - assert!(a.is_takes_value_set()); - assert!(!a.is_required_set()); - assert_eq!(a.val_names.iter().collect::>(), [&"opt"]); - } - - #[test] - fn create_option_usage2() { - let a = Arg::from_usage("

(file: fs::File, path: P) -> Self where @@ -125,13 +131,12 @@ impl File { path: path.into(), } } -} -/// Methods added by fs-err that are not available on -/// [`std::fs::File`][std::fs::File]. -/// -/// [std::fs::File]: https://doc.rust-lang.org/stable/std/fs/struct.File.html -impl File { + /// Extract the raw file and its path from this [`File`](struct.File.html) + pub fn into_parts(self) -> (fs::File, PathBuf) { + (self.file, self.path) + } + /// Returns a reference to the underlying [`std::fs::File`][std::fs::File]. /// /// [std::fs::File]: https://doc.rust-lang.org/stable/std/fs/struct.File.html @@ -139,6 +144,13 @@ impl File { &self.file } + /// Returns a mutable reference to the underlying [`std::fs::File`][std::fs::File]. + /// + /// [std::fs::File]: https://doc.rust-lang.org/stable/std/fs/struct.File.html + pub fn file_mut(&mut self) -> &mut fs::File { + &mut self.file + } + /// Returns a reference to the path that this file was created with. pub fn path(&self) -> &Path { &self.path @@ -146,7 +158,7 @@ impl File { /// Wrap the error in information specific to this `File` object. fn error(&self, source: io::Error, kind: ErrorKind) -> io::Error { - Error::new(source, kind, &self.path) + Error::build(source, kind, &self.path) } } @@ -178,6 +190,12 @@ impl<'a> Read for &'a File { } } +impl From for fs::File { + fn from(file: File) -> Self { + file.into_parts().0 + } +} + impl Seek for File { fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { self.file @@ -266,6 +284,25 @@ mod unix { .map_err(|err| self.error(err, ErrorKind::WriteAt)) } } + + #[cfg(feature = "io_safety")] + mod io_safety { + use std::os::unix::io::{AsFd, BorrowedFd, OwnedFd}; + + #[cfg_attr(docsrs, doc(cfg(feature = "io_safety")))] + impl AsFd for crate::File { + fn as_fd(&self) -> BorrowedFd<'_> { + self.file().as_fd() + } + } + + #[cfg_attr(docsrs, doc(cfg(feature = "io_safety")))] + impl From for OwnedFd { + fn from(file: crate::File) -> Self { + file.into_parts().0.into() + } + } + } } #[cfg(windows)] @@ -307,4 +344,23 @@ mod windows { self.file.into_raw_handle() } } + + #[cfg(feature = "io_safety")] + mod io_safety { + use std::os::windows::io::{AsHandle, BorrowedHandle, OwnedHandle}; + + #[cfg_attr(docsrs, doc(cfg(feature = "io_safety")))] + impl AsHandle for crate::File { + fn as_handle(&self) -> BorrowedHandle<'_> { + self.file().as_handle() + } + } + + #[cfg_attr(docsrs, doc(cfg(feature = "io_safety")))] + impl From for OwnedHandle { + fn from(file: crate::File) -> Self { + file.into_parts().0.into() + } + } + } } diff --git a/vendor/fs-err/src/lib.rs b/vendor/fs-err/src/lib.rs index 3cc8a3b4d..777db9535 100644 --- a/vendor/fs-err/src/lib.rs +++ b/vendor/fs-err/src/lib.rs @@ -1,7 +1,7 @@ /*! fs-err is a drop-in replacement for [`std::fs`][std::fs] that provides more helpful messages on errors. Extra information includes which operations was -attmpted and any involved paths. +attempted and any involved paths. # Error Messages @@ -66,8 +66,9 @@ println!("Program config: {:?}", decoded); [serde_json]: https://crates.io/crates/serde_json */ -#![doc(html_root_url = "https://docs.rs/fs-err/2.5.0")] +#![doc(html_root_url = "https://docs.rs/fs-err/2.8.1")] #![deny(missing_debug_implementations, missing_docs)] +#![cfg_attr(docsrs, feature(doc_cfg))] mod dir; mod errors; @@ -90,20 +91,20 @@ pub use path::PathExt; /// Wrapper for [`fs::read`](https://doc.rust-lang.org/stable/std/fs/fn.read.html). pub fn read>(path: P) -> io::Result> { let path = path.as_ref(); - let mut file = file::open(path.as_ref()).map_err(|err_gen| err_gen(path.to_path_buf()))?; + let mut file = file::open(path).map_err(|err_gen| err_gen(path.to_path_buf()))?; let mut bytes = Vec::with_capacity(initial_buffer_size(&file)); file.read_to_end(&mut bytes) - .map_err(|err| Error::new(err, ErrorKind::Read, path))?; + .map_err(|err| Error::build(err, ErrorKind::Read, path))?; Ok(bytes) } /// Wrapper for [`fs::read_to_string`](https://doc.rust-lang.org/stable/std/fs/fn.read_to_string.html). pub fn read_to_string>(path: P) -> io::Result { let path = path.as_ref(); - let mut file = file::open(path.as_ref()).map_err(|err_gen| err_gen(path.to_path_buf()))?; + let mut file = file::open(path).map_err(|err_gen| err_gen(path.to_path_buf()))?; let mut string = String::with_capacity(initial_buffer_size(&file)); file.read_to_string(&mut string) - .map_err(|err| Error::new(err, ErrorKind::Read, path))?; + .map_err(|err| Error::build(err, ErrorKind::Read, path))?; Ok(string) } @@ -113,7 +114,7 @@ pub fn write, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result file::create(path) .map_err(|err_gen| err_gen(path.to_path_buf()))? .write_all(contents.as_ref()) - .map_err(|err| Error::new(err, ErrorKind::Write, path)) + .map_err(|err| Error::build(err, ErrorKind::Write, path)) } /// Wrapper for [`fs::copy`](https://doc.rust-lang.org/stable/std/fs/fn.copy.html). @@ -125,7 +126,7 @@ where let from = from.as_ref(); let to = to.as_ref(); fs::copy(from, to) - .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::Copy, from, to)) + .map_err(|source| SourceDestError::build(source, SourceDestErrorKind::Copy, from, to)) } /// Wrapper for [`fs::create_dir`](https://doc.rust-lang.org/stable/std/fs/fn.create_dir.html). @@ -134,7 +135,7 @@ where P: AsRef, { let path = path.as_ref(); - fs::create_dir(path).map_err(|source| Error::new(source, ErrorKind::CreateDir, path)) + fs::create_dir(path).map_err(|source| Error::build(source, ErrorKind::CreateDir, path)) } /// Wrapper for [`fs::create_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.create_dir_all.html). @@ -143,7 +144,7 @@ where P: AsRef, { let path = path.as_ref(); - fs::create_dir_all(path).map_err(|source| Error::new(source, ErrorKind::CreateDir, path)) + fs::create_dir_all(path).map_err(|source| Error::build(source, ErrorKind::CreateDir, path)) } /// Wrapper for [`fs::remove_dir`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir.html). @@ -152,7 +153,7 @@ where P: AsRef, { let path = path.as_ref(); - fs::remove_dir(path).map_err(|source| Error::new(source, ErrorKind::RemoveDir, path)) + fs::remove_dir(path).map_err(|source| Error::build(source, ErrorKind::RemoveDir, path)) } /// Wrapper for [`fs::remove_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir_all.html). @@ -161,7 +162,7 @@ where P: AsRef, { let path = path.as_ref(); - fs::remove_dir_all(path).map_err(|source| Error::new(source, ErrorKind::RemoveDir, path)) + fs::remove_dir_all(path).map_err(|source| Error::build(source, ErrorKind::RemoveDir, path)) } /// Wrapper for [`fs::remove_file`](https://doc.rust-lang.org/stable/std/fs/fn.remove_file.html). @@ -170,19 +171,19 @@ where P: AsRef, { let path = path.as_ref(); - fs::remove_file(path).map_err(|source| Error::new(source, ErrorKind::RemoveFile, path)) + fs::remove_file(path).map_err(|source| Error::build(source, ErrorKind::RemoveFile, path)) } /// Wrapper for [`fs::metadata`](https://doc.rust-lang.org/stable/std/fs/fn.metadata.html). pub fn metadata>(path: P) -> io::Result { let path = path.as_ref(); - fs::metadata(path).map_err(|source| Error::new(source, ErrorKind::Metadata, path)) + fs::metadata(path).map_err(|source| Error::build(source, ErrorKind::Metadata, path)) } /// Wrapper for [`fs::canonicalize`](https://doc.rust-lang.org/stable/std/fs/fn.canonicalize.html). pub fn canonicalize>(path: P) -> io::Result { let path = path.as_ref(); - fs::canonicalize(path).map_err(|source| Error::new(source, ErrorKind::Canonicalize, path)) + fs::canonicalize(path).map_err(|source| Error::build(source, ErrorKind::Canonicalize, path)) } /// Wrapper for [`fs::hard_link`](https://doc.rust-lang.org/stable/std/fs/fn.hard_link.html). @@ -190,13 +191,13 @@ pub fn hard_link, Q: AsRef>(src: P, dst: Q) -> io::Result<( let src = src.as_ref(); let dst = dst.as_ref(); fs::hard_link(src, dst) - .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::HardLink, src, dst)) + .map_err(|source| SourceDestError::build(source, SourceDestErrorKind::HardLink, src, dst)) } /// Wrapper for [`fs::read_link`](https://doc.rust-lang.org/stable/std/fs/fn.read_link.html). pub fn read_link>(path: P) -> io::Result { let path = path.as_ref(); - fs::read_link(path).map_err(|source| Error::new(source, ErrorKind::ReadLink, path)) + fs::read_link(path).map_err(|source| Error::build(source, ErrorKind::ReadLink, path)) } /// Wrapper for [`fs::rename`](https://doc.rust-lang.org/stable/std/fs/fn.rename.html). @@ -204,7 +205,7 @@ pub fn rename, Q: AsRef>(from: P, to: Q) -> io::Result<()> let from = from.as_ref(); let to = to.as_ref(); fs::rename(from, to) - .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::Rename, from, to)) + .map_err(|source| SourceDestError::build(source, SourceDestErrorKind::Rename, from, to)) } /// Wrapper for [`fs::soft_link`](https://doc.rust-lang.org/stable/std/fs/fn.soft_link.html). @@ -215,21 +216,21 @@ pub fn soft_link, Q: AsRef>(src: P, dst: Q) -> io::Result<( let dst = dst.as_ref(); #[allow(deprecated)] fs::soft_link(src, dst) - .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::SoftLink, src, dst)) + .map_err(|source| SourceDestError::build(source, SourceDestErrorKind::SoftLink, src, dst)) } /// Wrapper for [`fs::symlink_metadata`](https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html). pub fn symlink_metadata>(path: P) -> io::Result { let path = path.as_ref(); fs::symlink_metadata(path) - .map_err(|source| Error::new(source, ErrorKind::SymlinkMetadata, path)) + .map_err(|source| Error::build(source, ErrorKind::SymlinkMetadata, path)) } /// Wrapper for [`fs::set_permissions`](https://doc.rust-lang.org/stable/std/fs/fn.set_permissions.html). pub fn set_permissions>(path: P, perm: fs::Permissions) -> io::Result<()> { let path = path.as_ref(); fs::set_permissions(path, perm) - .map_err(|source| Error::new(source, ErrorKind::SetPermissions, path)) + .map_err(|source| Error::build(source, ErrorKind::SetPermissions, path)) } fn initial_buffer_size(file: &std::fs::File) -> usize { diff --git a/vendor/fs-err/src/open_options.rs b/vendor/fs-err/src/open_options.rs index 2a11a3974..557fa7abe 100644 --- a/vendor/fs-err/src/open_options.rs +++ b/vendor/fs-err/src/open_options.rs @@ -5,6 +5,7 @@ pub struct OpenOptions(fs::OpenOptions); impl OpenOptions { /// Wrapper for [`std::fs::OpenOptions::new`](https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.new) + #[allow(clippy::new_without_default)] pub fn new() -> Self { OpenOptions(fs::OpenOptions::new()) } diff --git a/vendor/fs-err/src/os/unix.rs b/vendor/fs-err/src/os/unix.rs index 1c0bbc24d..ad7c488c4 100644 --- a/vendor/fs-err/src/os/unix.rs +++ b/vendor/fs-err/src/os/unix.rs @@ -11,7 +11,7 @@ pub mod fs { let src = src.as_ref(); let dst = dst.as_ref(); std::os::unix::fs::symlink(src, dst) - .map_err(|err| SourceDestError::new(err, SourceDestErrorKind::Symlink, src, dst)) + .map_err(|err| SourceDestError::build(err, SourceDestErrorKind::Symlink, src, dst)) } /// Wrapper for [`std::os::unix::fs::FileExt`](https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html). @@ -30,9 +30,9 @@ pub mod fs { /// The std traits might be extended in the future (See issue [#49961](https://github.com/rust-lang/rust/issues/49961#issuecomment-382751777)). /// This trait is sealed and can not be implemented by other crates. pub trait OpenOptionsExt: crate::Sealed { - /// Wapper for [`OpenOptionsExt::mode`](https://doc.rust-lang.org/std/os/unix/fs/trait.OpenOptionsExt.html#tymethod.mode) + /// Wrapper for [`OpenOptionsExt::mode`](https://doc.rust-lang.org/std/os/unix/fs/trait.OpenOptionsExt.html#tymethod.mode) fn mode(&mut self, mode: u32) -> &mut Self; - /// Wapper for [`OpenOptionsExt::custom_flags`](https://doc.rust-lang.org/std/os/unix/fs/trait.OpenOptionsExt.html#tymethod.custom_flags) + /// Wrapper for [`OpenOptionsExt::custom_flags`](https://doc.rust-lang.org/std/os/unix/fs/trait.OpenOptionsExt.html#tymethod.custom_flags) fn custom_flags(&mut self, flags: i32) -> &mut Self; } } diff --git a/vendor/fs-err/src/os/windows.rs b/vendor/fs-err/src/os/windows.rs index 3aaa4a2b8..f55985623 100644 --- a/vendor/fs-err/src/os/windows.rs +++ b/vendor/fs-err/src/os/windows.rs @@ -8,7 +8,7 @@ pub mod fs { let src = src.as_ref(); let dst = dst.as_ref(); std::os::windows::fs::symlink_dir(src, dst) - .map_err(|err| SourceDestError::new(err, SourceDestErrorKind::SymlinkDir, src, dst)) + .map_err(|err| SourceDestError::build(err, SourceDestErrorKind::SymlinkDir, src, dst)) } /// Wrapper for [std::os::windows::fs::symlink_file](https://doc.rust-lang.org/std/os/windows/fs/fn.symlink_file.html) @@ -16,7 +16,7 @@ pub mod fs { let src = src.as_ref(); let dst = dst.as_ref(); std::os::windows::fs::symlink_file(src, dst) - .map_err(|err| SourceDestError::new(err, SourceDestErrorKind::SymlinkFile, src, dst)) + .map_err(|err| SourceDestError::build(err, SourceDestErrorKind::SymlinkFile, src, dst)) } /// Wrapper for [`std::os::windows::fs::FileExt`](https://doc.rust-lang.org/std/os/windows/fs/trait.FileExt.html). diff --git a/vendor/fs-err/src/path.rs b/vendor/fs-err/src/path.rs index ed6b9eaf1..28549a31c 100644 --- a/vendor/fs-err/src/path.rs +++ b/vendor/fs-err/src/path.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; /// /// This trait is sealed and can not be implemented by other crates. // -// Because noone else can implement it, we can add methods backwards-compatibly. +// Because no one else can implement it, we can add methods backwards-compatibly. pub trait PathExt: crate::Sealed { /// Wrapper for [`crate::metadata`]. fn fs_err_metadata(&self) -> io::Result; diff --git a/vendor/fs-err/tests/version-numbers.rs b/vendor/fs-err/tests/version-numbers.rs deleted file mode 100644 index 41a5ea480..000000000 --- a/vendor/fs-err/tests/version-numbers.rs +++ /dev/null @@ -1,9 +0,0 @@ -#[test] -fn test_readme_deps() { - version_sync::assert_markdown_deps_updated!("README.md"); -} - -#[test] -fn test_html_root_url() { - version_sync::assert_html_root_url_updated!("src/lib.rs"); -} diff --git a/vendor/generic-array-0.12.4/.cargo-checksum.json b/vendor/generic-array-0.12.4/.cargo-checksum.json deleted file mode 100644 index cfe4f79f6..000000000 --- a/vendor/generic-array-0.12.4/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"ae7c1d7fcd6dceb6472568994016862441606c444d0670d4e9dffab20c5eeea3","Cargo.toml":"122428b66e56c3287df569deba1e7de4b7c316cee39e1f9e1c3e7d80c793e427","LICENSE":"ad4fcfaf8d5b12b97409c137a03d4a4e4b21024c65c54f976cc3b609c1bd5b0f","README.md":"9a1a45416eac57050036b13df6ec84d21d555e820726af3c782896bd9d37d94b","rustfmt.toml":"2a298b4ce1fe6e16b8f281a0035567b8eb15042ed3062729fd28224f29c2f75a","src/arr.rs":"d866a89232279e5602cfe80b7f4e0db2b8b1153532ca72f61d65ba4d792fa603","src/functional.rs":"a0b12be07c1cc85549a80ddf1cfa1c7d5cbc09c3710bb635a5f95c35537005dc","src/hex.rs":"45e780bf385f99eec5058cfae87f97042679b1e8cbc130c009d4c074052016aa","src/impl_serde.rs":"5556e952fd351ab0af27bb562b1b6382e96a20afe51a04300264842e1fb33747","src/impls.rs":"d3046213d058b43b7b7360a2fa9ab6794e44970f1bc1847649c42c8f1c4f2d75","src/iter.rs":"b8b130ddd52461c435b873b9435f771d6535ae835055a73d79c0f3105f6b367e","src/lib.rs":"99a3fe3bc49cbfb9f00554d4860b24abe02e8075404fdb88343f2ee389f09110","src/sequence.rs":"bdf4d8920205bb85dee95897940373991b232e7b0614ae52c03c5f4bc4e8dccc","tests/arr.rs":"97258231dfeefc52ec785c2019611cc1a339c3a13f744a26727a591f7e46a7a8","tests/generics.rs":"8da33daacab14d0fd685e0ca6292a2d19be23fa6c6e128921b554a7e1d6181a1","tests/hex.rs":"143d783defedd6609995862f8aac46b8c843272a8f877f83d2f7242de8814c02","tests/import_name.rs":"1235729ecbde47fc9a38b3bf35c750a53ed55e3cf967c9d2b24fd759dc9e9e0c","tests/iter.rs":"3e5e6a1354709e8bfa76e52969c61f3d21cb960027bb91745049c0dcdfa52bfd","tests/mod.rs":"75694855127075e14ddef490fffee3dea5a052bcdda2912878bd9995f3f2956d"},"package":"ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd"} \ No newline at end of file diff --git a/vendor/generic-array-0.12.4/CHANGELOG.md b/vendor/generic-array-0.12.4/CHANGELOG.md deleted file mode 100644 index d5e50e7b1..000000000 --- a/vendor/generic-array-0.12.4/CHANGELOG.md +++ /dev/null @@ -1,51 +0,0 @@ -* **`0.12.4`** - * Fix unsoundness in the `arr!` macro. - -* **`0.12.0`** - * Allow trailing commas in `arr!` macro. - * **BREAKING**: Serialize `GenericArray` using `serde` tuples, instead of variable-length sequences. This may not be compatible with old serialized data. - -* **`0.11.0`** - * **BREAKING** Redesign `GenericSequence` with an emphasis on use in generic type parameters. - * Add `MappedGenericSequence` and `FunctionalSequence` - * Implements optimized `map`, `zip` and `fold` for `GenericArray`, `&GenericArray` and `&mut GenericArray` - * **BREAKING** Remove `map_ref`, `zip_ref` and `map_slice` - * `map_slice` is now equivalent to `GenericArray::from_iter(slice.iter().map(...))` -* **`0.10.0`** - * Add `GenericSequence`, `Lengthen`, `Shorten`, `Split` and `Concat` traits. - * Redefine `transmute` to avert errors. -* **`0.9.0`** - * Rewrite construction methods to be well-defined in panic situations, correctly dropping elements. - * `NoDrop` crate replaced by `ManuallyDrop` as it became stable in Rust core. - * Add optimized `map`/`map_ref` and `zip`/`zip_ref` methods to `GenericArray` -* **`0.8.0`** - * Implement `AsRef`, `AsMut`, `Borrow`, `BorrowMut`, `Hash` for `GenericArray` - * Update `serde` to `1.0` - * Update `typenum` - * Make macro `arr!` non-cloning - * Implement `From<[T; N]>` up to `N=32` - * Fix #45 -* **`0.7.0`** - * Upgrade `serde` to `0.9` - * Make `serde` with `no_std` - * Implement `PartialOrd`/`Ord` for `GenericArray` -* **`0.6.0`** - * Fixed #30 - * Implement `Default` for `GenericArray` - * Implement `LowerHex` and `UpperHex` for `GenericArray` - * Use `precision` formatting field in hex representation - * Add `as_slice`, `as_mut_slice` - * Remove `GenericArray::new` in favor of `Default` trait - * Add `from_slice` and `from_mut_slice` - * `no_std` and `core` for crate. -* **`0.5.0`** - * Update `serde` - * remove `no_std` feature, fixed #19 -* **`0.4.0`** - * Re-export `typenum` -* **`0.3.0`** - * Implement `IntoIter` for `GenericArray` - * Add `map` method - * Add optional `serde` (de)serialization support feature. -* **`< 0.3.0`** - * Initial implementation in late 2015 diff --git a/vendor/generic-array-0.12.4/Cargo.toml b/vendor/generic-array-0.12.4/Cargo.toml deleted file mode 100644 index f4f4f4616..000000000 --- a/vendor/generic-array-0.12.4/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "generic-array" -version = "0.12.4" -authors = ["Bartłomiej Kamiński ", "Aaron Trent "] -description = "Generic types implementing functionality of arrays" -documentation = "http://fizyk20.github.io/generic-array/generic_array/" -readme = "README.md" -keywords = ["generic", "array"] -categories = ["data-structures", "no-std"] -license = "MIT" -repository = "https://github.com/fizyk20/generic-array.git" - -[lib] -name = "generic_array" -[dependencies.serde] -version = "1.0" -optional = true -default-features = false - -[dependencies.typenum] -version = "1.10" -[dev-dependencies.bincode] -version = "1.0" - -[dev-dependencies.serde_json] -version = "1.0" -[badges.travis-ci] -repository = "fizyk20/generic-array" diff --git a/vendor/generic-array-0.12.4/LICENSE b/vendor/generic-array-0.12.4/LICENSE deleted file mode 100644 index 5968bcccc..000000000 --- a/vendor/generic-array-0.12.4/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Bartłomiej Kamiński - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/generic-array-0.12.4/README.md b/vendor/generic-array-0.12.4/README.md deleted file mode 100644 index 0864ed627..000000000 --- a/vendor/generic-array-0.12.4/README.md +++ /dev/null @@ -1,34 +0,0 @@ -[![Crates.io](https://img.shields.io/crates/v/generic-array.svg)](https://crates.io/crates/generic-array) -[![Build Status](https://travis-ci.org/fizyk20/generic-array.svg?branch=master)](https://travis-ci.org/fizyk20/generic-array) -# generic-array - -This crate implements generic array types for Rust. - -[Documentation](http://fizyk20.github.io/generic-array/generic_array/) - -## Usage - -The Rust arrays `[T; N]` are problematic in that they can't be used generically with respect to `N`, so for example this won't work: - -```rust -struct Foo { - data: [i32; N] -} -``` - -**generic-array** defines a new trait `ArrayLength` and a struct `GenericArray>`, which let the above be implemented as: - -```rust -struct Foo> { - data: GenericArray -} -``` - -To actually define a type implementing `ArrayLength`, you can use unsigned integer types defined in [typenum](https://github.com/paholg/typenum) crate - for example, `GenericArray` would work almost like `[T; 5]` :) - -In version 0.1.1 an `arr!` macro was introduced, allowing for creation of arrays as shown below: - -```rust -let array = arr![u32; 1, 2, 3]; -assert_eq!(array[2], 3); -``` diff --git a/vendor/generic-array-0.12.4/rustfmt.toml b/vendor/generic-array-0.12.4/rustfmt.toml deleted file mode 100644 index 3dc0db27b..000000000 --- a/vendor/generic-array-0.12.4/rustfmt.toml +++ /dev/null @@ -1,3 +0,0 @@ -reorder_imports = true -reorder_imported_names = true -use_try_shorthand = true diff --git a/vendor/generic-array-0.12.4/src/arr.rs b/vendor/generic-array-0.12.4/src/arr.rs deleted file mode 100644 index ebe687500..000000000 --- a/vendor/generic-array-0.12.4/src/arr.rs +++ /dev/null @@ -1,126 +0,0 @@ -//! Implementation for `arr!` macro. - -use super::ArrayLength; -use core::ops::Add; -use typenum::U1; - -/// Helper trait for `arr!` macro -pub trait AddLength>: ArrayLength { - /// Resulting length - type Output: ArrayLength; -} - -impl AddLength for N1 -where - N1: ArrayLength + Add, - N2: ArrayLength, - >::Output: ArrayLength, -{ - type Output = >::Output; -} - -/// Helper type for `arr!` macro -pub type Inc = >::Output; - -#[doc(hidden)] -#[macro_export] -macro_rules! arr_impl { - (@replace_expr $e:expr)=>{ - 1 - }; - ($T:ty; $N:ty, [$($x:expr),*], []) => ({ - const __ARR_LENGTH:usize=0 $(+ $crate::arr_impl!(@replace_expr $x) )*; - fn __do_transmute<'a, T, N: $crate::ArrayLength>(arr: [T; __ARR_LENGTH]) -> $crate::GenericArray { - unsafe { $crate::transmute(arr) } - } - - let _:[();<$N as $crate::typenum::Unsigned>::USIZE]=[();__ARR_LENGTH]; - - __do_transmute::<$T,$N>([$($x),*]) - }); - ($T:ty; $N:ty, [], [$x1:expr]) => ( - $crate::arr_impl!($T; $crate::arr::Inc<$T, $N>, [$x1], []) - ); - ($T:ty; $N:ty, [], [$x1:expr, $($x:expr),+]) => ( - $crate::arr_impl!($T; $crate::arr::Inc<$T, $N>, [$x1], [$($x),+]) - ); - ($T:ty; $N:ty, [$($y:expr),+], [$x1:expr]) => ( - $crate::arr_impl!($T; $crate::arr::Inc<$T, $N>, [$($y),+, $x1], []) - ); - ($T:ty; $N:ty, [$($y:expr),+], [$x1:expr, $($x:expr),+]) => ( - $crate::arr_impl!($T; $crate::arr::Inc<$T, $N>, [$($y),+, $x1], [$($x),+]) - ); -} - -/// Macro allowing for easy generation of Generic Arrays. -/// Example: `let test = arr![u32; 1, 2, 3];` -#[macro_export] -macro_rules! arr { - ($T:ty; $(,)*) => ({ - unsafe { $crate::transmute::<[$T; 0], $crate::GenericArray<$T, $crate::typenum::U0>>([]) } - }); - ($T:ty; $($x:expr),* $(,)*) => ( - arr_impl!($T; $crate::typenum::U0, [], [$($x),*]) - ); - ($($x:expr,)+) => (arr![$($x),*]); - () => ("""Macro requires a type, e.g. `let array = arr![u32; 1, 2, 3];`") -} - - -mod doctests_only{ - /// - /// # With ellision - /// - /// Testing that lifetimes aren't transmuted when they're ellided. - /// - /// ```compile_fail - /// #[macro_use] extern crate generic_array; - /// fn main() { - /// fn unsound_lifetime_extension<'a, A>(a: &'a A) -> &'static A { - /// arr![&A; a][0] - /// } - /// } - /// ``` - /// - /// ```rust - /// #[macro_use] extern crate generic_array; - /// fn main() { - /// fn unsound_lifetime_extension<'a, A>(a: &'a A) -> &'a A { - /// arr![&A; a][0] - /// } - /// } - /// ``` - /// - /// # Without ellision - /// - /// Testing that lifetimes aren't transmuted when they're specified explicitly. - /// - /// ```compile_fail - /// #[macro_use] extern crate generic_array; - /// fn main() { - /// fn unsound_lifetime_extension<'a, A>(a: &'a A) -> &'static A { - /// arr![&'a A; a][0] - /// } - /// } - /// ``` - /// - /// ```compile_fail - /// #[macro_use] extern crate generic_array; - /// fn main() { - /// fn unsound_lifetime_extension<'a, A>(a: &'a A) -> &'static A { - /// arr![&'static A; a][0] - /// } - /// } - /// ``` - /// - /// ```rust - /// #[macro_use] extern crate generic_array; - /// fn main() { - /// fn unsound_lifetime_extension<'a, A>(a: &'a A) -> &'a A { - /// arr![&'a A; a][0] - /// } - /// } - /// ``` - #[allow(dead_code)] - pub enum DocTests{} -} diff --git a/vendor/generic-array-0.12.4/src/functional.rs b/vendor/generic-array-0.12.4/src/functional.rs deleted file mode 100644 index 50f4a71b8..000000000 --- a/vendor/generic-array-0.12.4/src/functional.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! Functional programming with generic sequences -//! -//! Please see `tests/generics.rs` for examples of how to best use these in your generic functions. - -use super::ArrayLength; -use core::iter::FromIterator; -use sequence::*; - -/// Defines the relationship between one generic sequence and another, -/// for operations such as `map` and `zip`. -pub unsafe trait MappedGenericSequence: GenericSequence -where - Self::Length: ArrayLength, -{ - /// Mapped sequence type - type Mapped: GenericSequence; -} - -unsafe impl<'a, T, U, S: MappedGenericSequence> MappedGenericSequence for &'a S -where - &'a S: GenericSequence, - S: GenericSequence>::Length>, - >::Length: ArrayLength, -{ - type Mapped = >::Mapped; -} - -unsafe impl<'a, T, U, S: MappedGenericSequence> MappedGenericSequence for &'a mut S -where - &'a mut S: GenericSequence, - S: GenericSequence>::Length>, - >::Length: ArrayLength, -{ - type Mapped = >::Mapped; -} - -/// Accessor type for a mapped generic sequence -pub type MappedSequence = - <>::Mapped as GenericSequence>::Sequence; - -/// Defines functional programming methods for generic sequences -pub unsafe trait FunctionalSequence: GenericSequence { - /// Maps a `GenericSequence` to another `GenericSequence`. - /// - /// If the mapping function panics, any already initialized elements in the new sequence - /// will be dropped, AND any unused elements in the source sequence will also be dropped. - fn map(self, f: F) -> MappedSequence - where - Self: MappedGenericSequence, - Self::Length: ArrayLength, - F: FnMut(Self::Item) -> U, - { - FromIterator::from_iter(self.into_iter().map(f)) - } - - /// Combines two `GenericSequence` instances and iterates through both of them, - /// initializing a new `GenericSequence` with the result of the zipped mapping function. - /// - /// If the mapping function panics, any already initialized elements in the new sequence - /// will be dropped, AND any unused elements in the source sequences will also be dropped. - #[inline] - fn zip(self, rhs: Rhs, f: F) -> MappedSequence - where - Self: MappedGenericSequence, - Rhs: MappedGenericSequence>, - Self::Length: ArrayLength + ArrayLength, - Rhs: GenericSequence, - F: FnMut(Self::Item, Rhs::Item) -> U, - { - rhs.inverted_zip2(self, f) - } - - /// Folds (or reduces) a sequence of data into a single value. - /// - /// If the fold function panics, any unused elements will be dropped. - fn fold(self, init: U, f: F) -> U - where - F: FnMut(U, Self::Item) -> U, - { - self.into_iter().fold(init, f) - } -} - -unsafe impl<'a, T, S: GenericSequence> FunctionalSequence for &'a S -where - &'a S: GenericSequence, -{ -} - -unsafe impl<'a, T, S: GenericSequence> FunctionalSequence for &'a mut S -where - &'a mut S: GenericSequence, -{ -} diff --git a/vendor/generic-array-0.12.4/src/hex.rs b/vendor/generic-array-0.12.4/src/hex.rs deleted file mode 100644 index 3ef92b1b9..000000000 --- a/vendor/generic-array-0.12.4/src/hex.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! Generic array are commonly used as a return value for hash digests, so -//! it's a good idea to allow to hexlify them easily. This module implements -//! `std::fmt::LowerHex` and `std::fmt::UpperHex` traits. -//! -//! Example: -//! -//! ```rust -//! # #[macro_use] -//! # extern crate generic_array; -//! # extern crate typenum; -//! # fn main() { -//! let array = arr![u8; 10, 20, 30]; -//! assert_eq!(format!("{:x}", array), "0a141e"); -//! # } -//! ``` -//! - -use {ArrayLength, GenericArray}; -use core::cmp::min; -use core::fmt; -use core::ops::Add; -use core::str; -use typenum::*; - -static LOWER_CHARS: &'static [u8] = b"0123456789abcdef"; -static UPPER_CHARS: &'static [u8] = b"0123456789ABCDEF"; - -impl> fmt::LowerHex for GenericArray -where - T: Add, - >::Output: ArrayLength, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let max_digits = f.precision().unwrap_or_else(|| self.len() * 2); - let max_hex = (max_digits >> 1) + (max_digits & 1); - - if T::to_usize() < 1024 { - // For small arrays use a stack allocated - // buffer of 2x number of bytes - let mut res = GenericArray::>::default(); - - for (i, c) in self.iter().take(max_hex).enumerate() { - res[i * 2] = LOWER_CHARS[(c >> 4) as usize]; - res[i * 2 + 1] = LOWER_CHARS[(c & 0xF) as usize]; - } - f.write_str(unsafe { str::from_utf8_unchecked(&res[..max_digits]) })?; - } else { - // For large array use chunks of up to 1024 bytes (2048 hex chars) - let mut buf = [0u8; 2048]; - let mut digits_left = max_digits; - - for chunk in self[..max_hex].chunks(1024) { - for (i, c) in chunk.iter().enumerate() { - buf[i * 2] = LOWER_CHARS[(c >> 4) as usize]; - buf[i * 2 + 1] = LOWER_CHARS[(c & 0xF) as usize]; - } - let n = min(chunk.len() * 2, digits_left); - f.write_str(unsafe { str::from_utf8_unchecked(&buf[..n]) })?; - digits_left -= n; - } - } - Ok(()) - } -} - -impl> fmt::UpperHex for GenericArray -where - T: Add, - >::Output: ArrayLength, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let max_digits = f.precision().unwrap_or_else(|| self.len() * 2); - let max_hex = (max_digits >> 1) + (max_digits & 1); - - if T::to_usize() < 1024 { - // For small arrays use a stack allocated - // buffer of 2x number of bytes - let mut res = GenericArray::>::default(); - - for (i, c) in self.iter().take(max_hex).enumerate() { - res[i * 2] = UPPER_CHARS[(c >> 4) as usize]; - res[i * 2 + 1] = UPPER_CHARS[(c & 0xF) as usize]; - } - f.write_str(unsafe { str::from_utf8_unchecked(&res[..max_digits]) })?; - } else { - // For large array use chunks of up to 1024 bytes (2048 hex chars) - let mut buf = [0u8; 2048]; - let mut digits_left = max_digits; - - for chunk in self[..max_hex].chunks(1024) { - for (i, c) in chunk.iter().enumerate() { - buf[i * 2] = UPPER_CHARS[(c >> 4) as usize]; - buf[i * 2 + 1] = UPPER_CHARS[(c & 0xF) as usize]; - } - let n = min(chunk.len() * 2, digits_left); - f.write_str(unsafe { str::from_utf8_unchecked(&buf[..n]) })?; - digits_left -= n; - } - } - Ok(()) - } -} diff --git a/vendor/generic-array-0.12.4/src/impl_serde.rs b/vendor/generic-array-0.12.4/src/impl_serde.rs deleted file mode 100644 index da1df2fc0..000000000 --- a/vendor/generic-array-0.12.4/src/impl_serde.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! Serde serialization/deserialization implementation - -use core::fmt; -use core::marker::PhantomData; -use serde::de::{self, SeqAccess, Visitor}; -use serde::{ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer}; -use {ArrayLength, GenericArray}; - -impl Serialize for GenericArray -where - T: Serialize, - N: ArrayLength, -{ - #[inline] - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut tup = serializer.serialize_tuple(N::to_usize())?; - for el in self { - tup.serialize_element(el)?; - } - - tup.end() - } -} - -struct GAVisitor { - _t: PhantomData, - _n: PhantomData, -} - -impl<'de, T, N> Visitor<'de> for GAVisitor -where - T: Deserialize<'de> + Default, - N: ArrayLength, -{ - type Value = GenericArray; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("struct GenericArray") - } - - fn visit_seq(self, mut seq: A) -> Result, A::Error> - where - A: SeqAccess<'de>, - { - let mut result = GenericArray::default(); - for i in 0..N::to_usize() { - result[i] = seq - .next_element()? - .ok_or_else(|| de::Error::invalid_length(i, &self))?; - } - Ok(result) - } -} - -impl<'de, T, N> Deserialize<'de> for GenericArray -where - T: Deserialize<'de> + Default, - N: ArrayLength, -{ - fn deserialize(deserializer: D) -> Result, D::Error> - where - D: Deserializer<'de>, - { - let visitor = GAVisitor { - _t: PhantomData, - _n: PhantomData, - }; - deserializer.deserialize_tuple(N::to_usize(), visitor) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use bincode; - use typenum; - - #[test] - fn test_serialize() { - let array = GenericArray::::default(); - let serialized = bincode::serialize(&array); - assert!(serialized.is_ok()); - } - - #[test] - fn test_deserialize() { - let mut array = GenericArray::::default(); - array[0] = 1; - array[1] = 2; - let serialized = bincode::serialize(&array).unwrap(); - let deserialized = bincode::deserialize::>(&array); - assert!(deserialized.is_ok()); - let array = deserialized.unwrap(); - assert_eq!(array[0], 1); - assert_eq!(array[1], 2); - } - - #[test] - fn test_serialized_size() { - let array = GenericArray::::default(); - let size = bincode::serialized_size(&array).unwrap(); - assert_eq!(size, 1); - } - -} diff --git a/vendor/generic-array-0.12.4/src/impls.rs b/vendor/generic-array-0.12.4/src/impls.rs deleted file mode 100644 index ea5a3c4c9..000000000 --- a/vendor/generic-array-0.12.4/src/impls.rs +++ /dev/null @@ -1,182 +0,0 @@ -use super::{ArrayLength, GenericArray}; -use core::borrow::{Borrow, BorrowMut}; -use core::cmp::Ordering; -use core::fmt::{self, Debug}; -use core::hash::{Hash, Hasher}; -use functional::*; -use sequence::*; - -impl Default for GenericArray -where - N: ArrayLength, -{ - #[inline] - fn default() -> Self { - Self::generate(|_| T::default()) - } -} - -impl Clone for GenericArray -where - N: ArrayLength, -{ - fn clone(&self) -> GenericArray { - self.map(Clone::clone) - } -} - -impl Copy for GenericArray -where - N: ArrayLength, - N::ArrayType: Copy, -{ -} - -impl PartialEq for GenericArray -where - N: ArrayLength, -{ - fn eq(&self, other: &Self) -> bool { - **self == **other - } -} -impl Eq for GenericArray -where - N: ArrayLength, -{ -} - -impl PartialOrd for GenericArray -where - N: ArrayLength, -{ - fn partial_cmp(&self, other: &GenericArray) -> Option { - PartialOrd::partial_cmp(self.as_slice(), other.as_slice()) - } -} - -impl Ord for GenericArray -where - N: ArrayLength, -{ - fn cmp(&self, other: &GenericArray) -> Ordering { - Ord::cmp(self.as_slice(), other.as_slice()) - } -} - -impl Debug for GenericArray -where - N: ArrayLength, -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - self[..].fmt(fmt) - } -} - -impl Borrow<[T]> for GenericArray -where - N: ArrayLength, -{ - #[inline(always)] - fn borrow(&self) -> &[T] { - &self[..] - } -} - -impl BorrowMut<[T]> for GenericArray -where - N: ArrayLength, -{ - #[inline(always)] - fn borrow_mut(&mut self) -> &mut [T] { - &mut self[..] - } -} - -impl AsRef<[T]> for GenericArray -where - N: ArrayLength, -{ - #[inline(always)] - fn as_ref(&self) -> &[T] { - &self[..] - } -} - -impl AsMut<[T]> for GenericArray -where - N: ArrayLength, -{ - #[inline(always)] - fn as_mut(&mut self) -> &mut [T] { - &mut self[..] - } -} - -impl Hash for GenericArray -where - N: ArrayLength, -{ - fn hash(&self, state: &mut H) - where - H: Hasher, - { - Hash::hash(&self[..], state) - } -} - -macro_rules! impl_from { - ($($n: expr => $ty: ty),*) => { - $( - impl From<[T; $n]> for GenericArray { - #[inline(always)] - fn from(arr: [T; $n]) -> Self { - unsafe { $crate::transmute(arr) } - } - } - - impl Into<[T; $n]> for GenericArray { - #[inline(always)] - fn into(self) -> [T; $n] { - unsafe { $crate::transmute(self) } - } - } - )* - - } -} - -impl_from! { - 1 => ::typenum::U1, - 2 => ::typenum::U2, - 3 => ::typenum::U3, - 4 => ::typenum::U4, - 5 => ::typenum::U5, - 6 => ::typenum::U6, - 7 => ::typenum::U7, - 8 => ::typenum::U8, - 9 => ::typenum::U9, - 10 => ::typenum::U10, - 11 => ::typenum::U11, - 12 => ::typenum::U12, - 13 => ::typenum::U13, - 14 => ::typenum::U14, - 15 => ::typenum::U15, - 16 => ::typenum::U16, - 17 => ::typenum::U17, - 18 => ::typenum::U18, - 19 => ::typenum::U19, - 20 => ::typenum::U20, - 21 => ::typenum::U21, - 22 => ::typenum::U22, - 23 => ::typenum::U23, - 24 => ::typenum::U24, - 25 => ::typenum::U25, - 26 => ::typenum::U26, - 27 => ::typenum::U27, - 28 => ::typenum::U28, - 29 => ::typenum::U29, - 30 => ::typenum::U30, - 31 => ::typenum::U31, - 32 => ::typenum::U32 -} diff --git a/vendor/generic-array-0.12.4/src/iter.rs b/vendor/generic-array-0.12.4/src/iter.rs deleted file mode 100644 index a2d67fc67..000000000 --- a/vendor/generic-array-0.12.4/src/iter.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! `GenericArray` iterator implementation. - -use super::{ArrayLength, GenericArray}; -use core::{cmp, ptr, fmt, mem}; -use core::mem::ManuallyDrop; - -/// An iterator that moves out of a `GenericArray` -pub struct GenericArrayIter> { - // Invariants: index <= index_back <= N - // Only values in array[index..index_back] are alive at any given time. - // Values from array[..index] and array[index_back..] are already moved/dropped. - array: ManuallyDrop>, - index: usize, - index_back: usize, -} - -#[cfg(test)] -mod test { - use super::*; - - fn send(_iter: I) {} - - #[test] - fn test_send_iter() { - send(GenericArray::from([1, 2, 3, 4]).into_iter()); - } -} - -impl GenericArrayIter -where - N: ArrayLength, -{ - /// Returns the remaining items of this iterator as a slice - #[inline] - pub fn as_slice(&self) -> &[T] { - &self.array.as_slice()[self.index..self.index_back] - } - - /// Returns the remaining items of this iterator as a mutable slice - #[inline] - pub fn as_mut_slice(&mut self) -> &mut [T] { - &mut self.array.as_mut_slice()[self.index..self.index_back] - } -} - -impl IntoIterator for GenericArray -where - N: ArrayLength, -{ - type Item = T; - type IntoIter = GenericArrayIter; - - fn into_iter(self) -> Self::IntoIter { - GenericArrayIter { - array: ManuallyDrop::new(self), - index: 0, - index_back: N::to_usize(), - } - } -} - -// Based on work in rust-lang/rust#49000 -impl fmt::Debug for GenericArrayIter -where - N: ArrayLength, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_tuple("GenericArrayIter") - .field(&self.as_slice()) - .finish() - } -} - -impl Drop for GenericArrayIter -where - N: ArrayLength, -{ - #[inline] - fn drop(&mut self) { - // Drop values that are still alive. - for p in self.as_mut_slice() { - unsafe { - ptr::drop_in_place(p); - } - } - } -} - -// Based on work in rust-lang/rust#49000 -impl Clone for GenericArrayIter -where - N: ArrayLength, -{ - fn clone(&self) -> Self { - // This places all cloned elements at the start of the new array iterator, - // not at their original indices. - unsafe { - let mut iter = GenericArrayIter { - array: ManuallyDrop::new(mem::uninitialized()), - index: 0, - index_back: 0, - }; - - for (dst, src) in iter.array.iter_mut().zip(self.as_slice()) { - ptr::write(dst, src.clone()); - - iter.index_back += 1; - } - - iter - } - } -} - -impl Iterator for GenericArrayIter -where - N: ArrayLength, -{ - type Item = T; - - #[inline] - fn next(&mut self) -> Option { - if self.index < self.index_back { - let p = unsafe { Some(ptr::read(self.array.get_unchecked(self.index))) }; - - self.index += 1; - - p - } else { - None - } - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - let len = self.len(); - (len, Some(len)) - } - - #[inline] - fn count(self) -> usize { - self.len() - } - - fn nth(&mut self, n: usize) -> Option { - // First consume values prior to the nth. - let ndrop = cmp::min(n, self.len()); - - for p in &mut self.array[self.index..self.index + ndrop] { - self.index += 1; - - unsafe { - ptr::drop_in_place(p); - } - } - - self.next() - } - - fn last(mut self) -> Option { - // Note, everything else will correctly drop first as `self` leaves scope. - self.next_back() - } -} - -impl DoubleEndedIterator for GenericArrayIter -where - N: ArrayLength, -{ - fn next_back(&mut self) -> Option { - if self.index < self.index_back { - self.index_back -= 1; - - unsafe { Some(ptr::read(self.array.get_unchecked(self.index_back))) } - } else { - None - } - } -} - -impl ExactSizeIterator for GenericArrayIter -where - N: ArrayLength, -{ - fn len(&self) -> usize { - self.index_back - self.index - } -} - -// TODO: Implement `FusedIterator` and `TrustedLen` when stabilized \ No newline at end of file diff --git a/vendor/generic-array-0.12.4/src/lib.rs b/vendor/generic-array-0.12.4/src/lib.rs deleted file mode 100644 index e98e8fd58..000000000 --- a/vendor/generic-array-0.12.4/src/lib.rs +++ /dev/null @@ -1,632 +0,0 @@ -//! This crate implements a structure that can be used as a generic array type.use -//! Core Rust array types `[T; N]` can't be used generically with -//! respect to `N`, so for example this: -//! -//! ```{should_fail} -//! struct Foo { -//! data: [T; N] -//! } -//! ``` -//! -//! won't work. -//! -//! **generic-array** exports a `GenericArray` type, which lets -//! the above be implemented as: -//! -//! ``` -//! # use generic_array::{ArrayLength, GenericArray}; -//! struct Foo> { -//! data: GenericArray -//! } -//! ``` -//! -//! The `ArrayLength` trait is implemented by default for -//! [unsigned integer types](../typenum/uint/index.html) from -//! [typenum](../typenum/index.html). -//! -//! For ease of use, an `arr!` macro is provided - example below: -//! -//! ``` -//! # #[macro_use] -//! # extern crate generic_array; -//! # extern crate typenum; -//! # fn main() { -//! let array = arr![u32; 1, 2, 3]; -//! assert_eq!(array[2], 3); -//! # } -//! ``` - -#![deny(missing_docs)] -#![no_std] - -#[cfg(feature = "serde")] -extern crate serde; - -#[cfg(test)] -extern crate bincode; - -pub extern crate typenum; - -mod hex; -mod impls; - -#[cfg(feature = "serde")] -pub mod impl_serde; - -use core::iter::FromIterator; -use core::marker::PhantomData; -use core::mem::ManuallyDrop; -use core::ops::{Deref, DerefMut}; -use core::{mem, ptr, slice}; -use typenum::bit::{B0, B1}; -use typenum::uint::{UInt, UTerm, Unsigned}; - -#[cfg_attr(test, macro_use)] -pub mod arr; -pub mod functional; -pub mod iter; -pub mod sequence; - -use functional::*; -pub use iter::GenericArrayIter; -use sequence::*; - -/// Trait making `GenericArray` work, marking types to be used as length of an array -pub unsafe trait ArrayLength: Unsigned { - /// Associated type representing the array type for the number - type ArrayType; -} - -unsafe impl ArrayLength for UTerm { - #[doc(hidden)] - type ArrayType = (); -} - -/// Internal type used to generate a struct of appropriate size -#[allow(dead_code)] -#[repr(C)] -#[doc(hidden)] -pub struct GenericArrayImplEven { - parent1: U, - parent2: U, - _marker: PhantomData, -} - -impl Clone for GenericArrayImplEven { - fn clone(&self) -> GenericArrayImplEven { - GenericArrayImplEven { - parent1: self.parent1.clone(), - parent2: self.parent2.clone(), - _marker: PhantomData, - } - } -} - -impl Copy for GenericArrayImplEven {} - -/// Internal type used to generate a struct of appropriate size -#[allow(dead_code)] -#[repr(C)] -#[doc(hidden)] -pub struct GenericArrayImplOdd { - parent1: U, - parent2: U, - data: T, -} - -impl Clone for GenericArrayImplOdd { - fn clone(&self) -> GenericArrayImplOdd { - GenericArrayImplOdd { - parent1: self.parent1.clone(), - parent2: self.parent2.clone(), - data: self.data.clone(), - } - } -} - -impl Copy for GenericArrayImplOdd {} - -unsafe impl> ArrayLength for UInt { - #[doc(hidden)] - type ArrayType = GenericArrayImplEven; -} - -unsafe impl> ArrayLength for UInt { - #[doc(hidden)] - type ArrayType = GenericArrayImplOdd; -} - -/// Struct representing a generic array - `GenericArray` works like [T; N] -#[allow(dead_code)] -pub struct GenericArray> { - data: U::ArrayType, -} - -unsafe impl> Send for GenericArray {} -unsafe impl> Sync for GenericArray {} - -impl Deref for GenericArray -where - N: ArrayLength, -{ - type Target = [T]; - - #[inline(always)] - fn deref(&self) -> &[T] { - unsafe { slice::from_raw_parts(self as *const Self as *const T, N::to_usize()) } - } -} - -impl DerefMut for GenericArray -where - N: ArrayLength, -{ - #[inline(always)] - fn deref_mut(&mut self) -> &mut [T] { - unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut T, N::to_usize()) } - } -} - -/// Creates an array one element at a time using a mutable iterator -/// you can write to with `ptr::write`. -/// -/// Incremenent the position while iterating to mark off created elements, -/// which will be dropped if `into_inner` is not called. -#[doc(hidden)] -pub struct ArrayBuilder> { - array: ManuallyDrop>, - position: usize, -} - -impl> ArrayBuilder { - #[doc(hidden)] - #[inline] - pub unsafe fn new() -> ArrayBuilder { - ArrayBuilder { - array: ManuallyDrop::new(mem::uninitialized()), - position: 0, - } - } - - /// Creates a mutable iterator for writing to the array using `ptr::write`. - /// - /// Increment the position value given as a mutable reference as you iterate - /// to mark how many elements have been created. - #[doc(hidden)] - #[inline] - pub unsafe fn iter_position(&mut self) -> (slice::IterMut, &mut usize) { - (self.array.iter_mut(), &mut self.position) - } - - /// When done writing (assuming all elements have been written to), - /// get the inner array. - #[doc(hidden)] - #[inline] - pub unsafe fn into_inner(self) -> GenericArray { - let array = ptr::read(&self.array); - - mem::forget(self); - - ManuallyDrop::into_inner(array) - } -} - -impl> Drop for ArrayBuilder { - fn drop(&mut self) { - for value in &mut self.array[..self.position] { - unsafe { - ptr::drop_in_place(value); - } - } - } -} - -/// Consumes an array. -/// -/// Increment the position while iterating and any leftover elements -/// will be dropped if position does not go to N -#[doc(hidden)] -pub struct ArrayConsumer> { - array: ManuallyDrop>, - position: usize, -} - -impl> ArrayConsumer { - #[doc(hidden)] - #[inline] - pub unsafe fn new(array: GenericArray) -> ArrayConsumer { - ArrayConsumer { - array: ManuallyDrop::new(array), - position: 0, - } - } - - /// Creates an iterator and mutable reference to the internal position - /// to keep track of consumed elements. - /// - /// Increment the position as you iterate to mark off consumed elements - #[doc(hidden)] - #[inline] - pub unsafe fn iter_position(&mut self) -> (slice::Iter, &mut usize) { - (self.array.iter(), &mut self.position) - } -} - -impl> Drop for ArrayConsumer { - fn drop(&mut self) { - for value in &mut self.array[self.position..N::to_usize()] { - unsafe { - ptr::drop_in_place(value); - } - } - } -} - -impl<'a, T: 'a, N> IntoIterator for &'a GenericArray -where - N: ArrayLength, -{ - type IntoIter = slice::Iter<'a, T>; - type Item = &'a T; - - fn into_iter(self: &'a GenericArray) -> Self::IntoIter { - self.as_slice().iter() - } -} - -impl<'a, T: 'a, N> IntoIterator for &'a mut GenericArray -where - N: ArrayLength, -{ - type IntoIter = slice::IterMut<'a, T>; - type Item = &'a mut T; - - fn into_iter(self: &'a mut GenericArray) -> Self::IntoIter { - self.as_mut_slice().iter_mut() - } -} - -impl FromIterator for GenericArray -where - N: ArrayLength, -{ - fn from_iter(iter: I) -> GenericArray - where - I: IntoIterator, - { - unsafe { - let mut destination = ArrayBuilder::new(); - - { - let (destination_iter, position) = destination.iter_position(); - - for (src, dst) in iter.into_iter().zip(destination_iter) { - ptr::write(dst, src); - - *position += 1; - } - } - - if destination.position < N::to_usize() { - from_iter_length_fail(destination.position, N::to_usize()); - } - - destination.into_inner() - } - } -} - -#[inline(never)] -#[cold] -fn from_iter_length_fail(length: usize, expected: usize) -> ! { - panic!( - "GenericArray::from_iter received {} elements but expected {}", - length, expected - ); -} - -unsafe impl GenericSequence for GenericArray -where - N: ArrayLength, - Self: IntoIterator, -{ - type Length = N; - type Sequence = Self; - - fn generate(mut f: F) -> GenericArray - where - F: FnMut(usize) -> T, - { - unsafe { - let mut destination = ArrayBuilder::new(); - - { - let (destination_iter, position) = destination.iter_position(); - - for (i, dst) in destination_iter.enumerate() { - ptr::write(dst, f(i)); - - *position += 1; - } - } - - destination.into_inner() - } - } - - #[doc(hidden)] - fn inverted_zip( - self, - lhs: GenericArray, - mut f: F, - ) -> MappedSequence, B, U> - where - GenericArray: - GenericSequence + MappedGenericSequence, - Self: MappedGenericSequence, - Self::Length: ArrayLength + ArrayLength, - F: FnMut(B, Self::Item) -> U, - { - unsafe { - let mut left = ArrayConsumer::new(lhs); - let mut right = ArrayConsumer::new(self); - - let (left_array_iter, left_position) = left.iter_position(); - let (right_array_iter, right_position) = right.iter_position(); - - FromIterator::from_iter(left_array_iter.zip(right_array_iter).map(|(l, r)| { - let left_value = ptr::read(l); - let right_value = ptr::read(r); - - *left_position += 1; - *right_position += 1; - - f(left_value, right_value) - })) - } - } - - #[doc(hidden)] - fn inverted_zip2(self, lhs: Lhs, mut f: F) -> MappedSequence - where - Lhs: GenericSequence + MappedGenericSequence, - Self: MappedGenericSequence, - Self::Length: ArrayLength + ArrayLength, - F: FnMut(Lhs::Item, Self::Item) -> U, - { - unsafe { - let mut right = ArrayConsumer::new(self); - - let (right_array_iter, right_position) = right.iter_position(); - - FromIterator::from_iter( - lhs.into_iter() - .zip(right_array_iter) - .map(|(left_value, r)| { - let right_value = ptr::read(r); - - *right_position += 1; - - f(left_value, right_value) - }), - ) - } - } -} - -unsafe impl MappedGenericSequence for GenericArray -where - N: ArrayLength + ArrayLength, - GenericArray: GenericSequence, -{ - type Mapped = GenericArray; -} - -unsafe impl FunctionalSequence for GenericArray -where - N: ArrayLength, - Self: GenericSequence, -{ - fn map(self, mut f: F) -> MappedSequence - where - Self::Length: ArrayLength, - Self: MappedGenericSequence, - F: FnMut(T) -> U, - { - unsafe { - let mut source = ArrayConsumer::new(self); - - let (array_iter, position) = source.iter_position(); - - FromIterator::from_iter(array_iter.map(|src| { - let value = ptr::read(src); - - *position += 1; - - f(value) - })) - } - } - - #[inline] - fn zip(self, rhs: Rhs, f: F) -> MappedSequence - where - Self: MappedGenericSequence, - Rhs: MappedGenericSequence>, - Self::Length: ArrayLength + ArrayLength, - Rhs: GenericSequence, - F: FnMut(T, Rhs::Item) -> U, - { - rhs.inverted_zip(self, f) - } - - fn fold(self, init: U, mut f: F) -> U - where - F: FnMut(U, T) -> U, - { - unsafe { - let mut source = ArrayConsumer::new(self); - - let (array_iter, position) = source.iter_position(); - - array_iter.fold(init, |acc, src| { - let value = ptr::read(src); - - *position += 1; - - f(acc, value) - }) - } - } -} - -impl GenericArray -where - N: ArrayLength, -{ - /// Extracts a slice containing the entire array. - #[inline] - pub fn as_slice(&self) -> &[T] { - self.deref() - } - - /// Extracts a mutable slice containing the entire array. - #[inline] - pub fn as_mut_slice(&mut self) -> &mut [T] { - self.deref_mut() - } - - /// Converts slice to a generic array reference with inferred length; - /// - /// Length of the slice must be equal to the length of the array. - #[inline] - pub fn from_slice(slice: &[T]) -> &GenericArray { - slice.into() - } - - /// Converts mutable slice to a mutable generic array reference - /// - /// Length of the slice must be equal to the length of the array. - #[inline] - pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray { - slice.into() - } -} - -impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a GenericArray { - /// Converts slice to a generic array reference with inferred length; - /// - /// Length of the slice must be equal to the length of the array. - #[inline] - fn from(slice: &[T]) -> &GenericArray { - assert_eq!(slice.len(), N::to_usize()); - - unsafe { &*(slice.as_ptr() as *const GenericArray) } - } -} - -impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut GenericArray { - /// Converts mutable slice to a mutable generic array reference - /// - /// Length of the slice must be equal to the length of the array. - #[inline] - fn from(slice: &mut [T]) -> &mut GenericArray { - assert_eq!(slice.len(), N::to_usize()); - - unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray) } - } -} - -impl GenericArray -where - N: ArrayLength, -{ - /// Construct a `GenericArray` from a slice by cloning its content - /// - /// Length of the slice must be equal to the length of the array - #[inline] - pub fn clone_from_slice(list: &[T]) -> GenericArray { - Self::from_exact_iter(list.iter().cloned()) - .expect("Slice must be the same length as the array") - } -} - -impl GenericArray -where - N: ArrayLength, -{ - /// Creates a new `GenericArray` instance from an iterator with a known exact size. - /// - /// Returns `None` if the size is not equal to the number of elements in the `GenericArray`. - pub fn from_exact_iter(iter: I) -> Option - where - I: IntoIterator, - ::IntoIter: ExactSizeIterator, - { - let iter = iter.into_iter(); - - if iter.len() == N::to_usize() { - unsafe { - let mut destination = ArrayBuilder::new(); - - { - let (destination_iter, position) = destination.iter_position(); - - for (dst, src) in destination_iter.zip(iter.into_iter()) { - ptr::write(dst, src); - - *position += 1; - } - } - - Some(destination.into_inner()) - } - } else { - None - } - } -} - -/// A reimplementation of the `transmute` function, avoiding problems -/// when the compiler can't prove equal sizes. -#[inline] -#[doc(hidden)] -pub unsafe fn transmute(a: A) -> B { - let b = ::core::ptr::read(&a as *const A as *const B); - ::core::mem::forget(a); - b -} - -#[cfg(test)] -mod test { - // Compile with: - // cargo rustc --lib --profile test --release -- - // -C target-cpu=native -C opt-level=3 --emit asm - // and view the assembly to make sure test_assembly generates - // SIMD instructions instead of a niave loop. - - #[inline(never)] - pub fn black_box(val: T) -> T { - use core::{mem, ptr}; - - let ret = unsafe { ptr::read_volatile(&val) }; - mem::forget(val); - ret - } - - #[test] - fn test_assembly() { - use functional::*; - - let a = black_box(arr![i32; 1, 3, 5, 7]); - let b = black_box(arr![i32; 2, 4, 6, 8]); - - let c = (&a).zip(b, |l, r| l + r); - - let d = a.fold(0, |a, x| a + x); - - assert_eq!(c, arr![i32; 3, 7, 11, 15]); - - assert_eq!(d, 16); - } -} diff --git a/vendor/generic-array-0.12.4/src/sequence.rs b/vendor/generic-array-0.12.4/src/sequence.rs deleted file mode 100644 index 7b928abda..000000000 --- a/vendor/generic-array-0.12.4/src/sequence.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! Useful traits for manipulating sequences of data stored in `GenericArray`s - -use super::*; -use core::{mem, ptr}; -use core::ops::{Add, Sub}; -use typenum::operator_aliases::*; - -/// Defines some sequence with an associated length and iteration capabilities. -/// -/// This is useful for passing N-length generic arrays as generics. -pub unsafe trait GenericSequence: Sized + IntoIterator { - /// `GenericArray` associated length - type Length: ArrayLength; - - /// Concrete sequence type used in conjuction with reference implementations of `GenericSequence` - type Sequence: GenericSequence + FromIterator; - - /// Initializes a new sequence instance using the given function. - /// - /// If the generator function panics while initializing the sequence, - /// any already initialized elements will be dropped. - fn generate(f: F) -> Self::Sequence - where - F: FnMut(usize) -> T; - - #[doc(hidden)] - fn inverted_zip( - self, - lhs: GenericArray, - mut f: F, - ) -> MappedSequence, B, U> - where - GenericArray: GenericSequence - + MappedGenericSequence, - Self: MappedGenericSequence, - Self::Length: ArrayLength + ArrayLength, - F: FnMut(B, Self::Item) -> U, - { - unsafe { - let mut left = ArrayConsumer::new(lhs); - - let (left_array_iter, left_position) = left.iter_position(); - - FromIterator::from_iter( - left_array_iter - .zip(self.into_iter()) - .map(|(l, right_value)| { - let left_value = ptr::read(l); - - *left_position += 1; - - f(left_value, right_value) - }) - ) - } - } - - #[doc(hidden)] - fn inverted_zip2(self, lhs: Lhs, mut f: F) -> MappedSequence - where - Lhs: GenericSequence + MappedGenericSequence, - Self: MappedGenericSequence, - Self::Length: ArrayLength + ArrayLength, - F: FnMut(Lhs::Item, Self::Item) -> U, - { - FromIterator::from_iter(lhs.into_iter().zip(self.into_iter()).map(|(l, r)| f(l, r))) - } -} - -/// Accessor for `GenericSequence` item type, which is really `IntoIterator::Item` -/// -/// For deeply nested generic mapped sequence types, like shown in `tests/generics.rs`, -/// this can be useful for keeping things organized. -pub type SequenceItem = ::Item; - -unsafe impl<'a, T: 'a, S: GenericSequence> GenericSequence for &'a S -where - &'a S: IntoIterator, -{ - type Length = S::Length; - type Sequence = S::Sequence; - - #[inline] - fn generate(f: F) -> Self::Sequence - where - F: FnMut(usize) -> T, - { - S::generate(f) - } -} - -unsafe impl<'a, T: 'a, S: GenericSequence> GenericSequence for &'a mut S -where - &'a mut S: IntoIterator, -{ - type Length = S::Length; - type Sequence = S::Sequence; - - #[inline] - fn generate(f: F) -> Self::Sequence - where - F: FnMut(usize) -> T, - { - S::generate(f) - } -} - -/// Defines any `GenericSequence` which can be lengthened or extended by appending -/// or prepending an element to it. -/// -/// Any lengthened sequence can be shortened back to the original using `pop_front` or `pop_back` -pub unsafe trait Lengthen: Sized + GenericSequence { - /// `GenericSequence` that has one more element than `Self` - type Longer: Shorten; - - /// Returns a new array with the given element appended to the end of it. - /// - /// Example: - /// - /// ```ignore - /// let a = arr![i32; 1, 2, 3]; - /// - /// let b = a.append(4); - /// - /// assert_eq!(b, arr![i32; 1, 2, 3, 4]); - /// ``` - fn append(self, last: T) -> Self::Longer; - - /// Returns a new array with the given element prepended to the front of it. - /// - /// Example: - /// - /// ```ignore - /// let a = arr![i32; 1, 2, 3]; - /// - /// let b = a.prepend(4); - /// - /// assert_eq!(b, arr![i32; 4, 1, 2, 3]); - /// ``` - fn prepend(self, first: T) -> Self::Longer; -} - -/// Defines a `GenericSequence` which can be shortened by removing the first or last element from it. -/// -/// Additionally, any shortened sequence can be lengthened by -/// appending or prepending an element to it. -pub unsafe trait Shorten: Sized + GenericSequence { - /// `GenericSequence` that has one less element than `Self` - type Shorter: Lengthen; - - /// Returns a new array without the last element, and the last element. - /// - /// Example: - /// - /// ```ignore - /// let a = arr![i32; 1, 2, 3, 4]; - /// - /// let (init, last) = a.pop_back(); - /// - /// assert_eq!(init, arr![i32; 1, 2, 3]); - /// assert_eq!(last, 4); - /// ``` - fn pop_back(self) -> (Self::Shorter, T); - - /// Returns a new array without the first element, and the first element. - /// Example: - /// - /// ```ignore - /// let a = arr![i32; 1, 2, 3, 4]; - /// - /// let (head, tail) = a.pop_front(); - /// - /// assert_eq!(head, 1); - /// assert_eq!(tail, arr![i32; 2, 3, 4]); - /// ``` - fn pop_front(self) -> (T, Self::Shorter); -} - -unsafe impl> Lengthen for GenericArray -where - N: Add, - Add1: ArrayLength, - Add1: Sub, - Sub1>: ArrayLength, -{ - type Longer = GenericArray>; - - fn append(self, last: T) -> Self::Longer { - let mut longer: Self::Longer = unsafe { mem::uninitialized() }; - - unsafe { - ptr::write(longer.as_mut_ptr() as *mut _, self); - ptr::write(&mut longer[N::to_usize()], last); - } - - longer - } - - fn prepend(self, first: T) -> Self::Longer { - let mut longer: Self::Longer = unsafe { mem::uninitialized() }; - - let longer_ptr = longer.as_mut_ptr(); - - unsafe { - ptr::write(longer_ptr as *mut _, first); - ptr::write(longer_ptr.offset(1) as *mut _, self); - } - - longer - } -} - -unsafe impl> Shorten for GenericArray -where - N: Sub, - Sub1: ArrayLength, - Sub1: Add, - Add1>: ArrayLength, -{ - type Shorter = GenericArray>; - - fn pop_back(self) -> (Self::Shorter, T) { - let init_ptr = self.as_ptr(); - let last_ptr = unsafe { init_ptr.offset(Sub1::::to_usize() as isize) }; - - let init = unsafe { ptr::read(init_ptr as _) }; - let last = unsafe { ptr::read(last_ptr as _) }; - - mem::forget(self); - - (init, last) - } - - fn pop_front(self) -> (T, Self::Shorter) { - let head_ptr = self.as_ptr(); - let tail_ptr = unsafe { head_ptr.offset(1) }; - - let head = unsafe { ptr::read(head_ptr as _) }; - let tail = unsafe { ptr::read(tail_ptr as _) }; - - mem::forget(self); - - (head, tail) - } -} - -/// Defines a `GenericSequence` that can be split into two parts at a given pivot index. -pub unsafe trait Split: GenericSequence -where - K: ArrayLength, -{ - /// First part of the resulting split array - type First: GenericSequence; - /// Second part of the resulting split array - type Second: GenericSequence; - - /// Splits an array at the given index, returning the separate parts of the array. - fn split(self) -> (Self::First, Self::Second); -} - -unsafe impl Split for GenericArray -where - N: ArrayLength, - K: ArrayLength, - N: Sub, - Diff: ArrayLength, -{ - type First = GenericArray; - type Second = GenericArray>; - - fn split(self) -> (Self::First, Self::Second) { - let head_ptr = self.as_ptr(); - let tail_ptr = unsafe { head_ptr.offset(K::to_usize() as isize) }; - - let head = unsafe { ptr::read(head_ptr as _) }; - let tail = unsafe { ptr::read(tail_ptr as _) }; - - mem::forget(self); - - (head, tail) - } -} - -/// Defines `GenericSequence`s which can be joined together, forming a larger array. -pub unsafe trait Concat: GenericSequence -where - M: ArrayLength, -{ - /// Sequence to be concatenated with `self` - type Rest: GenericSequence; - - /// Resulting sequence formed by the concatenation. - type Output: GenericSequence; - - /// Concatenate, or join, two sequences. - fn concat(self, rest: Self::Rest) -> Self::Output; -} - -unsafe impl Concat for GenericArray -where - N: ArrayLength + Add, - M: ArrayLength, - Sum: ArrayLength, -{ - type Rest = GenericArray; - type Output = GenericArray>; - - fn concat(self, rest: Self::Rest) -> Self::Output { - let mut output: Self::Output = unsafe { mem::uninitialized() }; - - let output_ptr = output.as_mut_ptr(); - - unsafe { - ptr::write(output_ptr as *mut _, self); - ptr::write(output_ptr.offset(N::to_usize() as isize) as *mut _, rest); - } - - output - } -} diff --git a/vendor/generic-array-0.12.4/tests/arr.rs b/vendor/generic-array-0.12.4/tests/arr.rs deleted file mode 100644 index c37b5d50f..000000000 --- a/vendor/generic-array-0.12.4/tests/arr.rs +++ /dev/null @@ -1,27 +0,0 @@ -#[macro_use] -extern crate generic_array; -extern crate typenum; - -#[test] -fn empty_without_trailing_comma() { - let ar = arr![u8; ]; - assert_eq!(format!("{:x}", ar), ""); -} - -#[test] -fn empty_with_trailing_comma() { - let ar = arr![u8; , ]; - assert_eq!(format!("{:x}", ar), ""); -} - -#[test] -fn without_trailing_comma() { - let ar = arr![u8; 10, 20, 30]; - assert_eq!(format!("{:x}", ar), "0a141e"); -} - -#[test] -fn with_trailing_comma() { - let ar = arr![u8; 10, 20, 30, ]; - assert_eq!(format!("{:x}", ar), "0a141e"); -} diff --git a/vendor/generic-array-0.12.4/tests/generics.rs b/vendor/generic-array-0.12.4/tests/generics.rs deleted file mode 100644 index d48fe08c0..000000000 --- a/vendor/generic-array-0.12.4/tests/generics.rs +++ /dev/null @@ -1,98 +0,0 @@ -#![recursion_limit = "128"] - -#[macro_use] -extern crate generic_array; - -use generic_array::typenum::consts::U4; - -use std::fmt::Debug; -use std::ops::Add; - -use generic_array::{GenericArray, ArrayLength}; -use generic_array::sequence::*; -use generic_array::functional::*; - -/// Example function using generics to pass N-length sequences and map them -pub fn generic_map(s: S) -where - S: FunctionalSequence, // `.map` - S::Item: Add, // `x + 1` - S: MappedGenericSequence, // `i32` -> `i32` - MappedSequence: Debug, // println! -{ - let a = s.map(|x| x + 1); - - println!("{:?}", a); -} - -/// Complex example function using generics to pass N-length sequences, zip them, and then map that result. -/// -/// If used with `GenericArray` specifically this isn't necessary -pub fn generic_sequence_zip_sum(a: A, b: B) -> i32 -where - A: FunctionalSequence, // `.zip` - B: FunctionalSequence, // `.zip` - A: MappedGenericSequence, // `i32` -> `i32` - B: MappedGenericSequence>, // `i32` -> `i32`, prove A and B can map to the same output - A::Item: Add, // `l + r` - MappedSequence: MappedGenericSequence + FunctionalSequence, // `.map` - SequenceItem>: Add, // `x + 1` - MappedSequence, i32, i32>: Debug, // `println!` - MappedSequence, i32, i32>: FunctionalSequence, // `.fold` - SequenceItem, i32, i32>>: Add // `x + a`, note the order -{ - let c = a.zip(b, |l, r| l + r).map(|x| x + 1); - - println!("{:?}", c); - - c.fold(0, |a, x| x + a) -} - -/// Super-simple fixed-length i32 `GenericArray`s -pub fn generic_array_plain_zip_sum(a: GenericArray, b: GenericArray) -> i32 { - a.zip(b, |l, r| l + r).map(|x| x + 1).fold(0, |a, x| x + a) -} - -pub fn generic_array_variable_length_zip_sum(a: GenericArray, b: GenericArray) -> i32 -where - N: ArrayLength, -{ - a.zip(b, |l, r| l + r).map(|x| x + 1).fold(0, |a, x| x + a) -} - -pub fn generic_array_same_type_variable_length_zip_sum(a: GenericArray, b: GenericArray) -> i32 -where - N: ArrayLength + ArrayLength<>::Output>, - T: Add, -{ - a.zip(b, |l, r| l + r).map(|x| x + 1).fold(0, |a, x| x + a) -} - -/// Complex example using fully generic `GenericArray`s with the same length. -/// -/// It's mostly just the repeated `Add` traits, which would be present in other systems anyway. -pub fn generic_array_zip_sum + ArrayLength>(a: GenericArray, b: GenericArray) -> i32 -where - A: Add, - N: ArrayLength<>::Output> + - ArrayLength<<>::Output as Add>::Output>, - >::Output: Add, - <>::Output as Add>::Output: Add, -{ - a.zip(b, |l, r| l + r).map(|x| x + 1).fold(0, |a, x| x + a) -} - -#[test] -fn test_generics() { - generic_map(arr![i32; 1, 2, 3, 4]); - - assert_eq!(generic_sequence_zip_sum(arr![i32; 1, 2, 3, 4], arr![i32; 2, 3, 4, 5]), 28); - - assert_eq!(generic_array_plain_zip_sum(arr![i32; 1, 2, 3, 4], arr![i32; 2, 3, 4, 5]), 28); - - assert_eq!(generic_array_variable_length_zip_sum(arr![i32; 1, 2, 3, 4], arr![i32; 2, 3, 4, 5]), 28); - - assert_eq!(generic_array_same_type_variable_length_zip_sum(arr![i32; 1, 2, 3, 4], arr![i32; 2, 3, 4, 5]), 28); - - assert_eq!(generic_array_zip_sum(arr![i32; 1, 2, 3, 4], arr![i32; 2, 3, 4, 5]), 28); -} \ No newline at end of file diff --git a/vendor/generic-array-0.12.4/tests/hex.rs b/vendor/generic-array-0.12.4/tests/hex.rs deleted file mode 100644 index 0882e9bb3..000000000 --- a/vendor/generic-array-0.12.4/tests/hex.rs +++ /dev/null @@ -1,61 +0,0 @@ -#[macro_use] -extern crate generic_array; -extern crate typenum; - -use generic_array::GenericArray; -use std::str::from_utf8; -use typenum::U2048; - -#[test] -fn short_lower_hex() { - let ar = arr![u8; 10, 20, 30]; - assert_eq!(format!("{:x}", ar), "0a141e"); -} - -#[test] -fn short_upper_hex() { - let ar = arr![u8; 30, 20, 10]; - assert_eq!(format!("{:X}", ar), "1E140A"); -} - -#[test] -fn long_lower_hex() { - let ar = GenericArray::::default(); - assert_eq!(format!("{:x}", ar), from_utf8(&[b'0'; 4096]).unwrap()); -} - -#[test] -fn long_lower_hex_truncated() { - let ar = GenericArray::::default(); - assert_eq!(format!("{:.3001x}", ar), from_utf8(&[b'0'; 3001]).unwrap()); -} - -#[test] -fn long_upper_hex() { - let ar = GenericArray::::default(); - assert_eq!(format!("{:X}", ar), from_utf8(&[b'0'; 4096]).unwrap()); -} - -#[test] -fn long_upper_hex_truncated() { - let ar = GenericArray::::default(); - assert_eq!(format!("{:.2777X}", ar), from_utf8(&[b'0'; 2777]).unwrap()); -} - -#[test] -fn truncated_lower_hex() { - let ar = arr![u8; 10, 20, 30, 40, 50]; - assert_eq!(format!("{:.2x}", ar), "0a"); - assert_eq!(format!("{:.3x}", ar), "0a1"); - assert_eq!(format!("{:.4x}", ar), "0a14"); -} - -#[test] -fn truncated_upper_hex() { - let ar = arr![u8; 30, 20, 10, 17, 0]; - assert_eq!(format!("{:.4X}", ar), "1E14"); - assert_eq!(format!("{:.5X}", ar), "1E140"); - assert_eq!(format!("{:.6X}", ar), "1E140A"); - assert_eq!(format!("{:.7X}", ar), "1E140A1"); - assert_eq!(format!("{:.8X}", ar), "1E140A11"); -} diff --git a/vendor/generic-array-0.12.4/tests/import_name.rs b/vendor/generic-array-0.12.4/tests/import_name.rs deleted file mode 100644 index 27653c9a8..000000000 --- a/vendor/generic-array-0.12.4/tests/import_name.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[macro_use] -extern crate generic_array as gen_arr; - -use gen_arr::typenum; - -#[test] -fn test_different_crate_name() { - let _: gen_arr::GenericArray = arr![u32; 0, 1, 2, 3]; - let _: gen_arr::GenericArray = arr![u32;]; -} diff --git a/vendor/generic-array-0.12.4/tests/iter.rs b/vendor/generic-array-0.12.4/tests/iter.rs deleted file mode 100644 index 47860d728..000000000 --- a/vendor/generic-array-0.12.4/tests/iter.rs +++ /dev/null @@ -1,164 +0,0 @@ -#[macro_use] -extern crate generic_array; - -use std::cell::Cell; -use std::ops::Drop; - -use generic_array::GenericArray; -use generic_array::typenum::consts::U5; - -#[test] -fn test_into_iter_as_slice() { - let array = arr![char; 'a', 'b', 'c']; - let mut into_iter = array.into_iter(); - assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); - let _ = into_iter.next().unwrap(); - assert_eq!(into_iter.as_slice(), &['b', 'c']); - let _ = into_iter.next().unwrap(); - let _ = into_iter.next().unwrap(); - assert_eq!(into_iter.as_slice(), &[]); -} - -#[test] -fn test_into_iter_as_mut_slice() { - let array = arr![char; 'a', 'b', 'c']; - let mut into_iter = array.into_iter(); - assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); - into_iter.as_mut_slice()[0] = 'x'; - into_iter.as_mut_slice()[1] = 'y'; - assert_eq!(into_iter.next().unwrap(), 'x'); - assert_eq!(into_iter.as_slice(), &['y', 'c']); -} - -#[test] -fn test_into_iter_debug() { - let array = arr![char; 'a', 'b', 'c']; - let into_iter = array.into_iter(); - let debug = format!("{:?}", into_iter); - assert_eq!(debug, "GenericArrayIter(['a', 'b', 'c'])"); -} - -#[test] -fn test_into_iter_clone() { - fn iter_equal>(it: I, slice: &[i32]) { - let v: Vec = it.collect(); - assert_eq!(&v[..], slice); - } - let mut it = arr![i32; 1, 2, 3].into_iter(); - iter_equal(it.clone(), &[1, 2, 3]); - assert_eq!(it.next(), Some(1)); - let mut it = it.rev(); - iter_equal(it.clone(), &[3, 2]); - assert_eq!(it.next(), Some(3)); - iter_equal(it.clone(), &[2]); - assert_eq!(it.next(), Some(2)); - iter_equal(it.clone(), &[]); - assert_eq!(it.next(), None); -} - -#[test] -fn test_into_iter_nth() { - let v = arr![i32; 0, 1, 2, 3, 4]; - for i in 0..v.len() { - assert_eq!(v.clone().into_iter().nth(i).unwrap(), v[i]); - } - assert_eq!(v.clone().into_iter().nth(v.len()), None); - - let mut iter = v.into_iter(); - assert_eq!(iter.nth(2).unwrap(), v[2]); - assert_eq!(iter.nth(1).unwrap(), v[4]); -} - -#[test] -fn test_into_iter_last() { - let v = arr![i32; 0, 1, 2, 3, 4]; - assert_eq!(v.into_iter().last().unwrap(), 4); - assert_eq!(arr![i32; 0].into_iter().last().unwrap(), 0); -} - -#[test] -fn test_into_iter_count() { - let v = arr![i32; 0, 1, 2, 3, 4]; - assert_eq!(v.clone().into_iter().count(), 5); - - let mut iter2 = v.into_iter(); - iter2.next(); - iter2.next(); - assert_eq!(iter2.count(), 3); -} - -#[test] -fn test_into_iter_flat_map() { - assert!((0..5).flat_map(|i| arr![i32; 2 * i, 2 * i + 1]).eq(0..10)); -} - -#[test] -fn test_into_iter_drops() { - struct R<'a> { - i: &'a Cell, - } - - impl<'a> Drop for R<'a> { - fn drop(&mut self) { - self.i.set(self.i.get() + 1); - } - } - - fn r(i: &Cell) -> R { - R { - i: i - } - } - - fn v(i: &Cell) -> GenericArray { - arr![R; r(i), r(i), r(i), r(i), r(i)] - } - - let i = Cell::new(0); - { - v(&i).into_iter(); - } - assert_eq!(i.get(), 5); - - let i = Cell::new(0); - { - let mut iter = v(&i).into_iter(); - let _x = iter.next(); - assert_eq!(i.get(), 0); - assert_eq!(iter.count(), 4); - assert_eq!(i.get(), 4); - } - assert_eq!(i.get(), 5); - - let i = Cell::new(0); - { - let mut iter = v(&i).into_iter(); - let _x = iter.nth(2); - assert_eq!(i.get(), 2); - let _y = iter.last(); - assert_eq!(i.get(), 3); - } - assert_eq!(i.get(), 5); - - let i = Cell::new(0); - for (index, _x) in v(&i).into_iter().enumerate() { - assert_eq!(i.get(), index); - } - assert_eq!(i.get(), 5); - - let i = Cell::new(0); - for (index, _x) in v(&i).into_iter().rev().enumerate() { - assert_eq!(i.get(), index); - } - assert_eq!(i.get(), 5); -} - -/* -//TODO: Cover this -#[allow(dead_code)] -fn assert_covariance() { - fn into_iter<'new>(i: GenericArrayIter<&'static str, U10>) -> GenericArrayIter<&'new str, U10> { - i - } -} -*/ \ No newline at end of file diff --git a/vendor/generic-array-0.12.4/tests/mod.rs b/vendor/generic-array-0.12.4/tests/mod.rs deleted file mode 100644 index 6c6d9eb49..000000000 --- a/vendor/generic-array-0.12.4/tests/mod.rs +++ /dev/null @@ -1,287 +0,0 @@ -#![recursion_limit = "128"] -#![no_std] -#[macro_use] -extern crate generic_array; -use core::cell::Cell; -use core::ops::{Add, Drop}; -use generic_array::GenericArray; -use generic_array::functional::*; -use generic_array::sequence::*; -use generic_array::typenum::{U1, U3, U4, U97}; - -#[test] -fn test() { - let mut list97 = [0; 97]; - for i in 0..97 { - list97[i] = i as i32; - } - let l: GenericArray = GenericArray::clone_from_slice(&list97); - assert_eq!(l[0], 0); - assert_eq!(l[1], 1); - assert_eq!(l[32], 32); - assert_eq!(l[56], 56); -} - -#[test] -fn test_drop() { - #[derive(Clone)] - struct TestDrop<'a>(&'a Cell); - - impl<'a> Drop for TestDrop<'a> { - fn drop(&mut self) { - self.0.set(self.0.get() + 1); - } - } - - let drop_counter = Cell::new(0); - { - let _: GenericArray = arr![TestDrop; TestDrop(&drop_counter), - TestDrop(&drop_counter), - TestDrop(&drop_counter)]; - } - assert_eq!(drop_counter.get(), 3); -} - -#[test] -fn test_arr() { - let test: GenericArray = arr![u32; 1, 2, 3]; - assert_eq!(test[1], 2); -} - -#[test] -fn test_copy() { - let test = arr![u32; 1, 2, 3]; - let test2 = test; - // if GenericArray is not copy, this should fail as a use of a moved value - assert_eq!(test[1], 2); - assert_eq!(test2[0], 1); -} - -#[derive(Debug, PartialEq, Eq)] -struct NoClone(T); - -#[test] -fn test_from_slice() { - let arr = [1, 2, 3, 4]; - let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]); - assert_eq!(&arr[..3], gen_arr.as_slice()); - let arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)]; - let gen_arr = GenericArray::<_, U3>::from_slice(&arr[..3]); - assert_eq!(&arr[..3], gen_arr.as_slice()); -} - -#[test] -fn test_from_mut_slice() { - let mut arr = [1, 2, 3, 4]; - { - let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]); - gen_arr[2] = 10; - } - assert_eq!(arr, [1, 2, 10, 4]); - let mut arr = [NoClone(1u32), NoClone(2), NoClone(3), NoClone(4)]; - { - let gen_arr = GenericArray::<_, U3>::from_mut_slice(&mut arr[..3]); - gen_arr[2] = NoClone(10); - } - assert_eq!(arr, [NoClone(1), NoClone(2), NoClone(10), NoClone(4)]); -} - -#[test] -fn test_default() { - let arr = GenericArray::::default(); - assert_eq!(arr[0], 0); -} - -#[test] -fn test_from() { - let data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]; - let garray: GenericArray<(usize, usize, usize), U3> = data.into(); - assert_eq!(&data, garray.as_slice()); -} - -#[test] -fn test_unit_macro() { - let arr = arr![f32; 3.14]; - assert_eq!(arr[0], 3.14); -} - -#[test] -fn test_empty_macro() { - let _arr = arr![f32;]; -} - -#[test] -fn test_cmp() { - arr![u8; 0x00].cmp(&arr![u8; 0x00]); -} - -/// This test should cause a helpful compile error if uncommented. -// #[test] -// fn test_empty_macro2(){ -// let arr = arr![]; -// } -#[cfg(feature = "serde")] -mod impl_serde { - extern crate serde_json; - - use generic_array::GenericArray; - use generic_array::typenum::U6; - - #[test] - fn test_serde_implementation() { - let array: GenericArray = arr![f64; 0.0, 5.0, 3.0, 7.07192, 76.0, -9.0]; - let string = serde_json::to_string(&array).unwrap(); - assert_eq!(string, "[0.0,5.0,3.0,7.07192,76.0,-9.0]"); - - let test_array: GenericArray = serde_json::from_str(&string).unwrap(); - assert_eq!(test_array, array); - } -} - -#[test] -fn test_map() { - let b: GenericArray = GenericArray::generate(|i| i as i32 * 4).map(|x| x - 3); - - assert_eq!(b, arr![i32; -3, 1, 5, 9]); -} - -#[test] -fn test_zip() { - let a: GenericArray<_, U4> = GenericArray::generate(|i| i + 1); - let b: GenericArray<_, U4> = GenericArray::generate(|i| i as i32 * 4); - - // Uses reference and non-reference arguments - let c = (&a).zip(b, |r, l| *r as i32 + l); - - assert_eq!(c, arr![i32; 1, 6, 11, 16]); -} - -#[test] -#[should_panic] -fn test_from_iter_short() { - use core::iter::repeat; - - let a: GenericArray<_, U4> = repeat(11).take(3).collect(); - - assert_eq!(a, arr![i32; 11, 11, 11, 0]); -} - -#[test] -fn test_from_iter() { - use core::iter::{once, repeat}; - - let a: GenericArray<_, U4> = repeat(11).take(3).chain(once(0)).collect(); - - assert_eq!(a, arr![i32; 11, 11, 11, 0]); -} - -#[test] -fn test_sizes() { - #![allow(dead_code)] - use core::mem::{size_of, size_of_val}; - - #[derive(Debug, Copy, Clone)] - #[repr(C)] - #[repr(packed)] - struct Test { - t: u16, - s: u32, - r: u16, - f: u16, - o: u32, - } - - assert_eq!(size_of::(), 14); - - assert_eq!(size_of_val(&arr![u8; 1, 2, 3]), size_of::() * 3); - assert_eq!(size_of_val(&arr![u32; 1]), size_of::() * 1); - assert_eq!(size_of_val(&arr![u64; 1, 2, 3, 4]), size_of::() * 4); - - assert_eq!(size_of::>(), size_of::() * 97); -} - -#[test] -fn test_append() { - let a = arr![i32; 1, 2, 3]; - - let b = a.append(4); - - assert_eq!(b, arr![i32; 1, 2, 3, 4]); -} - -#[test] -fn test_prepend() { - let a = arr![i32; 1, 2, 3]; - - let b = a.prepend(4); - - assert_eq!(b, arr![i32; 4, 1, 2, 3]); -} - -#[test] -fn test_pop() { - let a = arr![i32; 1, 2, 3, 4]; - - let (init, last) = a.pop_back(); - - assert_eq!(init, arr![i32; 1, 2, 3]); - assert_eq!(last, 4); - - let (head, tail) = a.pop_front(); - - assert_eq!(head, 1); - assert_eq!(tail, arr![i32; 2, 3, 4]); -} - -#[test] -fn test_split() { - let a = arr![i32; 1, 2, 3, 4]; - - let (b, c) = a.split(); - - assert_eq!(b, arr![i32; 1]); - assert_eq!(c, arr![i32; 2, 3, 4]); - - let (e, f) = a.split(); - - assert_eq!(e, arr![i32; 1, 2]); - assert_eq!(f, arr![i32; 3, 4]); -} - -#[test] -fn test_concat() { - let a = arr![i32; 1, 2]; - let b = arr![i32; 3, 4]; - - let c = a.concat(b); - - assert_eq!(c, arr![i32; 1, 2, 3, 4]); - - let (d, e) = c.split(); - - assert_eq!(d, arr![i32; 1]); - assert_eq!(e, arr![i32; 2, 3, 4]); -} - -#[test] -fn test_fold() { - let a = arr![i32; 1, 2, 3, 4]; - - assert_eq!(10, a.fold(0, |a, x| a + x)); -} - -fn sum_generic(s: S) -> i32 -where - S: FunctionalSequence, - S::Item: Add, // `+` - i32: Add, // reflexive -{ - s.fold(0, |a, x| a + x) -} - -#[test] -fn test_sum() { - let a = sum_generic(arr![i32; 1, 2, 3, 4]); - - assert_eq!(a, 10); -} diff --git a/vendor/getrandom/.cargo-checksum.json b/vendor/getrandom/.cargo-checksum.json index 7bdcc1bc4..adfe6c9e5 100644 --- a/vendor/getrandom/.cargo-checksum.json +++ b/vendor/getrandom/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"e972a70c9a4729acbd6bd81ca0c3e03944cab242743b308d124d64b3552f8e63","Cargo.toml":"66283df4cc6406f65b46dded3469d23f9d1c6372a0385af8cdcde9da1b6cf5d9","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d2ee195acd80c7d1364a369ad0d2dad46f5f9f973f9d3960367413fd87acfcd6","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"28f3f7ac4f093dfb6cd2c8e7e0714f16d0f03f8c658e56caa8fe9bd03b1ff39b","src/error.rs":"110ffe8a2c6b0fa46a4e317e837efe617b343f250fedac61bcabc3c5250e7432","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"674af2d277b66ecf2e49e1059638abd58db089df095b8b65d9e347782e4bb1e0","src/linux_android.rs":"39cb80999c8534145240a350976d261b8924436bf9a4563960c7bd8c2c83c773","src/macos.rs":"b692f2fcc2319a5195f47751d5bd7dd87c7c24a61d14fa4e3dbc992ae66212b7","src/openbsd.rs":"066b2dd395c190444a658bb0b52a052eabbd68ea5a534fb729c7e5373abc0a6a","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"9c7004446fabe5a7a21c73d5a65d7e2115b5bd1d1dbb735c984cab3dba239785","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"9fd636b23121a86630f0c7891a310444f5b1bb29b0013290e130b79ed1e1f79e","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"02b3a75613dc80444847675ecfea59f390c2597ce1d3334612a8dba71f6082de","src/windows.rs":"e3c8f033d5d2a6b8abc5c92b005232f5aca8ce941bd94964a0f58f2436af9990","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"} \ No newline at end of file +{"files":{"CHANGELOG.md":"1289f7318d266dca92eceb373c5ff6ee81fa867a6f180ad57759d37df9fcad91","Cargo.toml":"2b0b1b62739f57c58e5069f90b70003f56f3242517d14ac1f875b9f36d227e6e","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"209fbbe0ad52d9235e37badf9cadfe4dbdc87203179c0899e738b39ade42177b","README.md":"7ae74633326a22fd6298d7f209fb14884277bd98049795f444945acbb2b0dfbd","benches/mod.rs":"5495735ff210a50cab23c2cc84191ed910af7c30395a3d9d6095b722765b3864","src/3ds.rs":"0f48fc15f89b518fb92e06aaa4838b62dc073598e8f288df56ad1e5a9251af1e","src/bsd_arandom.rs":"d90c419d4def20f83e7535cd3f5ec07035045011a50c3652951d196a120c5d3e","src/custom.rs":"b363ee77664203d141985402433afd6808b72cc50bff586b3034d303eccfc281","src/dragonfly.rs":"47f933eac189f6ea48ecf021efd0747ebce1b43d1bece6bbf72a951bab705987","src/error.rs":"f87ce17f9299f9b59b47306dab25ed01d720a0ba53363f52b46b50e2f5e49e36","src/error_impls.rs":"9c34832ebb99cd5e31bc5c8ffc5beb5b3fa6f7ff0226aaa1cdf8e10e6d64b324","src/espidf.rs":"19f101486584fde6dad962f4d9792de168658047312106641a5caf6866a5bbcf","src/fuchsia.rs":"470d8509deb5b06fa6417f294c0a49e0e35a580249a5d8944c3be5aa746f64ea","src/ios.rs":"4bad4f5c096a50338b86aeac91a937c18bc55b9555e6f34806ad13732e64523d","src/js.rs":"04c750491ba3bcdad3609265938410ee09928c5d6dfd0d33d826a9884d13ac4c","src/lib.rs":"6f61a660fe35864a2fc8ed2fe29b1c2ddf5d29854a2871daade66f0059f65b8e","src/linux_android.rs":"ec24575aa4ae71b6991290dadfdea931b05397c3faababf24bd794f1a9624835","src/macos.rs":"6c09827ad5292cd022e063efa79523bfdb50ed08b9867ebaa007cd321b8d218e","src/openbsd.rs":"450a23ead462d4a840fee4aa0bfdab1e3d88c8f48e4bb608d457429ddeca69c0","src/rdrand.rs":"79d23183b1905d61bd9df9729dc798505a2ed750d3339e342ab144e1709827e4","src/solaris_illumos.rs":"d52fee9dd7d661f960c01894edd563c1ff8a512c111f7803092d9aa2ff98718e","src/solid.rs":"997035d54c9762d22a5a14f54e7fbed4dd266cdeacbdf6aab7d8aee05537e8ba","src/use_file.rs":"16e42eb0a56e375c330c1ca8eb58c444e82ef3ad35230b961fdba96a02a68804","src/util.rs":"da6964dc1523f1cb8d26365fa6a8ece46360587e6974931624b271f0c72cda8b","src/util_libc.rs":"2a63ac0e6dab16b85c4728b79a16e0640301e8b876f151b0a1db0b4394fa219f","src/vxworks.rs":"a5aa0e40f890e0f35626458bb656a3340b8af3111e4bacd2e12505a8d50a3505","src/wasi.rs":"dfdd0a870581948bd03abe64d49ca4295d9cfa26e09b97a526fd5e17148ad9ca","src/windows.rs":"d0b4f2afd1959660aa9abcd9477764bd7dc0b7d7048aee748804b37963c77c6f","tests/common/mod.rs":"b6beee8f535d2d094a65711fe0af91a6fc220aa09729ed7269fe33cafdc9177f","tests/custom.rs":"9f2c0193193f6bcf641116ca0b3653b33d2015e0e98ce107ee1d1f60c5eeae3a","tests/normal.rs":"9e1c4b1e468a09ed0225370dfb6608f8b8135e0fabb09bbc1a718105164aade6","tests/rdrand.rs":"4474ccebf9d33c89288862a7e367018405968dddc55c7c6f97e21b5fe2264601"},"package":"4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"} \ No newline at end of file diff --git a/vendor/getrandom/CHANGELOG.md b/vendor/getrandom/CHANGELOG.md index 4ab267ae0..b25704947 100644 --- a/vendor/getrandom/CHANGELOG.md +++ b/vendor/getrandom/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.7] - 2022-06-14 +### Changed +- Update `wasi` dependency to `0.11` [#253] + +### Fixed +- Use `AtomicPtr` instead of `AtomicUsize` for Strict Provenance compatibility. [#263] + +### Documentation +- Add comments explaining use of fallback mechanisms [#257] [#260] + +[#263]: https://github.com/rust-random/getrandom/pull/263 +[#260]: https://github.com/rust-random/getrandom/pull/260 +[#253]: https://github.com/rust-random/getrandom/pull/253 +[#257]: https://github.com/rust-random/getrandom/pull/257 + ## [0.2.6] - 2022-03-28 ### Added - Nintendo 3DS (`armv6k-nintendo-3ds`) support [#248] @@ -291,7 +306,8 @@ Publish initial implementation. ## [0.0.0] - 2019-01-19 Publish an empty template library. -[0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 +[0.2.7]: https://github.com/rust-random/getrandom/compare/v0.2.6...v0.2.7 +[0.2.6]: https://github.com/rust-random/getrandom/compare/v0.2.5...v0.2.6 [0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.4...v0.2.5 [0.2.4]: https://github.com/rust-random/getrandom/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/rust-random/getrandom/compare/v0.2.2...v0.2.3 diff --git a/vendor/getrandom/Cargo.toml b/vendor/getrandom/Cargo.toml index 0a664244e..9b9c0880a 100644 --- a/vendor/getrandom/Cargo.toml +++ b/vendor/getrandom/Cargo.toml @@ -12,17 +12,29 @@ [package] edition = "2018" name = "getrandom" -version = "0.2.6" +version = "0.2.7" authors = ["The Rand Project Developers"] exclude = [".*"] description = "A small cross-platform library for retrieving random data from system source" documentation = "https://docs.rs/getrandom" -categories = ["os", "no-std"] +readme = "README.md" +categories = [ + "os", + "no-std", +] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-random/getrandom" + [package.metadata.docs.rs] -features = ["std", "custom"] -rustdoc-args = ["--cfg", "docsrs"] +features = [ + "std", + "custom", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] + [dependencies.cfg-if] version = "1" @@ -37,11 +49,20 @@ package = "rustc-std-workspace-core" [features] custom = [] -js = ["wasm-bindgen", "js-sys"] +js = [ + "wasm-bindgen", + "js-sys", +] rdrand = [] -rustc-dep-of-std = ["compiler_builtins", "core", "libc/rustc-dep-of-std", "wasi/rustc-dep-of-std"] +rustc-dep-of-std = [ + "compiler_builtins", + "core", + "libc/rustc-dep-of-std", + "wasi/rustc-dep-of-std", +] std = [] test-in-browser = [] + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3" optional = true @@ -50,10 +71,13 @@ optional = true version = "0.2.62" optional = true default-features = false + [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dev-dependencies.wasm-bindgen-test] version = "0.3.18" + [target."cfg(target_os = \"wasi\")".dependencies.wasi] -version = "0.10" +version = "0.11" + [target."cfg(unix)".dependencies.libc] version = "0.2.120" default-features = false diff --git a/vendor/getrandom/src/bsd_arandom.rs b/vendor/getrandom/src/bsd_arandom.rs index f26f2609c..d44121254 100644 --- a/vendor/getrandom/src/bsd_arandom.rs +++ b/vendor/getrandom/src/bsd_arandom.rs @@ -31,6 +31,7 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { } pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 #[cfg(target_os = "freebsd")] { use crate::util_libc::Weak; diff --git a/vendor/getrandom/src/dragonfly.rs b/vendor/getrandom/src/dragonfly.rs index f27e90690..8daaa4048 100644 --- a/vendor/getrandom/src/dragonfly.rs +++ b/vendor/getrandom/src/dragonfly.rs @@ -17,6 +17,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; + // getrandom(2) was introduced in DragonflyBSD 5.7 if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); diff --git a/vendor/getrandom/src/error.rs b/vendor/getrandom/src/error.rs index 661575376..b5ab2bb18 100644 --- a/vendor/getrandom/src/error.rs +++ b/vendor/getrandom/src/error.rs @@ -109,10 +109,6 @@ cfg_if! { let idx = buf.iter().position(|&b| b == 0).unwrap_or(n); core::str::from_utf8(&buf[..idx]).ok() } - } else if #[cfg(target_os = "wasi")] { - fn os_err(errno: i32, _buf: &mut [u8]) -> Option { - wasi::Error::from_raw_error(errno as _) - } } else { fn os_err(_errno: i32, _buf: &mut [u8]) -> Option<&str> { None diff --git a/vendor/getrandom/src/lib.rs b/vendor/getrandom/src/lib.rs index 888b9a510..c62056e55 100644 --- a/vendor/getrandom/src/lib.rs +++ b/vendor/getrandom/src/lib.rs @@ -149,7 +149,7 @@ #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getrandom/0.2.6" + html_root_url = "https://docs.rs/getrandom/0.2.7" )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] diff --git a/vendor/getrandom/src/linux_android.rs b/vendor/getrandom/src/linux_android.rs index 5508fdd06..4270b67c6 100644 --- a/vendor/getrandom/src/linux_android.rs +++ b/vendor/getrandom/src/linux_android.rs @@ -14,6 +14,7 @@ use crate::{ }; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Linux 3.17 static HAS_GETRANDOM: LazyBool = LazyBool::new(); if HAS_GETRANDOM.unsync_init(is_getrandom_available) { sys_fill_exact(dest, |buf| unsafe { diff --git a/vendor/getrandom/src/macos.rs b/vendor/getrandom/src/macos.rs index 585a35abd..671a053bf 100644 --- a/vendor/getrandom/src/macos.rs +++ b/vendor/getrandom/src/macos.rs @@ -17,6 +17,7 @@ use core::mem; type GetEntropyFn = unsafe extern "C" fn(*mut u8, libc::size_t) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in 10.12, Rust supports 10.7+ static GETENTROPY: Weak = unsafe { Weak::new("getentropy\0") }; if let Some(fptr) = GETENTROPY.ptr() { let func: GetEntropyFn = unsafe { mem::transmute(fptr) }; diff --git a/vendor/getrandom/src/openbsd.rs b/vendor/getrandom/src/openbsd.rs index c8d28b3d8..41371736f 100644 --- a/vendor/getrandom/src/openbsd.rs +++ b/vendor/getrandom/src/openbsd.rs @@ -10,6 +10,7 @@ use crate::{util_libc::last_os_error, Error}; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getentropy(2) was added in OpenBSD 5.6, so we can use it unconditionally. for chunk in dest.chunks_mut(256) { let ret = unsafe { libc::getentropy(chunk.as_mut_ptr() as *mut libc::c_void, chunk.len()) }; if ret == -1 { diff --git a/vendor/getrandom/src/solaris_illumos.rs b/vendor/getrandom/src/solaris_illumos.rs index 2d1b767bb..cf3067d6d 100644 --- a/vendor/getrandom/src/solaris_illumos.rs +++ b/vendor/getrandom/src/solaris_illumos.rs @@ -30,6 +30,7 @@ type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { + // getrandom(2) was introduced in Solaris 11.3 for Illumos in 2015. static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; if let Some(fptr) = GETRANDOM.ptr() { let func: GetRandomFn = unsafe { mem::transmute(fptr) }; diff --git a/vendor/getrandom/src/util_libc.rs b/vendor/getrandom/src/util_libc.rs index 6df1cd7da..d057071a7 100644 --- a/vendor/getrandom/src/util_libc.rs +++ b/vendor/getrandom/src/util_libc.rs @@ -6,8 +6,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] -use crate::{util::LazyUsize, Error}; -use core::{num::NonZeroU32, ptr::NonNull}; +use crate::Error; +use core::{ + num::NonZeroU32, + ptr::NonNull, + sync::atomic::{fence, AtomicPtr, Ordering}, +}; +use libc::c_void; cfg_if! { if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] { @@ -76,29 +81,57 @@ pub fn sys_fill_exact( // A "weak" binding to a C function that may or may not be present at runtime. // Used for supporting newer OS features while still building on older systems. -// F must be a function pointer of type `unsafe extern "C" fn`. Based off of the -// weak! macro in libstd. +// Based off of the DlsymWeak struct in libstd: +// https://github.com/rust-lang/rust/blob/1.61.0/library/std/src/sys/unix/weak.rs#L84 +// except that the caller must manually cast self.ptr() to a function pointer. pub struct Weak { name: &'static str, - addr: LazyUsize, + addr: AtomicPtr, } impl Weak { + // A non-null pointer value which indicates we are uninitialized. This + // constant should ideally not be a valid address of a function pointer. + // However, if by chance libc::dlsym does return UNINIT, there will not + // be undefined behavior. libc::dlsym will just be called each time ptr() + // is called. This would be inefficient, but correct. + // TODO: Replace with core::ptr::invalid_mut(1) when that is stable. + const UNINIT: *mut c_void = 1 as *mut c_void; + // Construct a binding to a C function with a given name. This function is // unsafe because `name` _must_ be null terminated. pub const unsafe fn new(name: &'static str) -> Self { Self { name, - addr: LazyUsize::new(), + addr: AtomicPtr::new(Self::UNINIT), } } - // Return a function pointer if present at runtime. Otherwise, return null. - pub fn ptr(&self) -> Option> { - let addr = self.addr.unsync_init(|| unsafe { - libc::dlsym(libc::RTLD_DEFAULT, self.name.as_ptr() as *const _) as usize - }); - NonNull::new(addr as *mut _) + // Return the address of a function if present at runtime. Otherwise, + // return None. Multiple callers can call ptr() concurrently. It will + // always return _some_ value returned by libc::dlsym. However, the + // dlsym function may be called multiple times. + pub fn ptr(&self) -> Option> { + // Despite having only a single atomic variable (self.addr), we still + // cannot always use Ordering::Relaxed, as we need to make sure a + // successful call to dlsym() is "ordered before" any data read through + // the returned pointer (which occurs when the function is called). + // Our implementation mirrors that of the one in libstd, meaning that + // the use of non-Relaxed operations is probably unnecessary. + match self.addr.load(Ordering::Relaxed) { + Self::UNINIT => { + let symbol = self.name.as_ptr() as *const _; + let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) }; + // Synchronizes with the Acquire fence below + self.addr.store(addr, Ordering::Release); + NonNull::new(addr) + } + addr => { + let func = NonNull::new(addr)?; + fence(Ordering::Acquire); + Some(func) + } + } } } diff --git a/vendor/getrandom/src/wasi.rs b/vendor/getrandom/src/wasi.rs index 2d413e020..c5121824a 100644 --- a/vendor/getrandom/src/wasi.rs +++ b/vendor/getrandom/src/wasi.rs @@ -9,15 +9,11 @@ //! Implementation for WASI use crate::Error; use core::num::NonZeroU32; -use wasi::random_get; +use wasi::wasi_snapshot_preview1::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - unsafe { - random_get(dest.as_mut_ptr(), dest.len()).map_err(|e: wasi::Error| { - // convert wasi's Error into getrandom's NonZeroU32 error - // SAFETY: `wasi::Error` is `NonZeroU16` internally, so `e.raw_error()` - // will never return 0 - NonZeroU32::new_unchecked(e.raw_error() as u32).into() - }) + match unsafe { random_get(dest.as_mut_ptr() as i32, dest.len() as i32) } { + 0 => Ok(()), + err => Err(unsafe { NonZeroU32::new_unchecked(err as u32) }.into()), } } diff --git a/vendor/getrandom/src/windows.rs b/vendor/getrandom/src/windows.rs index 643badd07..41dc37a5c 100644 --- a/vendor/getrandom/src/windows.rs +++ b/vendor/getrandom/src/windows.rs @@ -24,6 +24,7 @@ extern "system" { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Prevent overflow of u32 for chunk in dest.chunks_mut(u32::max_value() as usize) { + // BCryptGenRandom was introduced in Windows Vista let ret = unsafe { BCryptGenRandom( ptr::null_mut(), diff --git a/vendor/gimli/.cargo-checksum.json b/vendor/gimli/.cargo-checksum.json index 5b855e30c..759ec93de 100644 --- a/vendor/gimli/.cargo-checksum.json +++ b/vendor/gimli/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"13bb20c4d7f171cdaf835093237311af52dd979091cbe2c46a6f978c9d783721","CONTRIBUTING.md":"5f513ec06013e4f6f097e9c9492da5a47b9f25c94c6ecadfb655a77405fe912c","Cargo.lock":"9961bcba2db19ce16584ca5cb089568de7ffcbc9668cba37fc3dd851b2e58e56","Cargo.toml":"d607f683bfe0d69d932c331701d54bdf429dbe5280b7cd3b1a5478d9dd9cdc79","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"03ac1a78a14682d70da4d485d3fa01d0ad819b65b6aed50359ee72af43158ca9","benches/bench.rs":"e0045b989683794951563aa91b37069b2f6ae55f95e288d23f5c984b46e3a7eb","examples/dwarf-validate.rs":"8a322dc48a04bff33a759030f399ca9972ddb103e63851cbb9b8c9672095f645","examples/dwarfdump.rs":"3ef93684d0b417da7dc89751e2f5d1c297b3574b478848cb79b550d4ecd83222","examples/simple.rs":"684dc9785f4aa0714fcb91a3ae1bb7c8612c9b12969be47fe1327447a2101d1c","examples/simple_line.rs":"ec5fa47c1ab019c6cd9d525223f947533f6d65d6add3131a0c40ac18fc1297db","fixtures/self/README.md":"557cd710240a14fdaa5842b216de57f2ed481151b640af09d6877984b3b2389f","fixtures/self/debug_abbrev":"7c0faa940d9c68d196d03ad55a20e5c746040fa428ff323277fa381deff82bba","fixtures/self/debug_aranges":"8c2aeb2335f61d04ecb7b747070d24f83a6517cbee79dc5c96d97fb6c53d6b6d","fixtures/self/debug_info":"42028a5983006e0703f9ca9515cd27d891ae4af70279fae5011d547f581e2661","fixtures/self/debug_inlined":"89d9516f06ff835621936037f5884fc56712bf304c1dcde52251ddd510fe8710","fixtures/self/debug_line":"b29aebcca3b38bb2bb8aa708cbe74a0dce5a3b0c18916b63d6d17282c017bec7","fixtures/self/debug_loc":"8906ccb9c204f233eb74c1d069dee97a19d18c2051f9147795d7b5364a9266aa","fixtures/self/debug_pubnames":"cf58e237f89c68afba724597fa7e260448636b45f2e69dc6f1bfe34006e27c48","fixtures/self/debug_pubtypes":"d43c1bed71c9d14d1683294cdc1833f069cf131d6e95ee808547919b4f352d81","fixtures/self/debug_ranges":"6d765ac18d33accd89186d077eeb505cbdf97d990c9201d63d9463cd7787ce7a","fixtures/self/debug_str":"9ed904b68eee77b8558b80b3b7ca03e8527f6c64483e9d6d845f40270eb21183","fixtures/self/eh_frame":"6dc3d84351cac42cf73d03452fbb532470dd94d08715154c48417e3f62095f17","fixtures/self/eh_frame_hdr":"afba7a0aa233c9a8c81c986495bd2505164844adb93272d6bc0c9e592e684716","rustfmt.toml":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/arch.rs":"1c4cb3e2a322f3f42fe0b82875c9d0ce060d9af2388990139bdce9a4487c32da","src/common.rs":"392f52a58db6101187ca5525bbeafca9bda2342debd058cabca37350cd9db619","src/constants.rs":"ca3169f7a45ff1b6a504966c5627ad5c99193e2d0ec06dc9edfdf37617198093","src/endianity.rs":"1f7e62ae34f540c06bedf1e7948739211556eea7dd83731a5ca52c7d687ed0fc","src/leb128.rs":"996d5c79d027f97c010ca487bc4ff5f8265f4b9e63d62b4e4fa291383c259ee9","src/lib.rs":"427d747b0af62894e3c5ea20aecad33e5f458bec0b50fbe584e1e6aa1e5eb4f8","src/read/abbrev.rs":"c49c47ff607435c9d0b702faf366068cd1e95d175be79358b1e21244151eeab6","src/read/addr.rs":"f63f289edf889e87107bb2090fb1c50b48af7015f31b7c39c3d6ea09630a38e9","src/read/aranges.rs":"dee9500e0428bc34fca58b2dda85aef6bf0293785c4077c1a4c144109e9d87c9","src/read/cfi.rs":"e4dacfb576ecbe9248cbea3c3c682b6fd835d3843bca68bb3e18dbda55728643","src/read/dwarf.rs":"a39c24429b437ae3a1cd17bae2f01c973c9ce39f7b5f2b3435982d6860944e0e","src/read/endian_reader.rs":"320983a859c2bb0dd44a3e6fae55ff0a84dba3fa80c2edbc64aa8135c44eddf0","src/read/endian_slice.rs":"ae1c52499728f6a85648f1bf87c02dcf43bebecb5ad4e835a1246938ba4338bf","src/read/index.rs":"e79b8d591b8e2007a37f5ea85a6d71b69d56ca3739a85cf7bf361724c5b829fa","src/read/line.rs":"47ca5ebb8bd19000045954686d3320b838e9404cba917ec60525f11ea0d87095","src/read/lists.rs":"e473ff419feed9756289e245b7879bd89e7f19098a53162fe6773fac496ae5bc","src/read/loclists.rs":"2a5655c53fb2bf5cfe2df373210217edaa06e4d3addf27df0f724100cbfbe43b","src/read/lookup.rs":"0cf89ba12b9d48b1fe035dd3a497730323acb9427a9457abbc2f7c58c4c71165","src/read/mod.rs":"7ea1d01906db92a31a0915b8d2a84776b2a1b2a6587aac8a4acf5ecc48c019b6","src/read/op.rs":"2de049cdcff6c0a324c5737d3fc93431c729554b3bf38e09777b855d7058b29f","src/read/pubnames.rs":"701c1279aef596ed8eff13f19a5803f9e1070afa20c9bafbf29659d4c294edd4","src/read/pubtypes.rs":"6250112d63120ed283698cb42189b127f624fb453abb1222dfa75fe103ad077e","src/read/reader.rs":"b10ff3e77b54347e96b1f3cff30da104dfdd0c4d7a55b672950788f1f1ae3478","src/read/rnglists.rs":"e7426fa1564cbd7e84871ddd741d6a7f016596633f1ffa097885b6e685fc8da2","src/read/str.rs":"932971a6f6f3453685dbd33ff3c2d31a10820b989a209bdfeca3e8c5012cc4b8","src/read/unit.rs":"305e834d7c14e6855beab411076cb7db2615373fd761396ec253250bb0381a59","src/read/util.rs":"480acb9a1fbae7ce935dd1d1307e6a0ab222e009b63ae7817b4bcdcccb9a9ec4","src/read/value.rs":"9a961a49c43bd05061fce1765bda0da049f26420d1be2ed0584de7d1597ab836","src/test_util.rs":"291eefa6b51c6d934ba2f4a4c9bc7c403046fc1cccf4d43487820f0154bb89e2","src/write/abbrev.rs":"fa02163389e92e804d139cf84f833ab6af932083f0eb2d74464b4a70bd3237ff","src/write/cfi.rs":"5d36c6978d2bda09921f5b71b764a75a58e819551471fb44db23ce5db7c4a8e3","src/write/dwarf.rs":"8a1a0893e31134ad68993994594f3024ad0c8af7c1188b29e0ffc26b42edef21","src/write/endian_vec.rs":"1d5811986648816a677580b22630f5059757a381487d73e9adbb3008c9ae0c58","src/write/line.rs":"df7d2082c71b5e523cd52745700aae3dcfa5800f0b280e831ef5d8eb8035d6a7","src/write/loc.rs":"bb5b750c04f6603e18225db72652ea00239234ba674a8a8627c99d4ab07b47a9","src/write/mod.rs":"d8aa1da854cdee629d470d00d87e00dc6998e4bec1ca951f8d2f277730ab9d69","src/write/op.rs":"fb99e95631e24e46eaddef393281ed4f4c56ebc0713a8cbe1683893f7bdde8c6","src/write/range.rs":"5bac01e372c08e3cc19e1e07e40492d8214cdfa8881737920cb792f4aa2ba80b","src/write/section.rs":"3ce781d5e82ba365ff54fdd36e0ef58c58a2215b09a8861eb0b038efac82b77f","src/write/str.rs":"4850cc2fee55980f9cbb6b4169f9861ab9d05c2b28a85c2b790480b83a66f514","src/write/unit.rs":"213c881736f8c87fcb2f921e379791eaba2915e8d077139965a9c6211001fe44","src/write/writer.rs":"304181287f90445bbfb33349c26b34bd87002d6844fc5686bfc0756fd0a1ecd8","tests/convert_self.rs":"8fba3599ac892a704cbcd5aed53eaef51b040043da04f85f002c597ee7549046","tests/parse_self.rs":"f2da1c7daef7139545c9367c2f26199e8b4623b31d4ec6480ddd851e6980f2dc"},"package":"78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4"} \ No newline at end of file +{"files":{"CHANGELOG.md":"789a696803d3f1bed3ff3566cac8e7cf15c4bf9428242d637d0ce7f3a0ad57a3","CONTRIBUTING.md":"5f513ec06013e4f6f097e9c9492da5a47b9f25c94c6ecadfb655a77405fe912c","Cargo.lock":"284bff6b09ef0fd214c34492417778d6d5b9f75dc54557015af01a95696c752a","Cargo.toml":"92dccbeaa61bc8c65da53917fbf32900b3cb2549f90b67b67e1c67672bac205e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"57e36d344dabe1c52a9c81eafb28787c309b86c47437abf8589ef17bf383fc5f","benches/bench.rs":"e0045b989683794951563aa91b37069b2f6ae55f95e288d23f5c984b46e3a7eb","examples/dwarf-validate.rs":"4aac1045e3c08bf00878eeff75c0cfc30c06171c5eab2e71d757505786729687","examples/dwarfdump.rs":"d74323c037689b32825efa9bf69614ee26a444513b266e819ecf486956ee3299","examples/simple.rs":"4c3425e8bd1880d9522f5ed2581fb5ccd452d4be678eebc0e147c48722a7be1d","examples/simple_line.rs":"ac795f859a17650dde466b5b23b8c161b2e3b8eb57e32f5b6718a3072f6bfad0","fixtures/self/README.md":"7cfd76031ec5a4b38cc4eb56ccbfe1bb590fb54c333d037550bdeaaeacfc20cb","fixtures/self/debug_abbrev":"7c0faa940d9c68d196d03ad55a20e5c746040fa428ff323277fa381deff82bba","fixtures/self/debug_aranges":"8c2aeb2335f61d04ecb7b747070d24f83a6517cbee79dc5c96d97fb6c53d6b6d","fixtures/self/debug_info":"42028a5983006e0703f9ca9515cd27d891ae4af70279fae5011d547f581e2661","fixtures/self/debug_inlined":"89d9516f06ff835621936037f5884fc56712bf304c1dcde52251ddd510fe8710","fixtures/self/debug_line":"b29aebcca3b38bb2bb8aa708cbe74a0dce5a3b0c18916b63d6d17282c017bec7","fixtures/self/debug_loc":"8906ccb9c204f233eb74c1d069dee97a19d18c2051f9147795d7b5364a9266aa","fixtures/self/debug_pubnames":"cf58e237f89c68afba724597fa7e260448636b45f2e69dc6f1bfe34006e27c48","fixtures/self/debug_pubtypes":"d43c1bed71c9d14d1683294cdc1833f069cf131d6e95ee808547919b4f352d81","fixtures/self/debug_ranges":"6d765ac18d33accd89186d077eeb505cbdf97d990c9201d63d9463cd7787ce7a","fixtures/self/debug_str":"9ed904b68eee77b8558b80b3b7ca03e8527f6c64483e9d6d845f40270eb21183","fixtures/self/eh_frame":"6dc3d84351cac42cf73d03452fbb532470dd94d08715154c48417e3f62095f17","fixtures/self/eh_frame_hdr":"afba7a0aa233c9a8c81c986495bd2505164844adb93272d6bc0c9e592e684716","rustfmt.toml":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","src/arch.rs":"1c4cb3e2a322f3f42fe0b82875c9d0ce060d9af2388990139bdce9a4487c32da","src/common.rs":"392f52a58db6101187ca5525bbeafca9bda2342debd058cabca37350cd9db619","src/constants.rs":"358cf7924c79bc72de59d23d1fa02b2047d6c763c8fbd8be263ab8cd3e3ba7ec","src/endianity.rs":"1f7e62ae34f540c06bedf1e7948739211556eea7dd83731a5ca52c7d687ed0fc","src/leb128.rs":"996d5c79d027f97c010ca487bc4ff5f8265f4b9e63d62b4e4fa291383c259ee9","src/lib.rs":"6863b9a9d1eddf34b4095dfe60318aae56914fbf515ba5601b29024cc963f27c","src/read/abbrev.rs":"a3f550c32f1eb880d82bdb5257d35e10d32cfd039050e8131cbeedac346cc1d9","src/read/addr.rs":"f63f289edf889e87107bb2090fb1c50b48af7015f31b7c39c3d6ea09630a38e9","src/read/aranges.rs":"ba3302f87cffb7ee15f48b0530ebd707f45ad056934223078d25ae2a1b034f1c","src/read/cfi.rs":"b1064ed9b4b87169a148cc86adc7443c5a771dc2d1799129f7883f1ef6adc165","src/read/dwarf.rs":"a39c24429b437ae3a1cd17bae2f01c973c9ce39f7b5f2b3435982d6860944e0e","src/read/endian_reader.rs":"320983a859c2bb0dd44a3e6fae55ff0a84dba3fa80c2edbc64aa8135c44eddf0","src/read/endian_slice.rs":"ae1c52499728f6a85648f1bf87c02dcf43bebecb5ad4e835a1246938ba4338bf","src/read/index.rs":"e79b8d591b8e2007a37f5ea85a6d71b69d56ca3739a85cf7bf361724c5b829fa","src/read/line.rs":"af7a1520777e56632970fc5fe7377fdcd12d078eb88eeb2b0f2cc95b73ff68a7","src/read/lists.rs":"67ca9e1a36a91feb4996d035211de845205212bfda02163685d217818567ff93","src/read/loclists.rs":"1b4ea85c0dd8c6eae492a60cb70810185d56ba579df7986cb8a36385031b10fd","src/read/lookup.rs":"0cf89ba12b9d48b1fe035dd3a497730323acb9427a9457abbc2f7c58c4c71165","src/read/mod.rs":"3bafc747c31a575bcc92d3e7d5ea5a15f5acc01918a4377cec1dced0f85b5d2b","src/read/op.rs":"e5dce6520dfc90ec74c3b070ca374b89fcf55ff23101471591458175a72c79e6","src/read/pubnames.rs":"ed752ee1a7017e6d3be42d81e4ddaaac960ef08081463a19106c9f041526d4a3","src/read/pubtypes.rs":"5e75b32c0923e827aff0bb2db456797a0e8d38ba46be992558a7990b3196bcf5","src/read/reader.rs":"b10ff3e77b54347e96b1f3cff30da104dfdd0c4d7a55b672950788f1f1ae3478","src/read/rnglists.rs":"af637d283d76514382ee0556463cccab4e6f0ea4d061db9a44a594b5d57d1fd7","src/read/str.rs":"4c2f50014451621fea45969cd313f6840fcd3a99d7a2d081bfa1f8e0e434133a","src/read/unit.rs":"6ed00ba004c329008bf295d9c7d724afe961750f0c7b08430fc213fd5d998003","src/read/util.rs":"0b7d0d2225a98618070dc472ccba49a5411aa8beed5ff6696da079d06156d363","src/read/value.rs":"5a91e03ad3d41f679b264753498434b91948c6b89955e4beb4522498386d9b1d","src/test_util.rs":"291eefa6b51c6d934ba2f4a4c9bc7c403046fc1cccf4d43487820f0154bb89e2","src/write/abbrev.rs":"fa02163389e92e804d139cf84f833ab6af932083f0eb2d74464b4a70bd3237ff","src/write/cfi.rs":"3b04b0ebd82363738199cc673f64e0ceb60506a67c4f18b435a109caa62840f3","src/write/dwarf.rs":"8a1a0893e31134ad68993994594f3024ad0c8af7c1188b29e0ffc26b42edef21","src/write/endian_vec.rs":"1d5811986648816a677580b22630f5059757a381487d73e9adbb3008c9ae0c58","src/write/line.rs":"df7d2082c71b5e523cd52745700aae3dcfa5800f0b280e831ef5d8eb8035d6a7","src/write/loc.rs":"bb5b750c04f6603e18225db72652ea00239234ba674a8a8627c99d4ab07b47a9","src/write/mod.rs":"d8aa1da854cdee629d470d00d87e00dc6998e4bec1ca951f8d2f277730ab9d69","src/write/op.rs":"7b1d49b10c8c92b2d5b259e83119ff7dc95bc552535bb7b1a82ca9556a35c589","src/write/range.rs":"5bac01e372c08e3cc19e1e07e40492d8214cdfa8881737920cb792f4aa2ba80b","src/write/section.rs":"3ce781d5e82ba365ff54fdd36e0ef58c58a2215b09a8861eb0b038efac82b77f","src/write/str.rs":"4850cc2fee55980f9cbb6b4169f9861ab9d05c2b28a85c2b790480b83a66f514","src/write/unit.rs":"213c881736f8c87fcb2f921e379791eaba2915e8d077139965a9c6211001fe44","src/write/writer.rs":"304181287f90445bbfb33349c26b34bd87002d6844fc5686bfc0756fd0a1ecd8","tests/convert_self.rs":"180909b562969e1691b64628ded8654e6e0b10b3357f39917bd8ac288c5826dd","tests/parse_self.rs":"f2da1c7daef7139545c9367c2f26199e8b4623b31d4ec6480ddd851e6980f2dc"},"package":"22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d"} \ No newline at end of file diff --git a/vendor/gimli/CHANGELOG.md b/vendor/gimli/CHANGELOG.md index da2ab0fe7..9ca6d70a8 100644 --- a/vendor/gimli/CHANGELOG.md +++ b/vendor/gimli/CHANGELOG.md @@ -2,6 +2,28 @@ -------------------------------------------------------------------------------- +## 0.26.2 + +Released 2022/07/16. + +### Changed + +* Fixed CFI personality encoding when writing. + [#609](https://github.com/gimli-rs/gimli/pull/609) + +* Fixed use of raw pointer for mutation, detected by Miri. + [#614](https://github.com/gimli-rs/gimli/pull/614) + +* Fixed `DW_OP_GNU_implicit_pointer` handling for DWARF version 2. + [#618](https://github.com/gimli-rs/gimli/pull/618) + +### Added + +* Added `read::EhHdrTable::iter`. + [#619](https://github.com/gimli-rs/gimli/pull/619) + +-------------------------------------------------------------------------------- + ## 0.26.1 Released 2021/11/02. diff --git a/vendor/gimli/Cargo.lock b/vendor/gimli/Cargo.lock index d55f428d0..b4a719a0c 100644 --- a/vendor/gimli/Cargo.lock +++ b/vendor/gimli/Cargo.lock @@ -153,14 +153,14 @@ dependencies = [ [[package]] name = "gimli" -version = "0.26.1" +version = "0.26.2" dependencies = [ "compiler_builtins", "crossbeam", "fallible-iterator", "getopts", "indexmap", - "memmap", + "memmap2", "num_cpus", "object", "rayon", @@ -216,13 +216,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] -name = "memmap" -version = "0.7.0" +name = "memmap2" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +checksum = "3a79b39c93a7a5a27eeaf9a23b5ff43f1b9e0ad6b1cdd441140ae53c35613fc7" dependencies = [ "libc", - "winapi", ] [[package]] @@ -256,9 +255,9 @@ dependencies = [ [[package]] name = "object" -version = "0.27.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67ac1d3f9a1d3616fd9a60c8d74296f22406a238b6a72f5cc1e6f314df4ffbf9" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" dependencies = [ "flate2", "memchr", @@ -357,25 +356,3 @@ name = "wasmparser" version = "0.57.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32fddd575d477c6e9702484139cf9f23dcd554b06d185ed0f56c857dd3a47aa6" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/vendor/gimli/Cargo.toml b/vendor/gimli/Cargo.toml index d5f283c80..f36ccd936 100644 --- a/vendor/gimli/Cargo.toml +++ b/vendor/gimli/Cargo.toml @@ -3,25 +3,37 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "gimli" -version = "0.26.1" -exclude = ["/ci/*", "/releases/*", "/.github"] +version = "0.26.2" +exclude = [ + "/releases/*", + "/.github", +] description = "A library for reading and writing the DWARF debugging format." documentation = "https://docs.rs/gimli" readme = "./README.md" -keywords = ["DWARF", "debug", "ELF", "eh_frame"] -categories = ["development-tools::debugging", "development-tools::profiling", "parser-implementations"] -license = "Apache-2.0/MIT" +keywords = [ + "DWARF", + "debug", + "ELF", + "eh_frame", +] +categories = [ + "development-tools::debugging", + "development-tools::profiling", + "parser-implementations", +] +license = "MIT OR Apache-2.0" repository = "https://github.com/gimli-rs/gimli" + [profile.bench] codegen-units = 1 debug = true @@ -40,11 +52,18 @@ required-features = ["read"] [[example]] name = "dwarfdump" -required-features = ["read", "std"] +required-features = [ + "read", + "std", +] [[example]] name = "dwarf-validate" -required-features = ["read", "std"] +required-features = [ + "read", + "std", +] + [dependencies.alloc] version = "1.0.0" optional = true @@ -72,20 +91,21 @@ optional = true version = "1.1.0" optional = true default-features = false + [dev-dependencies.crossbeam] version = "0.8" [dev-dependencies.getopts] version = "0.2" -[dev-dependencies.memmap] -version = "0.7" +[dev-dependencies.memmap2] +version = "0.5.5" [dev-dependencies.num_cpus] version = "1" [dev-dependencies.object] -version = "0.27.1" +version = "0.29.0" features = ["wasm"] [dev-dependencies.rayon] @@ -101,15 +121,26 @@ version = "0.1.3" version = "2" [features] -default = ["read", "write", "std", "fallible-iterator", "endian-reader"] -endian-reader = ["read", "stable_deref_trait"] +default = [ + "read", + "write", + "std", + "fallible-iterator", + "endian-reader", +] +endian-reader = [ + "read", + "stable_deref_trait", +] read = ["read-core"] read-core = [] -rustc-dep-of-std = ["core", "alloc", "compiler_builtins"] -std = ["fallible-iterator/std", "stable_deref_trait/std"] +rustc-dep-of-std = [ + "core", + "alloc", + "compiler_builtins", +] +std = [ + "fallible-iterator/std", + "stable_deref_trait/std", +] write = ["indexmap"] -[badges.coveralls] -repository = "gimli-rs/gimli" - -[badges.travis-ci] -repository = "gimli-rs/gimli" diff --git a/vendor/gimli/README.md b/vendor/gimli/README.md index 56cee2531..19e7bbd0e 100644 --- a/vendor/gimli/README.md +++ b/vendor/gimli/README.md @@ -6,7 +6,7 @@ [![Coverage Status](https://coveralls.io/repos/github/gimli-rs/gimli/badge.svg?branch=master)](https://coveralls.io/github/gimli-rs/gimli?branch=master) `gimli` is a blazing fast library for consuming the -[DWARF debugging format](http://dwarfstd.org/). +[DWARF debugging format](https://dwarfstd.org/). * **Zero copy:** everything is just a reference to the original input buffer. No copies of the input data get made. @@ -30,7 +30,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -gimli = "0.26.1" +gimli = "0.26.2" ``` The minimum supported Rust version is 1.42.0. @@ -49,7 +49,7 @@ The minimum supported Rust version is 1.42.0. * [An `addr2line` clone](https://github.com/gimli-rs/addr2line) - * [`ddbug`](https://github.com/philipc/ddbug), a utility giving insight into + * [`ddbug`](https://github.com/gimli-rs/ddbug), a utility giving insight into code generation by making debugging information readable. * [`dwprod`](https://github.com/fitzgen/dwprod), a tiny utility to list the diff --git a/vendor/gimli/examples/dwarf-validate.rs b/vendor/gimli/examples/dwarf-validate.rs index 1eabccc11..54d8f3a1d 100644 --- a/vendor/gimli/examples/dwarf-validate.rs +++ b/vendor/gimli/examples/dwarf-validate.rs @@ -52,7 +52,7 @@ fn main() { continue; } }; - let file = match unsafe { memmap::Mmap::map(&file) } { + let file = match unsafe { memmap2::Mmap::map(&file) } { Ok(mmap) => mmap, Err(err) => { eprintln!("Failed to map file '{}': {}", path.display(), &err); diff --git a/vendor/gimli/examples/dwarfdump.rs b/vendor/gimli/examples/dwarfdump.rs index 64b233305..4b61fd572 100644 --- a/vendor/gimli/examples/dwarfdump.rs +++ b/vendor/gimli/examples/dwarfdump.rs @@ -490,7 +490,7 @@ fn main() { process::exit(1); } }; - let mmap = match unsafe { memmap::Mmap::map(&file) } { + let mmap = match unsafe { memmap2::Mmap::map(&file) } { Ok(mmap) => mmap, Err(err) => { eprintln!("Failed to map file '{}': {}", path, err); @@ -531,7 +531,7 @@ fn main() { continue; } }; - let file = match unsafe { memmap::Mmap::map(&file) } { + let file = match unsafe { memmap2::Mmap::map(&file) } { Ok(mmap) => mmap, Err(err) => { eprintln!("Failed to map file '{}': {}", file_path, err); @@ -786,17 +786,36 @@ fn dump_eh_frame( // TODO: augmentation writeln!(w, " code_align: {}", cie.code_alignment_factor())?; writeln!(w, " data_align: {}", cie.data_alignment_factor())?; - writeln!(w, " ra_register: {:#x}", cie.return_address_register().0)?; + writeln!( + w, + " ra_register: {}", + register_name(cie.return_address_register()) + )?; if let Some(encoding) = cie.lsda_encoding() { - writeln!(w, " lsda_encoding: {:#02x}", encoding.0)?; + writeln!( + w, + " lsda_encoding: {}/{}", + encoding.application(), + encoding.format() + )?; } if let Some((encoding, personality)) = cie.personality_with_encoding() { - write!(w, " personality: {:#02x} ", encoding.0)?; + write!( + w, + " personality: {}/{} ", + encoding.application(), + encoding.format() + )?; dump_pointer(w, personality)?; writeln!(w)?; } if let Some(encoding) = cie.fde_address_encoding() { - writeln!(w, " fde_encoding: {:#02x}", encoding.0)?; + writeln!( + w, + " fde_encoding: {}/{}", + encoding.application(), + encoding.format() + )?; } let instructions = cie.instructions(&eh_frame, &bases); dump_cfi_instructions(w, instructions, true, register_name)?; @@ -1585,21 +1604,21 @@ fn dump_type_signature(w: &mut W, signature: gimli::DebugTypeSignature fn dump_file_index( w: &mut W, - file: u64, + file_index: u64, unit: &gimli::Unit, dwarf: &gimli::Dwarf, ) -> Result<()> { - if file == 0 { + if file_index == 0 && unit.header.version() <= 4 { return Ok(()); } let header = match unit.line_program { Some(ref program) => program.header(), None => return Ok(()), }; - let file = match header.file(file) { - Some(header) => header, + let file = match header.file(file_index) { + Some(file) => file, None => { - writeln!(w, "Unable to get header for file {}", file)?; + writeln!(w, "Unable to get header for file {}", file_index)?; return Ok(()); } }; @@ -1607,7 +1626,7 @@ fn dump_file_index( if let Some(directory) = file.directory(header) { let directory = dwarf.attr_string(unit, directory)?; let directory = directory.to_string_lossy()?; - if !directory.starts_with('/') { + if file.directory_index() != 0 && !directory.starts_with('/') { if let Some(ref comp_dir) = unit.comp_dir { write!(w, "{}/", comp_dir.to_string_lossy()?,)?; } @@ -2238,7 +2257,7 @@ fn dump_line_program( writeln!(w, " [lno,col]")?; } let mut rows = program.rows(); - let mut file_index = 0; + let mut file_index = std::u64::MAX; while let Some((header, row)) = rows.next_row()? { let line = match row.line() { Some(line) => line.get(), diff --git a/vendor/gimli/examples/simple.rs b/vendor/gimli/examples/simple.rs index b73ab7552..7c958d45c 100644 --- a/vendor/gimli/examples/simple.rs +++ b/vendor/gimli/examples/simple.rs @@ -6,7 +6,7 @@ use std::{borrow, env, fs}; fn main() { for path in env::args().skip(1) { let file = fs::File::open(&path).unwrap(); - let mmap = unsafe { memmap::Mmap::map(&file).unwrap() }; + let mmap = unsafe { memmap2::Mmap::map(&file).unwrap() }; let object = object::File::parse(&*mmap).unwrap(); let endian = if object.is_little_endian() { gimli::RunTimeEndian::Little diff --git a/vendor/gimli/examples/simple_line.rs b/vendor/gimli/examples/simple_line.rs index bf1114f90..87b224cda 100644 --- a/vendor/gimli/examples/simple_line.rs +++ b/vendor/gimli/examples/simple_line.rs @@ -6,7 +6,7 @@ use std::{borrow, env, fs, path}; fn main() { for path in env::args().skip(1) { let file = fs::File::open(&path).unwrap(); - let mmap = unsafe { memmap::Mmap::map(&file).unwrap() }; + let mmap = unsafe { memmap2::Mmap::map(&file).unwrap() }; let object = object::File::parse(&*mmap).unwrap(); let endian = if object.is_little_endian() { gimli::RunTimeEndian::Little @@ -68,9 +68,16 @@ fn dump_file(object: &object::File, endian: gimli::RunTimeEndian) -> Result<(), let mut path = path::PathBuf::new(); if let Some(file) = row.file(header) { path = comp_dir.clone(); - if let Some(dir) = file.directory(header) { - path.push(dwarf.attr_string(&unit, dir)?.to_string_lossy().as_ref()); + + // The directory index 0 is defined to correspond to the compilation unit directory. + if file.directory_index() != 0 { + if let Some(dir) = file.directory(header) { + path.push( + dwarf.attr_string(&unit, dir)?.to_string_lossy().as_ref(), + ); + } } + path.push( dwarf .attr_string(&unit, file.path_name())? diff --git a/vendor/gimli/fixtures/self/README.md b/vendor/gimli/fixtures/self/README.md index 3847c3852..91053d9b4 100644 --- a/vendor/gimli/fixtures/self/README.md +++ b/vendor/gimli/fixtures/self/README.md @@ -7,7 +7,7 @@ about cross platform and cross object file format issues when running examples. # Updating and adding new sections -## OSX +## macOS Use `otool` to list the sections of a binary: diff --git a/vendor/gimli/src/constants.rs b/vendor/gimli/src/constants.rs index c8d6a1662..c617f4e2e 100644 --- a/vendor/gimli/src/constants.rs +++ b/vendor/gimli/src/constants.rs @@ -1315,7 +1315,7 @@ DwEhPe(u8) { // pointer result itself. // // This isn't defined in the DWARF or the `.eh_frame` standards, but is -// generated by both GNU/Linux and OSX tooling. +// generated by both GNU/Linux and macOS tooling. DW_EH_PE_indirect = 0x80, // These constants apply to both the lower and upper bits. diff --git a/vendor/gimli/src/lib.rs b/vendor/gimli/src/lib.rs index 7ac1820e3..ed1af9cbd 100644 --- a/vendor/gimli/src/lib.rs +++ b/vendor/gimli/src/lib.rs @@ -1,5 +1,5 @@ //! `gimli` is a library for reading and writing the -//! [DWARF debugging format](http://dwarfstd.org/). +//! [DWARF debugging format](https://dwarfstd.org/). //! //! See the [read](./read/index.html) and [write](./write/index.html) modules //! for examples and API documentation. diff --git a/vendor/gimli/src/read/abbrev.rs b/vendor/gimli/src/read/abbrev.rs index 5f0e7bed7..1a24835a7 100644 --- a/vendor/gimli/src/read/abbrev.rs +++ b/vendor/gimli/src/read/abbrev.rs @@ -29,7 +29,7 @@ where /// /// It is the caller's responsibility to read the `.debug_abbrev` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugAbbrev, LittleEndian}; diff --git a/vendor/gimli/src/read/aranges.rs b/vendor/gimli/src/read/aranges.rs index c2d22850c..83159b69b 100644 --- a/vendor/gimli/src/read/aranges.rs +++ b/vendor/gimli/src/read/aranges.rs @@ -18,7 +18,7 @@ where /// /// It is the caller's responsibility to read the `.debug_aranges` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugAranges, LittleEndian}; diff --git a/vendor/gimli/src/read/cfi.rs b/vendor/gimli/src/read/cfi.rs index b6a81f3f4..2e5167349 100644 --- a/vendor/gimli/src/read/cfi.rs +++ b/vendor/gimli/src/read/cfi.rs @@ -63,7 +63,7 @@ where /// /// It is the caller's responsibility to read the section and present it as /// a `&[u8]` slice. That means using some ELF loader on Linux, a Mach-O - /// loader on OSX, etc. + /// loader on macOS, etc. /// /// ``` /// use gimli::{DebugFrame, NativeEndian}; @@ -218,6 +218,81 @@ impl ParsedEhFrameHdr { } } +/// An iterator for `.eh_frame_hdr` section's binary search table. +/// +/// Each table entry consists of a tuple containing an `initial_location` and `address`. +/// The `initial location` represents the first address that the targeted FDE +/// is able to decode. The `address` is the address of the FDE in the `.eh_frame` section. +/// The `address` can be converted with `EhHdrTable::pointer_to_offset` and `EhFrame::fde_from_offset` to an FDE. +#[derive(Debug)] +pub struct EhHdrTableIter<'a, 'bases, R: Reader> { + hdr: &'a ParsedEhFrameHdr, + table: R, + bases: &'bases BaseAddresses, + remain: u64, +} + +impl<'a, 'bases, R: Reader> EhHdrTableIter<'a, 'bases, R> { + /// Yield the next entry in the `EhHdrTableIter`. + pub fn next(&mut self) -> Result> { + if self.remain == 0 { + return Ok(None); + } + + let parameters = PointerEncodingParameters { + bases: &self.bases.eh_frame_hdr, + func_base: None, + address_size: self.hdr.address_size, + section: &self.hdr.section, + }; + + self.remain -= 1; + let from = parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut self.table)?; + let to = parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut self.table)?; + Ok(Some((from, to))) + } + /// Yield the nth entry in the `EhHdrTableIter` + pub fn nth(&mut self, n: usize) -> Result> { + use core::convert::TryFrom; + let size = match self.hdr.table_enc.format() { + constants::DW_EH_PE_uleb128 | constants::DW_EH_PE_sleb128 => { + return Err(Error::VariableLengthSearchTable); + } + constants::DW_EH_PE_sdata2 | constants::DW_EH_PE_udata2 => 2, + constants::DW_EH_PE_sdata4 | constants::DW_EH_PE_udata4 => 4, + constants::DW_EH_PE_sdata8 | constants::DW_EH_PE_udata8 => 8, + _ => return Err(Error::UnknownPointerEncoding), + }; + + let row_size = size * 2; + let n = u64::try_from(n).map_err(|_| Error::UnsupportedOffset)?; + self.remain = self.remain.saturating_sub(n); + self.table.skip(R::Offset::from_u64(n * row_size)?)?; + self.next() + } +} + +#[cfg(feature = "fallible-iterator")] +impl<'a, 'bases, R: Reader> fallible_iterator::FallibleIterator for EhHdrTableIter<'a, 'bases, R> { + type Item = (Pointer, Pointer); + type Error = Error; + fn next(&mut self) -> Result> { + EhHdrTableIter::next(self) + } + + fn size_hint(&self) -> (usize, Option) { + use core::convert::TryInto; + ( + self.remain.try_into().unwrap_or(0), + self.remain.try_into().ok(), + ) + } + + fn nth(&mut self, n: usize) -> Result> { + EhHdrTableIter::nth(self, n) + } +} + /// The CFI binary search table that is an optional part of the `.eh_frame_hdr` section. #[derive(Debug, Clone)] pub struct EhHdrTable<'a, R: Reader> { @@ -225,6 +300,20 @@ pub struct EhHdrTable<'a, R: Reader> { } impl<'a, R: Reader + 'a> EhHdrTable<'a, R> { + /// Return an iterator that can walk the `.eh_frame_hdr` table. + /// + /// Each table entry consists of a tuple containing an `initial_location` and `address`. + /// The `initial location` represents the first address that the targeted FDE + /// is able to decode. The `address` is the address of the FDE in the `.eh_frame` section. + /// The `address` can be converted with `EhHdrTable::pointer_to_offset` and `EhFrame::fde_from_offset` to an FDE. + pub fn iter<'bases>(&self, bases: &'bases BaseAddresses) -> EhHdrTableIter<'_, 'bases, R> { + EhHdrTableIter { + hdr: self.hdr, + bases, + remain: self.hdr.fde_count, + table: self.hdr.table.clone(), + } + } /// *Probably* returns a pointer to the FDE for the given address. /// /// This performs a binary search, so if there is no FDE for the given address, @@ -423,19 +512,19 @@ where Endian: Endianity, { /// Construct a new `EhFrame` instance from the data in the - /// `.debug_frame` section. + /// `.eh_frame` section. /// /// It is the caller's responsibility to read the section and present it as /// a `&[u8]` slice. That means using some ELF loader on Linux, a Mach-O - /// loader on OSX, etc. + /// loader on macOS, etc. /// /// ``` /// use gimli::{EhFrame, EndianSlice, NativeEndian}; /// - /// // Use with `.debug_frame` + /// // Use with `.eh_frame` /// # let buf = [0x00, 0x01, 0x02, 0x03]; - /// # let read_debug_frame_section_somehow = || &buf; - /// let debug_frame = EhFrame::new(read_debug_frame_section_somehow(), NativeEndian); + /// # let read_eh_frame_section_somehow = || &buf; + /// let eh_frame = EhFrame::new(read_eh_frame_section_somehow(), NativeEndian); /// ``` pub fn new(section: &'input [u8], endian: Endian) -> Self { Self::from(EndianSlice::new(section, endian)) @@ -6211,6 +6300,39 @@ mod tests { let table = table.unwrap(); let bases = Default::default(); + let mut iter = table.iter(&bases); + assert_eq!( + iter.next(), + Ok(Some(( + Pointer::Direct(10), + Pointer::Direct(0x12345 + start_of_fde1.value().unwrap() as u64) + ))) + ); + assert_eq!( + iter.next(), + Ok(Some(( + Pointer::Direct(20), + Pointer::Direct(0x12345 + start_of_fde2.value().unwrap() as u64) + ))) + ); + assert_eq!(iter.next(), Ok(None)); + + assert_eq!( + table.iter(&bases).nth(0), + Ok(Some(( + Pointer::Direct(10), + Pointer::Direct(0x12345 + start_of_fde1.value().unwrap() as u64) + ))) + ); + + assert_eq!( + table.iter(&bases).nth(1), + Ok(Some(( + Pointer::Direct(20), + Pointer::Direct(0x12345 + start_of_fde2.value().unwrap() as u64) + ))) + ); + assert_eq!(table.iter(&bases).nth(2), Ok(None)); let f = |_: &_, _: &_, o: EhFrameOffset| { assert_eq!(o, EhFrameOffset(start_of_cie.value().unwrap() as usize)); diff --git a/vendor/gimli/src/read/line.rs b/vendor/gimli/src/read/line.rs index 096ddf07b..0e7380bb9 100644 --- a/vendor/gimli/src/read/line.rs +++ b/vendor/gimli/src/read/line.rs @@ -27,7 +27,7 @@ where /// /// It is the caller's responsibility to read the `.debug_line` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugLine, LittleEndian}; diff --git a/vendor/gimli/src/read/lists.rs b/vendor/gimli/src/read/lists.rs index b63c5c126..898a757d3 100644 --- a/vendor/gimli/src/read/lists.rs +++ b/vendor/gimli/src/read/lists.rs @@ -4,6 +4,7 @@ use crate::read::{Error, Reader, Result}; #[derive(Debug, Clone, Copy)] pub(crate) struct ListsHeader { encoding: Encoding, + #[allow(dead_code)] offset_entry_count: u32, } diff --git a/vendor/gimli/src/read/loclists.rs b/vendor/gimli/src/read/loclists.rs index 3c4da127d..3902c181b 100644 --- a/vendor/gimli/src/read/loclists.rs +++ b/vendor/gimli/src/read/loclists.rs @@ -24,7 +24,7 @@ where /// /// It is the caller's responsibility to read the `.debug_loc` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugLoc, LittleEndian}; @@ -70,7 +70,7 @@ where /// /// It is the caller's responsibility to read the `.debug_loclists` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugLocLists, LittleEndian}; diff --git a/vendor/gimli/src/read/mod.rs b/vendor/gimli/src/read/mod.rs index 7291f3b96..3110957c2 100644 --- a/vendor/gimli/src/read/mod.rs +++ b/vendor/gimli/src/read/mod.rs @@ -48,7 +48,7 @@ //! //! * [An `addr2line` clone](https://github.com/gimli-rs/addr2line) //! -//! * [`ddbug`](https://github.com/philipc/ddbug), a utility giving insight into +//! * [`ddbug`](https://github.com/gimli-rs/ddbug), a utility giving insight into //! code generation by making debugging information readable //! //! * [`dwprod`](https://github.com/fitzgen/dwprod), a tiny utility to list the diff --git a/vendor/gimli/src/read/op.rs b/vendor/gimli/src/read/op.rs index 2ca6247bc..88ea20297 100644 --- a/vendor/gimli/src/read/op.rs +++ b/vendor/gimli/src/read/op.rs @@ -707,7 +707,13 @@ where } constants::DW_OP_stack_value => Ok(Operation::StackValue), constants::DW_OP_implicit_pointer | constants::DW_OP_GNU_implicit_pointer => { - let value = bytes.read_offset(encoding.format)?; + let value = if encoding.version == 2 { + bytes + .read_address(encoding.address_size) + .and_then(Offset::from_u64)? + } else { + bytes.read_offset(encoding.format)? + }; let byte_offset = bytes.read_sleb128()?; Ok(Operation::ImplicitPointer { value: DebugInfoOffset(value), @@ -2738,6 +2744,19 @@ mod tests { }, encoding8(), ); + + check_op_parse( + |s| s.D8(op.0).D64(0x1234_5678).sleb(0x123), + &Operation::ImplicitPointer { + value: DebugInfoOffset(0x1234_5678), + byte_offset: 0x123, + }, + Encoding { + format: Format::Dwarf32, + version: 2, + address_size: 8, + }, + ) } } diff --git a/vendor/gimli/src/read/pubnames.rs b/vendor/gimli/src/read/pubnames.rs index f05861f70..e8b7e5528 100644 --- a/vendor/gimli/src/read/pubnames.rs +++ b/vendor/gimli/src/read/pubnames.rs @@ -58,7 +58,7 @@ where /// /// It is the caller's responsibility to read the `.debug_pubnames` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugPubNames, LittleEndian}; diff --git a/vendor/gimli/src/read/pubtypes.rs b/vendor/gimli/src/read/pubtypes.rs index 0226e84d4..6723b4222 100644 --- a/vendor/gimli/src/read/pubtypes.rs +++ b/vendor/gimli/src/read/pubtypes.rs @@ -58,7 +58,7 @@ where /// /// It is the caller's responsibility to read the `.debug_pubtypes` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugPubTypes, LittleEndian}; diff --git a/vendor/gimli/src/read/rnglists.rs b/vendor/gimli/src/read/rnglists.rs index dd68083ac..d8d49042f 100644 --- a/vendor/gimli/src/read/rnglists.rs +++ b/vendor/gimli/src/read/rnglists.rs @@ -24,7 +24,7 @@ where /// /// It is the caller's responsibility to read the `.debug_ranges` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugRanges, LittleEndian}; @@ -70,7 +70,7 @@ where /// /// It is the caller's responsibility to read the `.debug_rnglists` /// section and present it as a `&[u8]` slice. That means using some ELF - /// loader on Linux, a Mach-O loader on OSX, etc. + /// loader on Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugRngLists, LittleEndian}; diff --git a/vendor/gimli/src/read/str.rs b/vendor/gimli/src/read/str.rs index dce8016af..c6b87d8f9 100644 --- a/vendor/gimli/src/read/str.rs +++ b/vendor/gimli/src/read/str.rs @@ -22,7 +22,7 @@ where /// /// It is the caller's responsibility to read the `.debug_str` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugStr, LittleEndian}; @@ -214,7 +214,7 @@ where /// /// It is the caller's responsibility to read the `.debug_line_str` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugLineStr, LittleEndian}; diff --git a/vendor/gimli/src/read/unit.rs b/vendor/gimli/src/read/unit.rs index 4766b2e84..670e55efd 100644 --- a/vendor/gimli/src/read/unit.rs +++ b/vendor/gimli/src/read/unit.rs @@ -93,7 +93,7 @@ where /// /// It is the caller's responsibility to read the `.debug_info` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugInfo, LittleEndian}; @@ -3086,7 +3086,7 @@ where /// /// It is the caller's responsibility to read the `.debug_types` section and /// present it as a `&[u8]` slice. That means using some ELF loader on - /// Linux, a Mach-O loader on OSX, etc. + /// Linux, a Mach-O loader on macOS, etc. /// /// ``` /// use gimli::{DebugTypes, LittleEndian}; diff --git a/vendor/gimli/src/read/util.rs b/vendor/gimli/src/read/util.rs index dd2af8181..16eafdde4 100644 --- a/vendor/gimli/src/read/util.rs +++ b/vendor/gimli/src/read/util.rs @@ -180,7 +180,7 @@ impl ArrayVec> { let slice = Box::leak(storage); debug_assert!(len <= slice.len()); // SAFETY: valid elements. - unsafe { Vec::from_raw_parts(slice.as_ptr() as _, len, slice.len()) } + unsafe { Vec::from_raw_parts(slice.as_mut_ptr() as *mut T, len, slice.len()) } } } diff --git a/vendor/gimli/src/read/value.rs b/vendor/gimli/src/read/value.rs index fc8c355a9..6f43ebb26 100644 --- a/vendor/gimli/src/read/value.rs +++ b/vendor/gimli/src/read/value.rs @@ -1,7 +1,5 @@ //! Definitions for values used in DWARF expressions. -use core::mem; - use crate::constants; #[cfg(feature = "read")] use crate::read::{AttributeValue, DebuggingInformationEntry}; diff --git a/vendor/gimli/src/write/cfi.rs b/vendor/gimli/src/write/cfi.rs index c58eb1b1d..718cb69ad 100644 --- a/vendor/gimli/src/write/cfi.rs +++ b/vendor/gimli/src/write/cfi.rs @@ -239,7 +239,7 @@ impl CommonInformationEntry { } if let Some((eh_pe, address)) = self.personality { w.write_u8(eh_pe.0)?; - w.write_eh_pointer(address, constants::DW_EH_PE_absptr, encoding.address_size)?; + w.write_eh_pointer(address, eh_pe, encoding.address_size)?; } if self.fde_address_encoding != constants::DW_EH_PE_absptr { w.write_u8(self.fde_address_encoding.0)?; @@ -888,6 +888,19 @@ mod tests { fde4.lsda = Some(Address::Constant(0x4400)); frames.add_fde(cie2_id, fde4.clone()); + let mut cie3 = CommonInformationEntry::new(encoding, 1, 8, X86_64::RA); + cie3.fde_address_encoding = constants::DW_EH_PE_pcrel; + cie3.lsda_encoding = Some(constants::DW_EH_PE_pcrel); + cie3.personality = Some((constants::DW_EH_PE_pcrel, Address::Constant(0x1235))); + cie3.signal_trampoline = true; + let cie3_id = frames.add_cie(cie3.clone()); + assert_ne!(cie2_id, cie3_id); + assert_eq!(cie3_id, frames.add_cie(cie3.clone())); + + let mut fde5 = FrameDescriptionEntry::new(Address::Constant(0x5000), 0x50); + fde5.lsda = Some(Address::Constant(0x5500)); + frames.add_fde(cie3_id, fde5.clone()); + // Test writing `.debug_frame`. let mut debug_frame = DebugFrame::from(EndianVec::new(LittleEndian)); frames.write_debug_frame(&mut debug_frame).unwrap(); diff --git a/vendor/gimli/src/write/op.rs b/vendor/gimli/src/write/op.rs index d1cacb356..c70eec2dd 100644 --- a/vendor/gimli/src/write/op.rs +++ b/vendor/gimli/src/write/op.rs @@ -778,7 +778,11 @@ impl Operation { } else { w.write_u8(constants::DW_OP_GNU_implicit_pointer.0)?; } - let size = encoding.format.word_size(); + let size = if encoding.version == 2 { + encoding.address_size + } else { + encoding.format.word_size() + }; match entry { Reference::Symbol(symbol) => { w.write_reference(symbol, size)?; diff --git a/vendor/gimli/tests/convert_self.rs b/vendor/gimli/tests/convert_self.rs index ec8b592d3..7c069ebd6 100644 --- a/vendor/gimli/tests/convert_self.rs +++ b/vendor/gimli/tests/convert_self.rs @@ -146,7 +146,7 @@ fn test_convert_eh_frame() { .write_eh_frame(&mut write_eh_frame) .expect("Should write eh_frame information"); let eh_frame = write_eh_frame.slice(); - assert_eq!(eh_frame.len(), 147152); + assert_eq!(eh_frame.len(), 147144); // Convert new section let mut eh_frame = read::EhFrame::new(&eh_frame, LittleEndian); diff --git a/vendor/handlebars/.cargo-checksum.json b/vendor/handlebars/.cargo-checksum.json index d41808a41..b1031c230 100644 --- a/vendor/handlebars/.cargo-checksum.json +++ b/vendor/handlebars/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"ab776bc63c83489640577a611f7df181de9a3191bf6e5fb449012fd5f6b5e770","Cargo.lock":"fb81e47543e26596ba74d5c165e26f70ec1532911dd638dc6bee65e572b09182","Cargo.toml":"5c6beb2539b6d5e038a5beeead3ed4c044b9be7fdcd4fab60b5a16ce31121bdf","LICENSE":"63b308fad3db82dc12067a8d7ff4b672fae97d12d0b4b3bb59179e27d640b3a4","README.md":"e9dfd89edf514c3613b5b2f47c05f2ba48bf1c9afee8eca1ba395887c8a85c9d","benches/bench.rs":"276ac8c581db35dbdc00e9e4cc1e2e1940fe95522a8f5a19ab088a2c68da61ed","build-wasm.sh":"9f7226d7d0768fe0fba97f698642a4c13a600468ba7d57abcfad9285efd9f4ce","examples/decorator.rs":"010762d337c64a8ade120c66ccb97ac176653d2fc1265c6f77c35d2a7693176f","examples/decorator/template.hbs":"76fd24f08b28b469529f4727321c7cc940198abb5c1aa24d7a6dd2ab42bdda66","examples/dev_mode.rs":"8e28b0f354e14006481faba76f32401a18476472b2e4c9faeea54f222980a9ba","examples/dev_mode/template.hbs":"4a5e1b81565572e26986d890e4a431953b81893a99ce07cef303e366dd84243c","examples/error.rs":"85219ee57a7bc739185862d04c7eff203743ddf730b940f92492894e3ebb5746","examples/error/error.hbs":"4e8fac806d444a5bc41436fe0a51b4d7850c7645f8996db7a99a821c88622eef","examples/error/template.hbs":"48313b522ddb0dd4285874b96d1b705b841dc141514f440790e904a262955951","examples/partials.rs":"e102f0bdacb80a08ac9ae3c92c415991095a1a2142d55420457706823a67fba0","examples/partials/base0.hbs":"6674275ef68faaeab8a4128da0983c9d732d7552f1791c2e3563fa8c5c66fb5a","examples/partials/base1.hbs":"97b1089705f5a21a6f344190e26133d920d56d4a7fdc1fa2fb7359a720bfe182","examples/partials/template2.hbs":"6f83bc48b774a3b83f9ce5a54bf014fb03514720f9e32834dc68000d06a17618","examples/quick.rs":"96df03fc1742504afae34c6da9da05206adc41f771406da2825b41725329cb2d","examples/render.rs":"eadc1aff65d96c7f95c948fbccfb79981276075f83e19a22214fe0772ef17496","examples/render/template.hbs":"2512ef3362379633790985fe2c40e7efab3ad0f431b7cbec5b7cc644dbbef8f5","examples/render_cli/simple.hbs":"a2e0df51e7c1a25c4e9e1bbe0f4911c7c86200d358fc6c9195b61e89adddc970","examples/render_file.rs":"f5b8e788ac6a71a170c5b315120e8779896df8d9b290fb3d785f51307f5d3c45","examples/render_file/template.hbs":"8ec8d0b61a996391ad7f8b6a914f84d0ac06c62e6d7c9c5fa054ca5e2c64a52e","examples/script.rs":"df869a15d6cd8c478f74582018c54e20545b9451e84cdec2f8bb71c31a618da0","examples/script/goals.rhai":"d756fd7d39f11fae148a6e11d23160da0cdac91c29f716dcb854c07a7db09c80","examples/script/template.hbs":"1f39785157a112bc5c4e94db1361c45a73b024bc8bd0fea0a9d5da8102afb310","profile.sh":"b8e80c59bc12fca93daa67c09001c1c045e594e532831cc957c9ac313f8b2390","release.toml":"968ff7e0a0f8b99d0b91a06cb007fcee55427ccbd05012b46202829336287151","rustfmt.toml":"8e99dabd6aadb112f9f9ed8709e7388b57bf43d19cd08342c093c870534a3f97","src/block.rs":"da38a572a95c3858685e4af82a7e1920c6b3311acf8c118c53c8531b091de391","src/cli.rs":"63aed9a8fb2135ee03bd2b49330be20d2018fe3c36265c14dbdc0da9b73cb6d0","src/context.rs":"5007324a0655daa994e1b64f0eed160e67e4a4d8fb02d21eca4c549d5dcea7c2","src/decorators/inline.rs":"73b8ba6ed98dbf8b3bca228796f47c9139d49f1a1c8d5b4603cc6354098b56c2","src/decorators/mod.rs":"322d4d692331a1e3a2806780cbe1e7a3a82b343486f1182d2e8a017a8bf11085","src/error.rs":"7da2635fdb0005437d8c4a7cb889336d0039665d7627544f600d473f5b90eab8","src/grammar.pest":"aed7ff83953551d48e4e94edc25d51f7e418ec79b62df1ca8f7e728444430d0b","src/grammar.rs":"848d1b56bc1d887e8c42836c37d41b2a634ec6eb9e3880be7dde31d84a38460d","src/helpers/block_util.rs":"11a295215f9c0d14b89f97161468425405386214f050bad07683669a162f9aa1","src/helpers/helper_each.rs":"75b536114f954287936e9f02a54b0c182144e2e6a4ad0970e66cc644cc8f3a0f","src/helpers/helper_extras.rs":"0575a1518eba51cafe91ec2b09666e1c987c9a9bc98cb00193d1e0d203a8b681","src/helpers/helper_if.rs":"37c81b7000948f601398b7163b37397020d191642021077bd7eb15c181632d32","src/helpers/helper_log.rs":"272f7c1f873b97974cce156c04281f2bd8c44ccc885b4c59dd2b43e8d7cc6ef6","src/helpers/helper_lookup.rs":"a9f000e36d0e9339930b3d94dabd4f123cdbdaa85e8d77d15e4a772a99ffe9d4","src/helpers/helper_raw.rs":"6b0b5b3774a1d5c3ebf30b1e0b8cac825f6ffb8a18cb9e08bd40786258e4b597","src/helpers/helper_with.rs":"9964ec02b56ad8fb6f3aa9abb535c0d3f6f2cf3eaeba59a5afd8687ea6df2209","src/helpers/mod.rs":"31eefbd1f302b852e43a3aa8432ce4faad04db37eba7fc1bfa8cf9c25967b899","src/helpers/scripting.rs":"6b9e7e08bdbf3e2716bb82b69e0f10efd4de1174842742215aba18fb2cc507e2","src/json/mod.rs":"ef2fc8fe98e9761e2e2a4b2d2293bb29cdb689db2f44f939fc61c48c6b52f0a7","src/json/path.rs":"818bc5f002839a529ffe5d5f8eddd815ac3808a5f9ce3bac79f1f71f5702599b","src/json/value.rs":"390ea4fa8b5131a3d00ff1c80d06359220f16d851a5e836192026ea32acbb02e","src/lib.rs":"ecbb4099b2c0cc77e746083181a8ed32b7f76671aa8e54d079eb4196b24d167c","src/local_vars.rs":"91d3a16bbfabe2eccecaa9a0dd866ebe88d70ce438d2f18581d1b7d231ba0644","src/macros.rs":"86eed922319644176e8464023455b78440b8e5d0d9b13a0ce61b2edf0f10984e","src/output.rs":"10c28874f78cddba70b24eb984a849c7750b207ac605f2aa46f2abe02846b3a2","src/partial.rs":"ddcd49436b6c653b3e5db44a997c5cd9006755dd1e6c07aa5996fa495aecd382","src/registry.rs":"56d613a72ca9e4ad15953cf5b74bf6df912e81f8f008780bebe93375fb1569ed","src/render.rs":"cec805cd1396bc87f1c2bcd9d45b8c6236a65cb99c6d45f14199fab99b94d38d","src/sources.rs":"46989eb76f36edff9dcb5d27488e8bd9c7ff1749f368a70e855f4808c58d7bcf","src/support.rs":"b3d1d99440182548ff9bfcffbd9a7e08507f740ed68382f9c74ab0a92a79eab7","src/template.rs":"61625e52f43c9df92fce25f626db6c61b31a42310c06a8158b13b9f960339e12","src/util.rs":"2ebc845de5ca47455442a1b6bd664565a52e29928e82c526fbfe56ed5196410f","tests/block_context.rs":"4dce11312d2b6c0c5c2f3104516e5567e5a370611e08f4055fa3653293580385","tests/data_helper.rs":"a7f9d1d42d5415ba1dba459840067acc1294f6f6057d9a5a13d9f7e19469e850","tests/escape.rs":"a4bd25c4268a306dc09dc17806f86895c4932753a585219902f0dd85c7e65cba","tests/helper_function_lifetime.rs":"635cbd0b44742539bdf36e803a19c6a1a698399f8b765415d53f28df1acfbc2b","tests/helper_macro.rs":"4660cfb782c03e70f536bedbb2ed5afed5e8fe841d77c1812e4b2ef55d81a6a6","tests/helper_with_space.rs":"c64952ea031f964e558cb323df1bf731bb7c0bf7b226142cea61afa2fd4efbfd","tests/root_var.rs":"fda5b30bac1e692fb010f9f98e052d5a525420fece9dcc3821a4e5aeee3a8841","tests/subexpression.rs":"b36ab31adf45272ca984c0c5ed9497820ca072a8805444d69bd089b766786bb5","tests/template_names.rs":"4bbe6b48c974ae7ea1e61806794d846e2f0e8505e1568c5305fa2364dceef68a","wasm/LICENSE":"63b308fad3db82dc12067a8d7ff4b672fae97d12d0b4b3bb59179e27d640b3a4","wasm/README.md":"d67bad452550d34e9317fb8f4884b8bc07939fbb0dfdcf1be6bfce52a6851fa6","wasm/wapm.toml":"bdb286ccaa18c5c8aa0d2db25755aba9b0e3e83a59fc4d2334c1854933000ea1"},"package":"72a0ffab8c36d0436114310c7e10b59b3307e650ddfabf6d006028e29a70c6e6"} \ No newline at end of file +{"files":{"CHANGELOG.md":"1c33d57ecdf48bcc7011c1e7306d05359a3fca61f3c48324e5cb5b378d406ef6","Cargo.lock":"81ba21eaf5647124881eacf240b9c34ae15c4f3b56072d7ff3ec665f269c3843","Cargo.toml":"afbdf3fe79ae8e5a434f6cb126f3441e8750a499f2b159226cd86e48e4d5424e","LICENSE":"63b308fad3db82dc12067a8d7ff4b672fae97d12d0b4b3bb59179e27d640b3a4","README.md":"ae8924a77607ab2439ef2cb87a93c49b51a4da228ea144bc847ec6d2a4acffba","benches/bench.rs":"276ac8c581db35dbdc00e9e4cc1e2e1940fe95522a8f5a19ab088a2c68da61ed","build-wasm.sh":"9f7226d7d0768fe0fba97f698642a4c13a600468ba7d57abcfad9285efd9f4ce","examples/decorator.rs":"010762d337c64a8ade120c66ccb97ac176653d2fc1265c6f77c35d2a7693176f","examples/decorator/template.hbs":"76fd24f08b28b469529f4727321c7cc940198abb5c1aa24d7a6dd2ab42bdda66","examples/dev_mode.rs":"7c8cebbc56da3e834688719f5c10df1c372c059259e40df8534c79a0dda01aab","examples/dev_mode/template.hbs":"4a5e1b81565572e26986d890e4a431953b81893a99ce07cef303e366dd84243c","examples/error.rs":"6f3d4dc945628778d3ef63dccdc7abbf367e214a5ff62a5dcbeb11d8f34317d7","examples/error/error.hbs":"4e8fac806d444a5bc41436fe0a51b4d7850c7645f8996db7a99a821c88622eef","examples/error/template.hbs":"48313b522ddb0dd4285874b96d1b705b841dc141514f440790e904a262955951","examples/helper_macro.rs":"ca0c7b7a45e8f3f8c7fe25d59a5bb3189b067189dab642bfb02dda416f20774d","examples/partials.rs":"0b3ee03668338b9900705b1162ac1f602255d4b691d1827cb603efff318d3166","examples/partials/base0.hbs":"6674275ef68faaeab8a4128da0983c9d732d7552f1791c2e3563fa8c5c66fb5a","examples/partials/base1.hbs":"97b1089705f5a21a6f344190e26133d920d56d4a7fdc1fa2fb7359a720bfe182","examples/partials/template2.hbs":"6f83bc48b774a3b83f9ce5a54bf014fb03514720f9e32834dc68000d06a17618","examples/quick.rs":"96df03fc1742504afae34c6da9da05206adc41f771406da2825b41725329cb2d","examples/render.rs":"eadc1aff65d96c7f95c948fbccfb79981276075f83e19a22214fe0772ef17496","examples/render/template.hbs":"2512ef3362379633790985fe2c40e7efab3ad0f431b7cbec5b7cc644dbbef8f5","examples/render_cli/simple.hbs":"a2e0df51e7c1a25c4e9e1bbe0f4911c7c86200d358fc6c9195b61e89adddc970","examples/render_file.rs":"f5b8e788ac6a71a170c5b315120e8779896df8d9b290fb3d785f51307f5d3c45","examples/render_file/template.hbs":"8ec8d0b61a996391ad7f8b6a914f84d0ac06c62e6d7c9c5fa054ca5e2c64a52e","examples/script.rs":"5e16423dc4c8ae0e383f0d8b9e1a652850fa5e48dbc57cca3757661c3e0476bb","examples/script/goals.rhai":"d756fd7d39f11fae148a6e11d23160da0cdac91c29f716dcb854c07a7db09c80","examples/script/template.hbs":"1f39785157a112bc5c4e94db1361c45a73b024bc8bd0fea0a9d5da8102afb310","profile.sh":"b8e80c59bc12fca93daa67c09001c1c045e594e532831cc957c9ac313f8b2390","release.toml":"d1c1f8e31be9268666c07a2c3f244e73c3db7474a2a64218fac71f7ad1f20b5d","rustfmt.toml":"8e99dabd6aadb112f9f9ed8709e7388b57bf43d19cd08342c093c870534a3f97","src/block.rs":"da38a572a95c3858685e4af82a7e1920c6b3311acf8c118c53c8531b091de391","src/cli.rs":"63aed9a8fb2135ee03bd2b49330be20d2018fe3c36265c14dbdc0da9b73cb6d0","src/context.rs":"6d594b5c93cdc1e8ee08c3858f50dddc312eaa20b9ea3f4c14906bc6ebee318f","src/decorators/inline.rs":"73b8ba6ed98dbf8b3bca228796f47c9139d49f1a1c8d5b4603cc6354098b56c2","src/decorators/mod.rs":"a9189648fd11609fc6681d6df4af0deb1a1958e12c447485a0455d7e67f70fa3","src/error.rs":"a101458e111478fd6c3749910ca7af8afa973d51eb9a4bd13569e66d0aa8ae8f","src/grammar.pest":"a6754e1b61ba282f325af30f907e9e175ad21f0bec322d42e6f975a6f3bf2c7e","src/grammar.rs":"d572c6507f673c1e5c7c018f485672e6c10671d6749d0d9182f26d62e2e1537e","src/helpers/block_util.rs":"11a295215f9c0d14b89f97161468425405386214f050bad07683669a162f9aa1","src/helpers/helper_each.rs":"827de9ba0224cdd361ce52f02a9f301e879d738d6837672798517b83db68b331","src/helpers/helper_extras.rs":"0575a1518eba51cafe91ec2b09666e1c987c9a9bc98cb00193d1e0d203a8b681","src/helpers/helper_if.rs":"2fe6cc5f3b44a42611d02137e5a11466850d44b6a41a803e7a9268f3a545e487","src/helpers/helper_log.rs":"272f7c1f873b97974cce156c04281f2bd8c44ccc885b4c59dd2b43e8d7cc6ef6","src/helpers/helper_lookup.rs":"34e57dbe6a4c65afa8978d32db1b9adfb783990ec951b4833a9986a86cb38ff1","src/helpers/helper_raw.rs":"6b0b5b3774a1d5c3ebf30b1e0b8cac825f6ffb8a18cb9e08bd40786258e4b597","src/helpers/helper_with.rs":"554373544f1aff16799cde954e37a945e26b452414436f612e12b538ec8e1893","src/helpers/mod.rs":"f8c24abb40739935225acdfad97f4bc808eb1fec77d09fda1ff5779b632b7650","src/helpers/scripting.rs":"3716d77e6e11993741885a15dcddaedc11e076f0b5e9a0b844416d3fbb0a834c","src/json/mod.rs":"ef2fc8fe98e9761e2e2a4b2d2293bb29cdb689db2f44f939fc61c48c6b52f0a7","src/json/path.rs":"49b821765da4aa305e51478527898ad4038c3952c7f07c639e8b71a59732e34a","src/json/value.rs":"390ea4fa8b5131a3d00ff1c80d06359220f16d851a5e836192026ea32acbb02e","src/lib.rs":"9374528d680b4cefdfcef945529a5f9c6b03b22ba09503135cc18914ff621d56","src/local_vars.rs":"91d3a16bbfabe2eccecaa9a0dd866ebe88d70ce438d2f18581d1b7d231ba0644","src/macros.rs":"0e2d174bb155da5df279ba15ef65b92519ca890949acc8231c72196bc8364a7c","src/output.rs":"f85acedeb124a1d344c5f73b309bd32d925de5dbed701b5fdebcadbd42f3c7ad","src/partial.rs":"6362967d77d29eea5ba7000ec741774288f08afe7c685e9d28b801b603599401","src/registry.rs":"388ebf2e28734963cd04f6622109e009ab22f7377236f6042aa5441875b22cef","src/render.rs":"17594a82a37295d4887945f18dc12eebe261094078e699b53ff6b7e193fcf986","src/sources.rs":"46989eb76f36edff9dcb5d27488e8bd9c7ff1749f368a70e855f4808c58d7bcf","src/support.rs":"f9328a0674984fcc3c6e93e8a43ec63bf9b502176283f60a2d6ceb15ca34840a","src/template.rs":"5e275cd2adb00e4238607e5e6d7e7db209a1233b813df77e30ccc5df1991bc01","src/util.rs":"2ebc845de5ca47455442a1b6bd664565a52e29928e82c526fbfe56ed5196410f","tests/block_context.rs":"4dce11312d2b6c0c5c2f3104516e5567e5a370611e08f4055fa3653293580385","tests/data_helper.rs":"a7f9d1d42d5415ba1dba459840067acc1294f6f6057d9a5a13d9f7e19469e850","tests/embed.rs":"de85f16a7a0372cc0e150abe3487ae8180598532e4d73b05b4b107e7e4a0b05e","tests/escape.rs":"7b643675b7884a497d7008cda6e51809efea94a79d25996564b7771cfdbf1709","tests/helper_function_lifetime.rs":"635cbd0b44742539bdf36e803a19c6a1a698399f8b765415d53f28df1acfbc2b","tests/helper_macro.rs":"959cc218fa47c8b30835412c5b6b4f76c8387de49e9e2c73baa9a788f9564361","tests/helper_with_space.rs":"0aee174428b799998a9994b008485373a1b084bf4ea49ed455c890eb627f1ac1","tests/root_var.rs":"fda5b30bac1e692fb010f9f98e052d5a525420fece9dcc3821a4e5aeee3a8841","tests/subexpression.rs":"b36ab31adf45272ca984c0c5ed9497820ca072a8805444d69bd089b766786bb5","tests/template_names.rs":"4bbe6b48c974ae7ea1e61806794d846e2f0e8505e1568c5305fa2364dceef68a","tests/templates/hello.hbs":"4aca52692d2247a22c46856dbfd439a5c4edc47237e488ece5d01e9d8030e882","tests/whitespace.rs":"1cadfbe9cd8e2dd4ca7759fdcaf7fd05116b5e9ec59ca67722c41732fe89dfa3","wasm/LICENSE":"63b308fad3db82dc12067a8d7ff4b672fae97d12d0b4b3bb59179e27d640b3a4","wasm/README.md":"d67bad452550d34e9317fb8f4884b8bc07939fbb0dfdcf1be6bfce52a6851fa6","wasm/wapm.toml":"bdb286ccaa18c5c8aa0d2db25755aba9b0e3e83a59fc4d2334c1854933000ea1"},"package":"360d9740069b2f6cbb63ce2dbaa71a20d3185350cbb990d7bebeb9318415eb17"} \ No newline at end of file diff --git a/vendor/handlebars/CHANGELOG.md b/vendor/handlebars/CHANGELOG.md index 62045f53e..c3b79a657 100644 --- a/vendor/handlebars/CHANGELOG.md +++ b/vendor/handlebars/CHANGELOG.md @@ -1,5 +1,80 @@ # Change Log +## [4.3.3](https://github.com/sunng87/handlebars-rust/compare/4.3.2...4.3.3) - 2022-07-20 + +* [Fixed] Disable partial expression indentation with `{{~> partial}}` to + bring behavior closer in line with original javascript version. [#518] +* [Fixed] Support for using partial context together with partial parameters + [#520] + +## [4.3.2](https://github.com/sunng87/handlebars-rust/compare/4.3.1...4.3.2) - 2022-07-14 + +* [Added] Render functions that reuse `Context` for custom `std::io::Write`: + `render_with_context_to_write` and `render_template_with_context_to_write` + +## [4.3.1](https://github.com/sunng87/handlebars-rust/compare/4.3.0...4.3.1) - 2022-06-09 + +* [Added] Added support for `{{~{variable}~}}` syntax [#509] + +## [4.3.0](https://github.com/sunng87/handlebars-rust/compare/4.2.2...4.3.0) - 2022-05-18 + +* [Changed] update MSRV to 1.57 as rhai requires +* [Fixed] Reimplemented indent support for partial expression `{{> + partial}}`, which is introduced in 4.2.0. The new implementation is + aligned with original javascript version, that every text line + generated from partial are indented as `{{> partial}}` + does. `prevent_indent` will turn-off this feature. [#505] +* [Changed] changed error support library from quick_error to + thiserror + +## [4.2.2](https://github.com/sunng87/handlebars-rust/compare/4.2.1...4.2.2) - 2022-03-09 + +* [Fixed] Block param scope leaked into partials [#496] +* [Changed] Use Rust 2021 edition and update MSRV to 1.56 + +## [4.2.1](https://github.com/sunng87/handlebars-rust/compare/4.2.0...4.2.1) - 2022-01-17 + +* [Fixed] Nested partial `@partial-block` referencing issue [#488] +* [Fixed] Docs generation on docs.rs for `rust-embed` feature + +## [4.2.0](https://github.com/sunng87/handlebars-rust/compare/4.1.6...4.2.0) - 2022-01-05 + +* [Added] RustEmbed support for loading templates from [#484] +* [Fixed] Parser support for variables begins with digit [#479] +* [Changed] Keep indent whitespaces for partial expression `{{> + partial}}` as default in handlebarsjs. A new option `prevent_indent` + is provided on `Handlebars` to turn off this behaviour. [#486] +* [Changed] Update MSRV to 1.51 due to dependency changes + +## [4.1.6](https://github.com/sunng87/handlebars-rust/compare/4.1.5...4.1.6) - 2021-12-03 + +* [Added] Create `Context` from owned `serde_json::Value` [#477] + +## [4.1.5](https://github.com/sunng87/handlebars-rust/compare/4.1.4...4.1.5) - 2021-11-17 + +* [Fixed] Single-quote string literal is supported, again [#475] + +## [4.1.4](https://github.com/sunng87/handlebars-rust/compare/4.1.3...4.1.4) - 2021-11-06 + +* [Fixed] Corrected empty line stripping strategy [#473] + +## [4.1.3](https://github.com/sunng87/handlebars-rust/compare/4.1.2...4.1.3) - 2021-09-10 + +* [Added] `@last` variable for `each` block with object [#466] +* [Fixed] Missing whitespaces behind expression [#468] + +## [4.1.2](https://github.com/sunng87/handlebars-rust/compare/4.1.1...4.1.2) - 2021-08-11 + +* [Added] Support for generic types in `handlebars_helper!`. +* [Added] Getter and setter for rhai `Engine` from registry. +* [Fixed] Improve doc for `dev_mode` that it has to be enabled before + adding templates. + +## [4.1.1](https://github.com/sunng87/handlebars-rust/compare/4.1.0...4.1.1) - 2021-07-31 + +* [Changed] Update rhai to 1.0 [#455] +* [Fixed] Empty line stripping for partial include statement, and other corner cases [#458] + ## [4.1.0](https://github.com/sunng87/handlebars-rust/compare/4.0.1...4.1.0) - 2021-07-05 * [Added] export `StringOutput` as requested in #442 diff --git a/vendor/handlebars/Cargo.lock b/vendor/handlebars/Cargo.lock index 8fc6db06f..27cc86f9b 100644 --- a/vendor/handlebars/Cargo.lock +++ b/vendor/handlebars/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.15.2" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a2e47a1fbe209ee101dd6d61285226744c6c8d3c21c8dc878ba6cb9f467f3a" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" dependencies = [ "gimli", ] @@ -19,22 +19,11 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "796540673305a66d127804eef19ad696f1f204b8c1025aaca4958c17eab32877" -dependencies = [ - "getrandom 0.2.3", - "once_cell", - "version_check", -] - -[[package]] -name = "ahash" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43bb833f0bf979d8475d38fbf09ed3b8a55e1885fe93ad3f93239fc6a4f17b98" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" dependencies = [ - "getrandom 0.2.3", + "getrandom", "once_cell", "version_check", ] @@ -50,9 +39,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.41" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15af2628f6890fe2609a3b91bef4c83450512802e59489f9c1cb1fa5df064a61" +checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" [[package]] name = "arrayvec" @@ -63,6 +52,12 @@ dependencies = [ "nodrop", ] +[[package]] +name = "ascii" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf56136a5198c7b01a49e3afcbef6cf84597273d298f54432926024107b0109" + [[package]] name = "atty" version = "0.2.14" @@ -76,36 +71,30 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.60" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7815ea54e4d821e791162e078acbebfd6d8c8939cd559c9335dceb1c8ca7282" +checksum = "11a17d453482a265fd5f8479f2a3f405566e6ca627837aaddb85af8b1ab8ef61" dependencies = [ "addr2line", "cc", - "cfg-if 1.0.0", + "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", ] -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - [[package]] name = "bitflags" -version = "1.2.1" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "block-buffer" @@ -125,7 +114,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" dependencies = [ - "generic-array 0.14.4", + "generic-array 0.14.5", ] [[package]] @@ -139,9 +128,9 @@ dependencies = [ [[package]] name = "bstr" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90682c8d613ad3373e66de8c6411e0ae2ab2571e879d2efbf73558cc66f21279" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" dependencies = [ "lazy_static", "memchr", @@ -149,21 +138,11 @@ dependencies = [ "serde", ] -[[package]] -name = "buf_redux" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b953a6887648bb07a535631f2bc00fbdb2a2216f135552cb3f534ed136b9c07f" -dependencies = [ - "memchr", - "safemem", -] - [[package]] name = "bumpalo" -version = "3.7.0" +version = "3.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631" +checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" [[package]] name = "byte-tools" @@ -173,9 +152,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "bytemuck" -version = "1.7.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9966d2ab714d0f785dbac0a0396251a35280aeb42413281617d0209ab4898435" +checksum = "cdead85bdec19c194affaeeb670c0e41fe23de31459efd1c174d049269cf02cc" [[package]] name = "byteorder" @@ -185,85 +164,87 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" - -[[package]] -name = "bytes" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" [[package]] name = "cast" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57cdfa5d50aad6cb4d44dcab6101a7f79925bd59d82ca42f38a9856a28865374" +checksum = "4c24dab4283a142afa2fdca129b80ad2c6284e073930f964c3a1293c225ee39a" dependencies = [ "rustc_version", ] [[package]] name = "cc" -version = "1.0.68" +version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a72c244c1ff497a746a7e1fb3d14bd08420ecda70c8f25c7112f2781652d787" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" [[package]] name = "cfg-if" -version = "0.1.10" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] -name = "cfg-if" -version = "1.0.0" +name = "chunked_transfer" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "fff857943da45f546682664a79488be82e69e43c1a7a2307679ab9afb3a66d2e" [[package]] name = "clap" -version = "2.33.3" +version = "2.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" +checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" dependencies = [ "bitflags", "textwrap", "unicode-width", ] +[[package]] +name = "cmake" +version = "0.1.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8ad8cef104ac57b68b89df3208164d228503abbdce70f6880ffa3d970e7443a" +dependencies = [ + "cc", +] + [[package]] name = "cpp_demangle" -version = "0.3.2" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44919ecaf6f99e8e737bc239408931c9a01e9a6c74814fee8242dd2506b65390" +checksum = "eeaa953eaad386a53111e47172c2fedba671e5684c8dd601a5f474f4f118710f" dependencies = [ - "cfg-if 1.0.0", - "glob", + "cfg-if", ] [[package]] name = "cpufeatures" -version = "0.1.4" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed00c67cb5d0a7d64a44f6ad2668db7e7530311dd53ea79bcd4fb022c64911c8" +checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" dependencies = [ "libc", ] [[package]] name = "criterion" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab327ed7354547cc2ef43cbe20ef68b988e70b4b593cbd66a2a61733123a3d23" +checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10" dependencies = [ "atty", "cast", "clap", "criterion-plot", "csv", - "itertools 0.10.1", + "itertools", "lazy_static", "num-traits", "oorandom", @@ -280,42 +261,43 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e022feadec601fba1649cfa83586381a4ad31c6bf3a9ab7d408118b05dd9889d" +checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57" dependencies = [ "cast", - "itertools 0.9.0", + "itertools", ] [[package]] name = "crossbeam-channel" -version = "0.5.1" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9" +checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.9.5" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec02e091aa634e2c3ada4a392989e7c3116673ef0ac5b72232439094d73b7fd" +checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" dependencies = [ - "cfg-if 1.0.0", + "autocfg", + "cfg-if", "crossbeam-utils", "lazy_static", "memoffset", @@ -324,11 +306,11 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "lazy_static", ] @@ -340,7 +322,7 @@ checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" dependencies = [ "bstr", "csv-core", - "itoa", + "itoa 0.4.8", "ryu", "serde", ] @@ -356,9 +338,9 @@ dependencies = [ [[package]] name = "debugid" -version = "0.7.2" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91cf5a8c2f2097e2a32627123508635d47ce10563d999ec1a95addf08b502ba" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" dependencies = [ "uuid", ] @@ -378,7 +360,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" dependencies = [ - "generic-array 0.14.4", + "generic-array 0.14.5", ] [[package]] @@ -389,9 +371,9 @@ checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" [[package]] name = "env_logger" -version = "0.8.4" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" +checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" dependencies = [ "atty", "humantime", @@ -407,88 +389,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] -name = "fixedbitset" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37ab347416e802de484e4d03c7316c48f1ecb56574dfd4a46a80f173ce1de04d" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" -dependencies = [ - "matches", - "percent-encoding", -] - -[[package]] -name = "futures" -version = "0.3.15" +name = "fastrand" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7e43a803dae2fa37c1f6a8fe121e1f7bf9548b4dfc0522a42f34145dadfc27" +checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", + "instant", ] [[package]] -name = "futures-channel" -version = "0.3.15" +name = "findshlibs" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e682a68b29a882df0545c143dc3646daefe80ba479bcdede94d5a703de2871e2" +checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64" dependencies = [ - "futures-core", - "futures-sink", + "cc", + "lazy_static", + "libc", + "winapi", ] [[package]] -name = "futures-core" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0402f765d8a89a26043b889b26ce3c4679d268fa6bb22cd7c6aad98340e179d1" - -[[package]] -name = "futures-io" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acc499defb3b348f8d8f3f66415835a9131856ff7714bf10dadfc4ec4bdb29a1" - -[[package]] -name = "futures-sink" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a57bead0ceff0d6dde8f465ecd96c9338121bb7717d3e7b108059531870c4282" - -[[package]] -name = "futures-task" -version = "0.3.15" +name = "fixedbitset" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a16bef9fc1a4dddb5bee51c989e3fbba26569cbb0e31f5b303c184e3dd33dae" +checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" [[package]] -name = "futures-util" -version = "0.3.15" +name = "form_urlencoded" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "feb5c238d27e2bf94ffdfd27b2c29e3df4a68c4193bb6427384259e2bf191967" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" dependencies = [ - "autocfg", - "futures-core", - "futures-sink", - "futures-task", - "pin-project-lite", - "pin-utils", - "slab", + "matches", + "percent-encoding", ] [[package]] @@ -502,9 +436,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.4" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" +checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" dependencies = [ "typenum", "version_check", @@ -512,198 +446,76 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom" -version = "0.2.3" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" +checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "libc", - "wasi 0.10.2+wasi-snapshot-preview1", + "wasi", ] [[package]] name = "gimli" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e4075386626662786ddb0ec9081e7c7eeb1ba31951f447ca780ef9f5d568189" - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "h2" -version = "0.3.3" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "825343c4eef0b63f541f8903f395dc5beb362a979b5799a84062527ef1e37726" -dependencies = [ - "bytes 1.0.1", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] +checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" [[package]] name = "half" -version = "1.7.1" +version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62aca2aba2d62b4a7f5b33f3712cb1b0692779a56fb510499d5c0aa594daeaf3" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" [[package]] name = "handlebars" -version = "4.1.0" +version = "4.3.3" dependencies = [ "criterion", "env_logger", "log", - "maplit", "pest", "pest_derive", "pprof", - "quick-error 2.0.1", "rhai", + "rust-embed", "serde", "serde_derive", "serde_json", "tempfile", - "tokio", + "thiserror", + "time", + "tiny_http", "walkdir", - "warp", ] [[package]] name = "hashbrown" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" - -[[package]] -name = "headers" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0b7591fb62902706ae8e7aaff416b1b0fa2c0fd0878b46dc13baa3712d8a855" -dependencies = [ - "base64", - "bitflags", - "bytes 1.0.1", - "headers-core", - "http", - "mime", - "sha-1 0.9.6", - "time", -] - -[[package]] -name = "headers-core" -version = "0.2.0" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" -dependencies = [ - "http", -] +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" [[package]] name = "heck" -version = "0.3.3" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" [[package]] name = "hermit-abi" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" dependencies = [ "libc", ] -[[package]] -name = "http" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527e8c9ac747e28542699a951517aa9a6945af506cd1f2e1b53a576c17b6cc11" -dependencies = [ - "bytes 1.0.1", - "fnv", - "itoa", -] - -[[package]] -name = "http-body" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60daa14be0e0786db0f03a9e57cb404c9d756eed2b6c62b9ea98ec5743ec75a9" -dependencies = [ - "bytes 1.0.1", - "http", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a87b616e37e93c22fb19bcd386f02f3af5ea98a25670ad0fce773de23c5e68" - -[[package]] -name = "httpdate" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6456b8a6c8f33fee7d958fcd1b60d55b11940a79e63ae87013e6d22e26034440" - [[package]] name = "humantime" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" -[[package]] -name = "hyper" -version = "0.14.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07d6baa1b441335f3ce5098ac421fb6547c46dda735ca1bc6d0153c838f9dd83" -dependencies = [ - "bytes 1.0.1", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "idna" version = "0.2.3" @@ -717,9 +529,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.6.2" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" dependencies = [ "autocfg", "hashbrown", @@ -727,14 +539,14 @@ dependencies = [ [[package]] name = "inferno" -version = "0.10.6" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3cbcc228d2ad2e99328c2b19f38d80ec387ca6a29f778e40e32ca9f25448c3" +checksum = "16d4bde3a7105e59c66a4104cfe9606453af1c7a0eac78cb7d5bc263eb762a70" dependencies = [ - "ahash 0.6.3", + "ahash", "atty", "indexmap", - "itoa", + "itoa 1.0.1", "lazy_static", "log", "num-format", @@ -743,62 +555,41 @@ dependencies = [ "str_stack", ] -[[package]] -name = "input_buffer" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f97967975f448f1a7ddb12b0bc41069d09ed6a1c161a92687e057325db35d413" -dependencies = [ - "bytes 1.0.1", -] - [[package]] name = "instant" -version = "0.1.9" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61124eeebbd69b8190558df225adf7e4caafce0d743919e5d6b19652314ec5ec" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" -dependencies = [ - "either", + "cfg-if", ] [[package]] name = "itertools" -version = "0.9.0" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b" +checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" dependencies = [ "either", ] [[package]] -name = "itertools" -version = "0.10.1" +name = "itoa" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" -dependencies = [ - "either", -] +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" [[package]] name = "itoa" -version = "0.4.7" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" [[package]] name = "js-sys" -version = "0.3.51" +version = "0.3.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83bdfbace3a0e81a4253f73b49e960b053e396a11012cbd49b9b74d6a2b67062" +checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" dependencies = [ "wasm-bindgen", ] @@ -811,26 +602,27 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.97" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b8adadd720df158f4d70dfe7ccc6adb0472d7c55ca83445f6a5ab3e36f8fb6" +checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b" [[package]] name = "lock_api" -version = "0.4.4" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" dependencies = [ + "autocfg", "scopeguard", ] [[package]] name = "log" -version = "0.4.14" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -841,81 +633,41 @@ checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" [[package]] name = "matches" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" +checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" [[package]] name = "memchr" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] -name = "memmap" -version = "0.7.0" +name = "memmap2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +checksum = "057a3db23999c867821a7a59feb06a578fcb03685e983dff90daf9e7d24ac08f" dependencies = [ "libc", - "winapi", ] [[package]] name = "memoffset" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59accc507f1338036a0477ef61afdae33cde60840f4dfe481319ce3ad116ddf9" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" dependencies = [ "autocfg", ] -[[package]] -name = "mime" -version = "0.3.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" - -[[package]] -name = "mime_guess" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "miniz_oxide" -version = "0.4.4" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082" dependencies = [ "adler", - "autocfg", -] - -[[package]] -name = "mio" -version = "0.7.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c2bdb6314ec10835cd3293dd268473a835c02b7b352e788be788b3c6ca6bb16" -dependencies = [ - "libc", - "log", - "miow", - "ntapi", - "winapi", -] - -[[package]] -name = "miow" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" -dependencies = [ - "winapi", ] [[package]] @@ -924,35 +676,15 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" -[[package]] -name = "multipart" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050aeedc89243f5347c3e237e3e13dc76fbe4ae3742a57b94dc14f69acf76d4" -dependencies = [ - "buf_redux", - "httparse", - "log", - "mime", - "mime_guess", - "quick-error 1.2.3", - "rand 0.7.3", - "safemem", - "tempfile", - "twoway", -] - [[package]] name = "nix" -version = "0.17.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e4785f2c3b7589a0d0c1dd60285e1188adac4006e8abd6dd578e1567027363" +checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9" dependencies = [ "bitflags", - "cc", - "cfg-if 0.1.10", + "cfg-if", "libc", - "void", ] [[package]] @@ -961,15 +693,6 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" -[[package]] -name = "ntapi" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" -dependencies = [ - "winapi", -] - [[package]] name = "num-format" version = "0.4.0" @@ -977,42 +700,51 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bafe4179722c2894288ee77a9f044f02811c86af699344c498b0840c698a2465" dependencies = [ "arrayvec", - "itoa", + "itoa 0.4.8", ] [[package]] name = "num-traits" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" dependencies = [ "autocfg", ] [[package]] name = "num_cpus" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" dependencies = [ "hermit-abi", "libc", ] +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + [[package]] name = "object" -version = "0.25.3" +version = "0.28.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38f2be3697a57b4060074ff41b44c16870d916ad7877c17696e063257482bc7" +checksum = "e42c982f2d955fac81dd7e1d0e1426a7d702acd9c98d19ab01083a6a0328c424" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.8.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" +checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" [[package]] name = "oorandom" @@ -1034,27 +766,25 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "parking_lot" -version = "0.11.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb" +checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" dependencies = [ - "instant", "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" -version = "0.8.3" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018" +checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" dependencies = [ - "cfg-if 1.0.0", - "instant", + "cfg-if", "libc", "redox_syscall", "smallvec", - "winapi", + "windows-sys", ] [[package]] @@ -1103,151 +833,120 @@ checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d" dependencies = [ "maplit", "pest", - "sha-1 0.8.2", + "sha-1", ] [[package]] name = "petgraph" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "467d164a6de56270bd7c4d070df81d07beace25012d5103ced4e9ff08d6afdb7" +checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f" dependencies = [ "fixedbitset", "indexmap", ] [[package]] -name = "pin-project" -version = "1.0.7" +name = "plotters" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7509cc106041c40a4518d2af7a61530e1eed0e6285296a3d8c5472806ccc4a4" +checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c950132583b500556b1efd71d45b319029f2b71518d979fcc208e16b42426f" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0e1f259c92177c30a4c9d177246edd0a3568b25756a977d0632cf8fa37e905" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "plotters" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", ] [[package]] name = "plotters-backend" -version = "0.3.0" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b07fffcddc1cb3a1de753caa4e4df03b79922ba43cf882acc1bdd7e8df9f4590" +checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" [[package]] name = "plotters-svg" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b38a02e23bd9604b842a812063aec4ef702b57989c37b655254bb61c471ad211" +checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" dependencies = [ "plotters-backend", ] [[package]] name = "pprof" -version = "0.3.20" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "937e4766a8d473f9dd3eb318c654dec77d6715a87ab50081d6e5cfceea73c105" +checksum = "1bba88ee898c63351101af3e60c66c5398c517681ce533eef8caff10ecf11ec1" dependencies = [ "backtrace", + "cfg-if", + "findshlibs", "inferno", - "lazy_static", "libc", "log", "nix", + "once_cell", "parking_lot", "prost", "prost-build", "prost-derive", + "smallvec", "symbolic-demangle", "tempfile", "thiserror", ] -[[package]] -name = "ppv-lite86" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" - [[package]] name = "proc-macro2" -version = "1.0.27" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" +checksum = "9027b48e9d4c9175fa2218adf3557f91c1137021739951d4932f5f8268ac48aa" dependencies = [ "unicode-xid", ] [[package]] name = "prost" -version = "0.6.1" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce49aefe0a6144a45de32927c77bd2859a5f7677b55f220ae5b744e87389c212" +checksum = "bc03e116981ff7d8da8e5c220e374587b98d294af7ba7dd7fda761158f00086f" dependencies = [ - "bytes 0.5.6", + "bytes", "prost-derive", ] [[package]] name = "prost-build" -version = "0.6.1" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b10678c913ecbd69350e8535c3aef91a8676c0773fc1d7b95cdd196d7f2f26" +checksum = "65a1118354442de7feb8a2a76f3d80ef01426bd45542c8c1fdffca41a758f846" dependencies = [ - "bytes 0.5.6", + "bytes", + "cfg-if", + "cmake", "heck", - "itertools 0.8.2", + "itertools", + "lazy_static", "log", "multimap", "petgraph", "prost", "prost-types", + "regex", "tempfile", "which", ] [[package]] name = "prost-derive" -version = "0.6.1" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537aa19b95acde10a12fec4301466386f757403de4cd4e5b4fa78fb5ecb18f72" +checksum = "7b670f45da57fb8542ebdbb6105a925fe571b67f9e7ed9f47a06a84e72b4e7cc" dependencies = [ "anyhow", - "itertools 0.8.2", + "itertools", "proc-macro2", "quote", "syn", @@ -1255,130 +954,37 @@ dependencies = [ [[package]] name = "prost-types" -version = "0.6.1" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1834f67c0697c001304b75be76f67add9c89742eda3a085ad8ee0bb38c3417aa" +checksum = "2d0a014229361011dc8e69c8a1ec6c2e8d0f2af7c91e3ea3f5b2170298461e68" dependencies = [ - "bytes 0.5.6", + "bytes", "prost", ] -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - -[[package]] -name = "quick-error" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" - [[package]] name = "quick-xml" -version = "0.20.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26aab6b48e2590e4a64d1ed808749ba06257882b461d01ca71baeb747074a6dd" +checksum = "8533f14c8382aaad0d592c812ac3b826162128b65662331e1127b45c3d18536b" dependencies = [ "memchr", ] [[package]] name = "quote" -version = "1.0.9" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" dependencies = [ "proc-macro2", ] -[[package]] -name = "rand" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom 0.1.16", - "libc", - "rand_chacha 0.2.2", - "rand_core 0.5.1", - "rand_hc 0.2.0", -] - -[[package]] -name = "rand" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.2", - "rand_hc 0.3.0", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" -dependencies = [ - "ppv-lite86", - "rand_core 0.5.1", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.2", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom 0.1.16", -] - -[[package]] -name = "rand_core" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7" -dependencies = [ - "getrandom 0.2.3", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", -] - -[[package]] -name = "rand_hc" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" -dependencies = [ - "rand_core 0.6.2", -] - [[package]] name = "rayon" -version = "1.5.1" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06aca804d41dbc8ba42dfd964f0d01334eceb64314b9ecf7c5fad5188a06d90" +checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" dependencies = [ "autocfg", "crossbeam-deque", @@ -1388,31 +994,30 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.9.1" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78120e2c850279833f1dd3582f730c4ab53ed95aeaaaa862a2a5c71b1656d8e" +checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" dependencies = [ "crossbeam-channel", "crossbeam-deque", "crossbeam-utils", - "lazy_static", "num_cpus", ] [[package]] name = "redox_syscall" -version = "0.2.8" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "742739e41cd49414de871ea5e549afb7e2a3ac77b589bcbebe8c82fab37147fc" +checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" dependencies = [ "bitflags", ] [[package]] name = "regex" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" +checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" dependencies = [ "aho-corasick", "memchr", @@ -1442,20 +1047,21 @@ dependencies = [ [[package]] name = "rgb" -version = "0.8.27" +version = "0.8.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fddb3b23626145d1776addfc307e1a1851f60ef6ca64f376bcb889697144cf0" +checksum = "e74fdc210d8f24a7dbfedc13b04ba5764f5232754ccebfdf5fff1bad791ccbc6" dependencies = [ "bytemuck", ] [[package]] name = "rhai" -version = "0.20.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d862e125236e74d2a5033e88b9cb9404010a6a39516a388f570975494fe73bce" +checksum = "9f06953bb8b9e4307cb7ccc0d9d018e2ddd25a30d32831f631ce4fe8f17671f7" dependencies = [ - "ahash 0.7.4", + "ahash", + "bitflags", "instant", "num-traits", "rhai_codegen", @@ -1466,41 +1072,69 @@ dependencies = [ [[package]] name = "rhai_codegen" -version = "0.3.6" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643fd67d19aafd45a9e335afe4183dc58ba0cc6a1f43fbe34c7d92c041cdcafc" +checksum = "faa0ff1c9dc19c9f8bba510a2a75d3f0449f6233570c2672c7e31c692a11a59a" dependencies = [ "proc-macro2", "quote", "syn", ] +[[package]] +name = "rust-embed" +version = "6.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a17e5ac65b318f397182ae94e532da0ba56b88dd1200b774715d36c4943b1c3" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "6.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e763e24ba2bf0c72bc6be883f967f794a019fafd1b86ba1daff9c91a7edd30" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "syn", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "7.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756feca3afcbb1487a1d01f4ecd94cf8ec98ea074c55a69e7136d29fb6166029" +dependencies = [ + "sha2", + "walkdir", +] + [[package]] name = "rustc-demangle" -version = "0.1.19" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "410f7acf3cb3a44527c5d9546bad4bf4e6c460915d5f9f2fc524498bfe8f70ce" +checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" [[package]] name = "rustc_version" -version = "0.3.3" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ "semver", ] [[package]] name = "ryu" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" - -[[package]] -name = "safemem" -version = "0.3.3" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" +checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" [[package]] name = "same-file" @@ -1511,12 +1145,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - [[package]] name = "scopeguard" version = "1.1.0" @@ -1525,36 +1153,24 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "semver" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver-parser" -version = "0.10.2" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" -dependencies = [ - "pest", -] +checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" [[package]] name = "serde" -version = "1.0.126" +version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" dependencies = [ "serde_derive", ] [[package]] name = "serde_cbor" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e18acfa2f90e8b735b2836ab8d538de304cbb6729a7360729ea5a895d15a622" +checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" dependencies = [ "half", "serde", @@ -1562,9 +1178,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.126" +version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" dependencies = [ "proc-macro2", "quote", @@ -1573,23 +1189,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.64" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" +checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edfa57a7f8d9c1d260a549e7224100f6c43d43f9103e06dd8b4095a9b2b43ce9" -dependencies = [ - "form_urlencoded", - "itoa", + "itoa 1.0.1", "ryu", "serde", ] @@ -1607,47 +1211,33 @@ dependencies = [ ] [[package]] -name = "sha-1" -version = "0.9.6" +name = "sha2" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c4cfa741c5832d0ef7fab46cabed29c2aae926db0b11bb2069edd8db5e64e16" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" dependencies = [ "block-buffer 0.9.0", - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "digest 0.9.0", "opaque-debug 0.3.0", ] -[[package]] -name = "slab" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f173ac3d1a7e3b28003f40de0b5ce7fe2710f9b9dc3fc38664cebee46b3b6527" - [[package]] name = "smallvec" -version = "1.6.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" +checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" [[package]] name = "smartstring" -version = "0.2.6" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ada87540bf8ef4cf8a1789deb175626829bb59b1fefd816cf7f7f55efcdbae9" +checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29" dependencies = [ + "autocfg", "static_assertions", -] - -[[package]] -name = "socket2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e3dfc207c526015c632472a77be09cf1b6e46866581aecae5cc38fb4235dea2" -dependencies = [ - "libc", - "winapi", + "version_check", ] [[package]] @@ -1670,21 +1260,21 @@ checksum = "9091b6114800a5f2141aee1d1b9d6ca3592ac062dc5decb3764ec5895a47b4eb" [[package]] name = "symbolic-common" -version = "8.2.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8e101b55bbcf228c855fa34fc4312e4f58b4a3251f1298bc0f97b71557815d" +checksum = "9ea2ab8b85d27d49d184438b4b77fbd521b385cc9c5c802f60e784f2df25a03d" dependencies = [ "debugid", - "memmap", + "memmap2", "stable_deref_trait", "uuid", ] [[package]] name = "symbolic-demangle" -version = "8.2.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e257e28c2cbcf60a0c21089d32ff8b6cdc7efa6125b13693d29e8986aa1cd99" +checksum = "7939b15a1c62633d1fce17f8a7b668312eaa2d3b117bf4ced5e6e77870c43b6a" dependencies = [ "cpp_demangle", "rustc-demangle", @@ -1693,9 +1283,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.73" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f71489ff30030d2ae598524f61326b902466f72a0fb1a8564c001cc63425bcc7" +checksum = "a07e33e919ebcd69113d5be0e4d70c5707004ff45188910106854f38b960df4a" dependencies = [ "proc-macro2", "quote", @@ -1704,13 +1294,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22" +checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", + "fastrand", "libc", - "rand 0.8.3", "redox_syscall", "remove_dir_all", "winapi", @@ -1718,9 +1308,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" dependencies = [ "winapi-util", ] @@ -1736,18 +1326,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.25" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa6f76457f59514c7eeb4e59d891395fab0b2fd1d40723ae737d64153392e9c6" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.25" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a36768c0fbf1bb15eca10defa29526bda730a2376c2ab4393ccfa16fb1a318d" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" dependencies = [ "proc-macro2", "quote", @@ -1756,170 +1346,66 @@ dependencies = [ [[package]] name = "time" -version = "0.1.43" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd" dependencies = [ + "itoa 1.0.1", "libc", - "winapi", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ + "num_threads", "serde", - "serde_json", -] - -[[package]] -name = "tinyvec" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b5220f05bb7de7f3f53c7c065e1199b3172696fe2db9f9c4d8ad9b4ee74c342" -dependencies = [ - "tinyvec_macros", + "time-macros", ] [[package]] -name = "tinyvec_macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" - -[[package]] -name = "tokio" -version = "1.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aea337f72e96efe29acc234d803a5981cd9a2b6ed21655cd7fc21cfe021e8ec7" -dependencies = [ - "autocfg", - "bytes 1.0.1", - "libc", - "memchr", - "mio", - "num_cpus", - "pin-project-lite", - "tokio-macros", -] - -[[package]] -name = "tokio-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c49e3df43841dafb86046472506755d8501c5615673955f6aa17181125d13c37" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-stream" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8864d706fdb3cc0843a49647ac892720dac98a6eeb818b77190592cf4994066" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-tungstenite" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1a5f475f1b9d077ea1017ecbc60890fda8e54942d680ca0b1d2b47cfa2d861b" -dependencies = [ - "futures-util", - "log", - "pin-project", - "tokio", - "tungstenite", -] - -[[package]] -name = "tokio-util" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1caa0b0c8d94a049db56b5acf8cba99dc0623aab1b26d5b5f5e2d945846b3592" -dependencies = [ - "bytes 1.0.1", - "futures-core", - "futures-sink", - "log", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tower-service" -version = "0.3.1" +name = "time-macros" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" +checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792" [[package]] -name = "tracing" -version = "0.1.26" +name = "tiny_http" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09adeb8c97449311ccd28a427f96fb563e7fd31aabf994189879d9da2394b89d" +checksum = "e0d6ef4e10d23c1efb862eecad25c5054429a71958b4eeef85eb5e7170b477ca" dependencies = [ - "cfg-if 1.0.0", + "ascii", + "chunked_transfer", "log", - "pin-project-lite", - "tracing-core", + "time", + "url", ] [[package]] -name = "tracing-core" -version = "0.1.18" +name = "tinytemplate" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9ff14f98b1a4b289c6248a023c1c2fa1491062964e9fed67ab29c4e4da4a052" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" dependencies = [ - "lazy_static", + "serde", + "serde_json", ] [[package]] -name = "try-lock" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" - -[[package]] -name = "tungstenite" -version = "0.12.0" +name = "tinyvec" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ada8297e8d70872fa9a551d93250a9f407beb9f37ef86494eb20012a2ff7c24" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" dependencies = [ - "base64", - "byteorder", - "bytes 1.0.1", - "http", - "httparse", - "input_buffer", - "log", - "rand 0.8.3", - "sha-1 0.9.6", - "url", - "utf-8", + "tinyvec_macros", ] [[package]] -name = "twoway" -version = "0.1.8" +name = "tinyvec_macros" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b11b2b5241ba34be09c3cc85a36e56e48f9888862e19cedf23336d35316ed1" -dependencies = [ - "memchr", -] +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "typenum" -version = "1.13.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" +checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" [[package]] name = "ucd-trie" @@ -1927,23 +1413,11 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" -[[package]] -name = "unicase" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" -dependencies = [ - "version_check", -] - [[package]] name = "unicode-bidi" -version = "0.3.5" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeb8be209bb1c96b7c177c7420d26e04eccacb0eeae6b980e35fcb74678107e0" -dependencies = [ - "matches", -] +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-normalization" @@ -1954,23 +1428,17 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-segmentation" -version = "1.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" - [[package]] name = "unicode-width" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" [[package]] name = "unicode-xid" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" [[package]] name = "url" @@ -1984,29 +1452,17 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - [[package]] name = "uuid" -version = "0.8.2" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" +checksum = "dd6469f4314d5f1ffec476e05f17cc9a78bc7a27a6a857842170bdf8d6f98d2f" [[package]] name = "version_check" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" - -[[package]] -name = "void" -version = "1.0.2" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "walkdir" @@ -2019,51 +1475,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "want" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" -dependencies = [ - "log", - "try-lock", -] - -[[package]] -name = "warp" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "332d47745e9a0c38636dbd454729b147d16bd1ed08ae67b3ab281c4506771054" -dependencies = [ - "bytes 1.0.1", - "futures", - "headers", - "http", - "hyper", - "log", - "mime", - "mime_guess", - "multipart", - "percent-encoding", - "pin-project", - "scoped-tls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-stream", - "tokio-tungstenite", - "tokio-util", - "tower-service", - "tracing", -] - -[[package]] -name = "wasi" -version = "0.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - [[package]] name = "wasi" version = "0.10.2+wasi-snapshot-preview1" @@ -2072,19 +1483,19 @@ checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" [[package]] name = "wasm-bindgen" -version = "0.2.74" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" +checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.74" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" +checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" dependencies = [ "bumpalo", "lazy_static", @@ -2097,9 +1508,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.74" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" +checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2107,9 +1518,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.74" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" +checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" dependencies = [ "proc-macro2", "quote", @@ -2120,15 +1531,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.74" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" [[package]] name = "web-sys" -version = "0.3.51" +version = "0.3.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e828417b379f3df7111d3a2a9e5753706cae29c41f7c4029ee9fd77f3e09e582" +checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" dependencies = [ "js-sys", "wasm-bindgen", @@ -2136,10 +1547,12 @@ dependencies = [ [[package]] name = "which" -version = "3.1.1" +version = "4.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d011071ae14a2f6671d0b74080ae0cd8ebf3a6f8c9589a2cd45f23126fe29724" +checksum = "5c4fb54e6113b6a8772ee41c3404fb0301ac79604489467e0a9ce1f3e97c24ae" dependencies = [ + "either", + "lazy_static", "libc", ] @@ -2173,3 +1586,46 @@ name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" diff --git a/vendor/handlebars/Cargo.toml b/vendor/handlebars/Cargo.toml index f46e0bd13..f40384c26 100644 --- a/vendor/handlebars/Cargo.toml +++ b/vendor/handlebars/Cargo.toml @@ -3,29 +3,45 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] -edition = "2018" +edition = "2021" +rust-version = "1.57" name = "handlebars" -version = "4.1.0" +version = "4.3.3" authors = ["Ning Sun "] description = "Handlebars templating implemented in Rust." homepage = "https://github.com/sunng87/handlebars-rust" documentation = "https://docs.rs/crate/handlebars/" readme = "README.md" -keywords = ["handlebars", "templating", "web"] -categories = ["template-engine", "web-programming"] +keywords = [ + "handlebars", + "templating", + "web", +] +categories = [ + "template-engine", + "web-programming", +] license = "MIT" repository = "https://github.com/sunng87/handlebars-rust" +resolver = "2" + [package.metadata.docs.rs] -features = ["dir_source", "script_helper"] -rustdoc-args = ["--cfg", "docsrs"] +features = [ + "dir_source", + "script_helper", + "rust-embed", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] [lib] name = "handlebars" @@ -35,9 +51,14 @@ path = "src/lib.rs" name = "handlebars-cli" path = "src/cli.rs" +[[example]] +name = "script" +required-features = ["script_helper"] + [[bench]] name = "bench" harness = false + [dependencies.log] version = "0.4.0" @@ -47,12 +68,16 @@ version = "2.1.0" [dependencies.pest_derive] version = "2.1.0" -[dependencies.quick-error] -version = "2.0" - [dependencies.rhai] -version = "0.20" -features = ["sync", "serde"] +version = "1.6" +features = [ + "sync", + "serde", +] +optional = true + +[dependencies.rust-embed] +version = "6.3.0" optional = true [dependencies.serde] @@ -61,17 +86,18 @@ version = "1.0.0" [dependencies.serde_json] version = "1.0.39" +[dependencies.thiserror] +version = "1" + [dependencies.walkdir] version = "2.2.3" optional = true + [dev-dependencies.criterion] version = "0.3" [dev-dependencies.env_logger] -version = "0.8" - -[dev-dependencies.maplit] -version = "1.0.0" +version = "0.9" [dev-dependencies.serde_derive] version = "1.0.75" @@ -79,20 +105,29 @@ version = "1.0.75" [dev-dependencies.tempfile] version = "3.0.0" -[dev-dependencies.tokio] -version = "1" -features = ["macros", "rt-multi-thread"] +[dev-dependencies.time] +version = "0.3.7" +features = [ + "serde", + "formatting", + "parsing", +] -[dev-dependencies.warp] -version = "0.3" +[dev-dependencies.tiny_http] +version = "0.11" [features] default = [] dir_source = ["walkdir"] no_logging = [] script_helper = ["rhai"] + [target."cfg(unix)".dev-dependencies.pprof] -version = "0.3.13" -features = ["flamegraph", "protobuf"] +version = "0.10" +features = [ + "flamegraph", + "prost-codec", +] + [badges.maintenance] status = "actively-developed" diff --git a/vendor/handlebars/README.md b/vendor/handlebars/README.md index 4a9c41827..18d21abfb 100644 --- a/vendor/handlebars/README.md +++ b/vendor/handlebars/README.md @@ -4,16 +4,11 @@ handlebars-rust [Handlebars templating language](https://handlebarsjs.com) implemented in Rust and for Rust. -Handlebars-rust is the template engine that renders the official Rust website -[rust-lang.org](https://www.rust-lang.org), [its -book](https://doc.rust-lang.org/book/). - -[![Build Status](https://travis-ci.org/sunng87/handlebars-rust.svg?branch=master)](https://travis-ci.org/sunng87/handlebars-rust) -[![](https://meritbadge.herokuapp.com/handlebars)](https://crates.io/crates/handlebars) +[![CI](https://github.com/sunng87/handlebars-rust/actions/workflows/main.yml/badge.svg)](https://github.com/sunng87/handlebars-rust/actions/workflows/main.yml) +[![](https://img.shields.io/crates/v/handlebars)](https://crates.io/crates/handlebars) [![](https://img.shields.io/crates/d/handlebars.svg)](https://crates.io/crates/handlebars) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) [![Docs](https://docs.rs/handlebars/badge.svg)](https://docs.rs/crate/handlebars/) -![rustc](https://img.shields.io/badge/rustc-1.50+-lightgray.svg) [![Donate](https://img.shields.io/badge/donate-liberapay-yellow.svg)](https://liberapay.com/Sunng/donate) ## Getting Started @@ -55,6 +50,8 @@ Examples are provided in source tree to demo usage of various api. to use custom helpers. * [render_file](https://github.com/sunng87/handlebars-rust/blob/master/examples/render_file.rs) similar to render, but render to file instead of string +* [helper_macro](https://github.com/sunng87/handlebars-rust/blob/master/examples/helper_macro.rs) + demos usage of `handlebars_helper!` to simplify helper development * [partials](https://github.com/sunng87/handlebars-rust/blob/master/examples/partials.rs) template inheritance with handlebars * [decorator](https://github.com/sunng87/handlebars-rust/blob/master/examples/decorator.rs) @@ -71,7 +68,7 @@ Examples are provided in source tree to demo usage of various api. ## Minimum Rust Version Policy Handlebars will track Rust nightly and stable channel. When dropping -support for previous stable versions, I will bump **major** version +support for previous stable versions, I will bump **patch** version and clarify in CHANGELOG. ## Document @@ -133,7 +130,7 @@ And using it in your template: {{hex 16}} ``` -By default, handlebars-rust ships [additional helpers](https://github.com/sunng87/handlebars-rust/blob/master/src/helpers/helper_boolean.rs#L5) +By default, handlebars-rust ships [additional helpers](https://github.com/sunng87/handlebars-rust/blob/master/src/helpers/helper_extras.rs#L6) (compared with original js version) that is useful when working with `if`. @@ -146,7 +143,7 @@ moment, and can change in future. Every time I look into a templating system, I will investigate its support for [template -inheritance](https://docs.djangoproject.com/en/1.9/ref/templates/language/#template-inheritance). +inheritance](https://docs.djangoproject.com/en/3.2/ref/templates/language/#template-inheritance). Template include is not sufficient for template reuse. In most cases you will need a skeleton of page as parent (header, footer, etc.), and @@ -164,6 +161,13 @@ loaded from files or directory. This can be handy for template development. Handlebars 3.0 can be used in WebAssembly projects. +#### Fully scriptable + +With [rhai](https://github.com/rhaiscript/rhai) script support, you +can implement your own helper with the scripting language. Together +with the template lanaguage itself, template development can be fully +scriptable without changing rust code. + ## Related Projects ### Web frameworks @@ -174,7 +178,7 @@ Handlebars 3.0 can be used in WebAssembly projects. example](https://github.com/seanmonstar/warp/blob/master/examples/handlebars_template.rs) * Tower-web: [Built-in](https://github.com/carllerche/tower-web) * Actix: [handlebars - example](https://github.com/actix/examples/blob/master/template_engines/handlebars/src/main.rs) + example](https://github.com/actix/examples/blob/master/templating/handlebars/src/main.rs) * Tide: [tide-handlebars](https://github.com/No9/tide-handlebars) ### Adopters diff --git a/vendor/handlebars/examples/dev_mode.rs b/vendor/handlebars/examples/dev_mode.rs index 99017474f..3256eed37 100644 --- a/vendor/handlebars/examples/dev_mode.rs +++ b/vendor/handlebars/examples/dev_mode.rs @@ -2,10 +2,9 @@ use std::sync::Arc; use handlebars::Handlebars; use serde_json::json; -use warp::{self, Filter}; +use tiny_http::{Response, Server}; -#[tokio::main] -async fn main() { +fn handlebars() -> Handlebars<'static> { let mut reg = Handlebars::new(); // enable dev mode for template reloading reg.set_dev_mode(true); @@ -14,14 +13,19 @@ async fn main() { reg.register_template_file("tpl", "./examples/dev_mode/template.hbs") .unwrap(); - let hbs = Arc::new(reg); - let route = warp::get().map(move || { + reg +} + +fn main() { + let hbs = Arc::new(handlebars()); + + let server = Server::http("127.0.0.1:3030").expect("Failed to start demo server."); + println!("Edit ./examples/dev_mode/template.hbs and request http://localhost:3030 to see the change on the fly."); + + for req in server.incoming_requests() { let result = hbs .render("tpl", &json!({"model": "t14s", "brand": "Thinkpad"})) .unwrap_or_else(|e| e.to_string()); - warp::reply::html(result) - }); - - println!("Edit ./examples/dev_mode/template.hbs and request http://localhost:3030 to see the change on the run."); - warp::serve(route).run(([127, 0, 0, 1], 3030)).await; + req.respond(Response::from_string(result)).unwrap(); + } } diff --git a/vendor/handlebars/examples/error.rs b/vendor/handlebars/examples/error.rs index 3fb874e2b..ed0f7c423 100644 --- a/vendor/handlebars/examples/error.rs +++ b/vendor/handlebars/examples/error.rs @@ -3,11 +3,44 @@ extern crate handlebars; #[macro_use] extern crate serde_json; -use std::error::Error; +use std::error::Error as StdError; -use handlebars::Handlebars; +use handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError}; +use thiserror::Error; -fn main() -> Result<(), Box> { +#[derive(Debug, Error)] +pub enum HelperError { + #[error("db error")] + DbError, + #[error("api error")] + ApiError, +} + +/// A helper that raise error according to parameters +pub fn error_helper( + h: &Helper, + _: &Handlebars, + _: &Context, + _: &mut RenderContext, + _: &mut dyn Output, +) -> Result<(), RenderError> { + let param = h + .param(0) + .ok_or(RenderError::new("Param 0 is required for error helper."))?; + match param.value().as_str() { + Some("db") => Err(RenderError::from_error( + "helper error", + HelperError::DbError, + )), + Some("api") => Err(RenderError::from_error( + "helper error", + HelperError::ApiError, + )), + _ => Ok(()), + } +} + +fn main() -> Result<(), Box> { env_logger::init(); let mut handlebars = Handlebars::new(); @@ -36,5 +69,18 @@ fn main() -> Result<(), Box> { println!("{}", be1.source().unwrap()); println!("{:?}", be1.source().unwrap().source()); + // process error generated in helper + handlebars.register_helper("err", Box::new(error_helper)); + let e2 = handlebars + .render_template("{{err \"db\"}}", &json!({})) + .unwrap_err(); + // down-casting the error to user defined type + match e2.source().and_then(|e| e.downcast_ref::()) { + Some(HelperError::DbError) => { + println!("Detected error from helper: db error",) + } + _ => {} + } + Ok(()) } diff --git a/vendor/handlebars/examples/helper_macro.rs b/vendor/handlebars/examples/helper_macro.rs new file mode 100644 index 000000000..dcc6ea31a --- /dev/null +++ b/vendor/handlebars/examples/helper_macro.rs @@ -0,0 +1,63 @@ +use std::error::Error; + +use handlebars::{handlebars_helper, Handlebars, JsonRender}; +use serde_json::{json, Value}; +use time::format_description::parse; +use time::OffsetDateTime; + +// define a helper using helper +// a date format helper accept an `OffsetDateTime` as parameter +handlebars_helper!(date: |dt: OffsetDateTime| dt.format(&parse("[year]-[month]-[day]").unwrap()).unwrap()); + +// a helper returns number of provided parameters +handlebars_helper!(nargs: |*args| args.len()); + +// a helper joins all values, using both hash and parameters +handlebars_helper!(join: |{sep:str=","}, *args| + args.iter().map(|a| a.render()).collect::>().join(sep) +); + +handlebars_helper!(isdefined: |v: Value| !v.is_null()); + +// a helper provides format +handlebars_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}| + dt.format(&parse(fmt).unwrap()).unwrap() +); + +fn main() -> Result<(), Box> { + // create the handlebars registry + let mut handlebars = Handlebars::new(); + + handlebars.register_helper("date", Box::new(date)); + handlebars.register_helper("date2", Box::new(date2)); + handlebars.register_helper("nargs", Box::new(nargs)); + handlebars.register_helper("join", Box::new(join)); + handlebars.register_helper("isdefined", Box::new(isdefined)); + + let data = OffsetDateTime::now_utc(); + + println!("{}", handlebars.render_template("{{date this}}", &data)?); + println!("{}", handlebars.render_template("{{date2 this}}", &data)?); + println!( + "{}", + handlebars.render_template("{{date2 this fmt=\"[day]/[month]/[year]\"}}", &data)? + ); + + println!("{}", handlebars.render_template("{{nargs 1 2 3 4}}", &())?); + + println!( + "{}", + handlebars.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())? + ); + + println!( + "{}", + handlebars.render_template( + r#"{{isdefined a}} {{isdefined b}} +{{#if (isdefined a)}}a{{/if}} {{#if (isdefined b)}}b{{/if}}"#, + &json!({"a": 1}) + )? + ); + + Ok(()) +} diff --git a/vendor/handlebars/examples/partials.rs b/vendor/handlebars/examples/partials.rs index 80b20c2f7..017dd04b7 100644 --- a/vendor/handlebars/examples/partials.rs +++ b/vendor/handlebars/examples/partials.rs @@ -1,9 +1,8 @@ extern crate env_logger; extern crate handlebars; -#[macro_use] -extern crate maplit; use handlebars::Handlebars; +use serde_json::json; use std::error::Error; fn main() -> Result<(), Box> { @@ -15,14 +14,14 @@ fn main() -> Result<(), Box> { handlebars.register_template_file("base0", "./examples/partials/base0.hbs")?; handlebars.register_template_file("base1", "./examples/partials/base1.hbs")?; - let data0 = btreemap! { - "title".to_string() => "example 0".to_string(), - "parent".to_string() => "base0".to_string() - }; - let data1 = btreemap! { - "title".to_string() => "example 1".to_string(), - "parent".to_string() => "base1".to_string() - }; + let data0 = json!({ + "title": "example 0", + "parent": "base0" + }); + let data1 = json!({ + "title": "example 1", + "parent": "base1" + }); println!("Page 0"); println!("{}", handlebars.render("template", &data0)?); diff --git a/vendor/handlebars/examples/script.rs b/vendor/handlebars/examples/script.rs index bedd426cd..de89fa482 100644 --- a/vendor/handlebars/examples/script.rs +++ b/vendor/handlebars/examples/script.rs @@ -5,7 +5,6 @@ use std::error::Error; #[macro_use] extern crate serde_json; -#[cfg(feature = "script_helper")] fn main() -> Result<(), Box> { let mut handlebars = Handlebars::new(); @@ -31,9 +30,3 @@ fn main() -> Result<(), Box> { println!("{}", handlebars.render("tpl", &data)?); Ok(()) } - -#[cfg(not(feature = "script_helper"))] -fn main() -> Result<(), Box> { - println!("Please enable feature flag script_helper for this example"); - Ok(()) -} diff --git a/vendor/handlebars/release.toml b/vendor/handlebars/release.toml index e0f365aa1..6ee7a8383 100644 --- a/vendor/handlebars/release.toml +++ b/vendor/handlebars/release.toml @@ -1,4 +1,6 @@ sign-commit = true +sign-tag = true +dev-version = true pre-release-replacements = [ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}", prerelease=false}, {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", prerelease=false}, diff --git a/vendor/handlebars/src/context.rs b/vendor/handlebars/src/context.rs index 10e15fd90..86f99ba4d 100644 --- a/vendor/handlebars/src/context.rs +++ b/vendor/handlebars/src/context.rs @@ -45,7 +45,7 @@ fn parse_json_visitor<'a, 'reg>( for path_seg in relative_path { match path_seg { PathSeg::Named(the_path) => { - if let Some((holder, base_path)) = get_in_block_params(&block_contexts, the_path) { + if let Some((holder, base_path)) = get_in_block_params(block_contexts, the_path) { with_block_param = Some((holder, base_path)); } break; @@ -171,10 +171,7 @@ impl Context { block_contexts: &VecDeque>, ) -> Result, RenderError> { // always use absolute at the moment until we get base_value lifetime issue fixed - let resolved_visitor = parse_json_visitor(&relative_path, block_contexts, true); - - // debug logging - debug!("Accessing context value: {:?}", resolved_visitor); + let resolved_visitor = parse_json_visitor(relative_path, block_contexts, true); match resolved_visitor { ResolvedPath::AbsolutePath(paths) => { @@ -223,6 +220,12 @@ impl Context { } } +impl From for Context { + fn from(data: Json) -> Context { + Context { data } + } +} + #[cfg(test)] mod test { use crate::block::{BlockContext, BlockParams}; @@ -359,9 +362,9 @@ mod test { #[test] fn test_key_name_with_this() { - let m = btreemap! { - "this_name".to_string() => "the_value".to_string() - }; + let m = json!({ + "this_name": "the_value" + }); let ctx = Context::wraps(&m).unwrap(); assert_eq!( navigate_from_root(&ctx, "this_name").unwrap().render(), diff --git a/vendor/handlebars/src/decorators/mod.rs b/vendor/handlebars/src/decorators/mod.rs index b8bad900f..bd2d23458 100644 --- a/vendor/handlebars/src/decorators/mod.rs +++ b/vendor/handlebars/src/decorators/mod.rs @@ -105,9 +105,9 @@ mod test { .register_template_string("t0", "{{*foo}}".to_string()) .unwrap(); - let data = btreemap! { - "hello".to_string() => "world".to_string() - }; + let data = json!({ + "hello": "world" + }); assert!(handlebars.render("t0", &data).is_err()); @@ -132,9 +132,9 @@ mod test { .register_template_string("t0", "{{hello}}{{*foo}}{{hello}}".to_string()) .unwrap(); - let data = btreemap! { - "hello".to_string() => "world".to_string() - }; + let data = json!({ + "hello": "world" + }); handlebars.register_decorator( "foo", diff --git a/vendor/handlebars/src/error.rs b/vendor/handlebars/src/error.rs index f4721623f..618d68e4f 100644 --- a/vendor/handlebars/src/error.rs +++ b/vendor/handlebars/src/error.rs @@ -1,10 +1,13 @@ -use std::error::Error; -use std::fmt; +// use std::backtrace::Backtrace; +use std::error::Error as StdError; +use std::fmt::{self, Write}; use std::io::Error as IOError; use std::num::ParseIntError; use std::string::FromUtf8Error; use serde_json::error::Error as SerdeError; +use thiserror::Error; + #[cfg(feature = "dir_source")] use walkdir::Error as WalkdirError; @@ -12,14 +15,16 @@ use walkdir::Error as WalkdirError; use rhai::{EvalAltResult, ParseError}; /// Error when rendering data on template. -#[derive(Debug, Default)] +#[derive(Debug, Default, Error)] pub struct RenderError { pub desc: String, pub template_name: Option, pub line_no: Option, pub column_no: Option, - cause: Option>, + #[source] + cause: Option>, unimplemented: bool, + // backtrace: Backtrace, } impl fmt::Display for RenderError { @@ -38,14 +43,6 @@ impl fmt::Display for RenderError { } } -impl Error for RenderError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - self.cause - .as_ref() - .map(|e| e.as_ref() as &(dyn Error + 'static)) - } -} - impl From for RenderError { fn from(e: IOError) -> RenderError { RenderError::from_error("Cannot generate output.", e) @@ -115,7 +112,7 @@ impl RenderError { pub fn from_error(error_info: &str, cause: E) -> RenderError where - E: Error + Send + Sync + 'static, + E: StdError + Send + Sync + 'static, { let mut e = RenderError::new(error_info); e.cause = Some(Box::new(cause)); @@ -129,39 +126,31 @@ impl RenderError { } } -quick_error! { /// Template parsing error - #[derive(Debug)] - pub enum TemplateErrorReason { - MismatchingClosedHelper(open: String, closed: String) { - display("helper {:?} was opened, but {:?} is closing", - open, closed) - } - MismatchingClosedDecorator(open: String, closed: String) { - display("decorator {:?} was opened, but {:?} is closing", - open, closed) - } - InvalidSyntax { - display("invalid handlebars syntax.") - } - InvalidParam (param: String) { - display("invalid parameter {:?}", param) - } - NestedSubexpression { - display("nested subexpression is not supported") - } - IoError(err: IOError, name: String) { - display("Template \"{}\": {}", name, err) - } - #[cfg(feature = "dir_source")] - WalkdirError(err: WalkdirError) { - display("Walk dir error: {}", err) - } - } +#[derive(Debug, Error)] +pub enum TemplateErrorReason { + #[error("helper {0:?} was opened, but {1:?} is closing")] + MismatchingClosedHelper(String, String), + #[error("decorator {0:?} was opened, but {1:?} is closing")] + MismatchingClosedDecorator(String, String), + #[error("invalid handlebars syntax.")] + InvalidSyntax, + #[error("invalid parameter {0:?}")] + InvalidParam(String), + #[error("nested subexpression is not supported")] + NestedSubexpression, + #[error("Template \"{1}\": {0}")] + IoError(IOError, String), + #[cfg(feature = "dir_source")] + #[error("Walk dir error: {err}")] + WalkdirError { + #[from] + err: WalkdirError, + }, } /// Error on parsing template. -#[derive(Debug)] +#[derive(Debug, Error)] pub struct TemplateError { pub reason: TemplateErrorReason, pub template_name: Option, @@ -194,8 +183,6 @@ impl TemplateError { } } -impl Error for TemplateError {} - impl From<(IOError, String)> for TemplateError { fn from(err_info: (IOError, String)) -> TemplateError { let (e, name) = err_info; @@ -206,7 +193,7 @@ impl From<(IOError, String)> for TemplateError { #[cfg(feature = "dir_source")] impl From for TemplateError { fn from(e: WalkdirError) -> TemplateError { - TemplateError::of(TemplateErrorReason::WalkdirError(e)) + TemplateError::of(TemplateErrorReason::from(e)) } } @@ -218,7 +205,7 @@ fn template_segment(template_str: &str, line: usize, col: usize) -> String { let mut buf = String::new(); for (line_count, line_content) in template_str.lines().enumerate() { if line_count >= line_start && line_count <= line_end { - buf.push_str(&format!("{:4} | {}\n", line_count, line_content)); + let _ = writeln!(&mut buf, "{:4} | {}", line_count, line_content); if line_count == line - 1 { buf.push_str(" |"); for c in 0..line_content.len() { @@ -257,16 +244,11 @@ impl fmt::Display for TemplateError { } #[cfg(feature = "script_helper")] -quick_error! { - #[derive(Debug)] - pub enum ScriptError { - IoError(err: IOError) { - from() - source(err) - } - ParseError(err: ParseError) { - from() - source(err) - } - } +#[derive(Debug, Error)] +pub enum ScriptError { + #[error(transparent)] + IoError(#[from] IOError), + + #[error(transparent)] + ParseError(#[from] ParseError), } diff --git a/vendor/handlebars/src/grammar.pest b/vendor/handlebars/src/grammar.pest index 250d9d213..ac6776ee2 100644 --- a/vendor/handlebars/src/grammar.pest +++ b/vendor/handlebars/src/grammar.pest @@ -14,14 +14,20 @@ literal = { string_literal | null_literal = @{ "null" ~ !symbol_char } boolean_literal = @{ ("true"|"false") ~ !symbol_char } -number_literal = @{ "-"? ~ ASCII_DIGIT+ ~ "."? ~ ASCII_DIGIT* ~ ("E" ~ "-"? ~ ASCII_DIGIT+)? } -json_char = { +number_literal = @{ "-"? ~ ASCII_DIGIT+ ~ "."? ~ ASCII_DIGIT* ~ ("E" ~ "-"? ~ ASCII_DIGIT+)? ~ !symbol_char } +json_char_double_quote = { !("\"" | "\\") ~ ANY | "\\" ~ ("\"" | "\\" | "/" | "b" | "f" | "n" | "r" | "t") | "\\" ~ ("u" ~ ASCII_HEX_DIGIT{4}) } -string_inner = @{ json_char* } -string_literal = ${ "\"" ~ string_inner ~ "\"" } +json_char_single_quote = { + !("'" | "\\") ~ ANY + | "\\" ~ ("'" | "\\" | "/" | "b" | "f" | "n" | "r" | "t") + | "\\" ~ ("u" ~ ASCII_HEX_DIGIT{4}) +} +string_inner_double_quote = @{ json_char_double_quote* } +string_inner_single_quote = @{ json_char_single_quote* } +string_literal = ${ ("\"" ~ string_inner_double_quote ~ "\"") | ("'" ~ string_inner_single_quote ~ "'") } array_literal = { "[" ~ literal? ~ ("," ~ literal)* ~ "]" } object_literal = { "{" ~ (string_literal ~ ":" ~ literal)? ~ ("," ~ string_literal ~ ":" ~ literal)* ~ "}" } @@ -50,12 +56,17 @@ pro_whitespace_omitter = { "~" } expression = { !invert_tag ~ "{{" ~ pre_whitespace_omitter? ~ ((identifier ~ (hash|param)+) | name ) ~ pro_whitespace_omitter? ~ "}}" } -html_expression_triple_bracket = _{ "{{{" ~ pre_whitespace_omitter? ~ - ((identifier ~ (hash|param)+) | name ) ~ - pro_whitespace_omitter? ~ "}}}" } +html_expression_triple_bracket_legacy = _{ "{{{" ~ pre_whitespace_omitter? ~ + ((identifier ~ (hash|param)+) | name ) ~ + pro_whitespace_omitter? ~ "}}}" } +html_expression_triple_bracket = _{ "{{" ~ pre_whitespace_omitter? ~ "{" ~ + ((identifier ~ (hash|param)+) | name ) ~ + "}" ~ pro_whitespace_omitter? ~ "}}" } + amp_expression = _{ "{{" ~ pre_whitespace_omitter? ~ "&" ~ name ~ pro_whitespace_omitter? ~ "}}" } -html_expression = { html_expression_triple_bracket | amp_expression } +html_expression = { (html_expression_triple_bracket_legacy | html_expression_triple_bracket) + | amp_expression } decorator_expression = { "{{" ~ pre_whitespace_omitter? ~ "*" ~ exp_line ~ pro_whitespace_omitter? ~ "}}" } diff --git a/vendor/handlebars/src/grammar.rs b/vendor/handlebars/src/grammar.rs index 1fd292ce1..6e61cd4e4 100644 --- a/vendor/handlebars/src/grammar.rs +++ b/vendor/handlebars/src/grammar.rs @@ -4,26 +4,6 @@ #[grammar = "grammar.pest"] pub struct HandlebarsParser; -#[inline] -pub(crate) fn whitespace_matcher(c: char) -> bool { - c == ' ' || c == '\t' -} - -#[inline] -pub(crate) fn newline_matcher(c: char) -> bool { - c == '\n' || c == '\r' -} - -pub(crate) fn ends_with_empty_line(text: &str) -> bool { - text.trim_end_matches(whitespace_matcher) - .ends_with(newline_matcher) -} - -pub(crate) fn starts_with_empty_line(text: &str) -> bool { - text.trim_start_matches(whitespace_matcher) - .starts_with(newline_matcher) -} - #[cfg(test)] mod test { use super::{HandlebarsParser, Rule}; @@ -191,6 +171,7 @@ mod test { "{{exp 1}}", "{{exp \"literal\"}}", "{{exp \"literal with space\"}}", + "{{exp 'literal with space'}}", r#"{{exp "literal with escape \\\\"}}"#, "{{exp ref}}", "{{exp (sub)}}", @@ -199,6 +180,8 @@ mod test { "{{exp {}}}", "{{exp key=1}}", "{{exp key=ref}}", + "{{exp key='literal with space'}}", + "{{exp key=\"literal with space\"}}", "{{exp key=(sub)}}", "{{exp key=(sub 0)}}", "{{exp key=(sub 0 key=1)}}", @@ -225,6 +208,12 @@ mod test { "{{&html}}", "{{{html 1}}}", "{{{html p=true}}}", + "{{{~ html}}}", + "{{{html ~}}}", + "{{{~ html ~}}}", + "{{~{ html }~}}", + "{{~{ html }}}", + "{{{ html }~}}", ]; for i in s.iter() { assert_rule!(Rule::html_expression, i); diff --git a/vendor/handlebars/src/helpers/helper_each.rs b/vendor/handlebars/src/helpers/helper_each.rs index 4b76e7ce7..2be28dc9c 100644 --- a/vendor/handlebars/src/helpers/helper_each.rs +++ b/vendor/handlebars/src/helpers/helper_each.rs @@ -18,7 +18,7 @@ fn update_block_context<'reg>( is_first: bool, value: &Json, ) { - if let Some(ref p) = base_path { + if let Some(p) = base_path { if is_first { *block.base_path_mut() = copy_on_push_vec(p, relative_path); } else if let Some(ptr) = block.base_path_mut().last_mut() { @@ -83,7 +83,7 @@ impl HelperDef for EachHelper { Json::Array(ref list) if !list.is_empty() || (list.is_empty() && h.inverse().is_none()) => { - let block_context = create_block(&value); + let block_context = create_block(value); rc.push_block(block_context); let len = list.len(); @@ -100,8 +100,8 @@ impl HelperDef for EachHelper { block.set_local_var("last", to_json(is_last)); block.set_local_var("index", index.clone()); - update_block_context(block, array_path, i.to_string(), is_first, &v); - set_block_param(block, h, array_path, &index, &v)?; + update_block_context(block, array_path, i.to_string(), is_first, v); + set_block_param(block, h, array_path, &index, v)?; } t.render(r, ctx, rc, out)?; @@ -113,28 +113,28 @@ impl HelperDef for EachHelper { Json::Object(ref obj) if !obj.is_empty() || (obj.is_empty() && h.inverse().is_none()) => { - let block_context = create_block(&value); + let block_context = create_block(value); rc.push_block(block_context); - let mut is_first = true; + let len = obj.len(); + let obj_path = value.context_path(); - for (k, v) in obj.iter() { + for (i, (k, v)) in obj.iter().enumerate() { if let Some(ref mut block) = rc.block_mut() { - let key = to_json(k); + let is_first = i == 0usize; + let is_last = i == len - 1; + let key = to_json(k); block.set_local_var("first", to_json(is_first)); + block.set_local_var("last", to_json(is_last)); block.set_local_var("key", key.clone()); - update_block_context(block, obj_path, k.to_string(), is_first, &v); - set_block_param(block, h, obj_path, &key, &v)?; + update_block_context(block, obj_path, k.to_string(), is_first, v); + set_block_param(block, h, obj_path, &key, v)?; } t.render(r, ctx, rc, out)?; - - if is_first { - is_first = false; - } } rc.pop_block(); @@ -159,7 +159,6 @@ pub static EACH_HELPER: EachHelper = EachHelper; #[cfg(test)] mod test { - use crate::json::value::to_json; use crate::registry::Registry; use serde_json::value::Value as Json; use std::collections::BTreeMap; @@ -188,7 +187,10 @@ mod test { ) .is_ok()); assert!(handlebars - .register_template_string("t1", "{{#each this}}{{@first}}|{{@key}}:{{this}}|{{/each}}") + .register_template_string( + "t1", + "{{#each this}}{{@first}}|{{@last}}|{{@key}}:{{this}}|{{/each}}" + ) .is_ok()); let r0 = handlebars.render("t0", &vec![1u16, 2u16, 3u16]); @@ -199,9 +201,13 @@ mod test { let mut m: BTreeMap = BTreeMap::new(); m.insert("ftp".to_string(), 21); + m.insert("gopher".to_string(), 70); m.insert("http".to_string(), 80); let r1 = handlebars.render("t1", &m); - assert_eq!(r1.ok().unwrap(), "true|ftp:21|false|http:80|".to_string()); + assert_eq!( + r1.ok().unwrap(), + "true|false|ftp:21|false|false|gopher:70|false|true|http:80|".to_string() + ); } #[test] @@ -303,15 +309,15 @@ mod test { assert!(handlebars .register_template_string("t0", "{{#each a}}1{{else}}empty{{/each}}") .is_ok()); - let m1 = btreemap! { - "a".to_string() => Vec::::new(), - }; + let m1 = json!({ + "a": [] + }); let r0 = handlebars.render("t0", &m1).unwrap(); assert_eq!(r0, "empty"); - let m2 = btreemap! { - "b".to_string() => Vec::::new() - }; + let m2 = json!({ + "b": [] + }); let r1 = handlebars.render("t0", &m2).unwrap(); assert_eq!(r1, "empty"); } @@ -322,9 +328,9 @@ mod test { assert!(handlebars .register_template_string("t0", "{{#each a as |i|}}{{i}}{{/each}}") .is_ok()); - let m1 = btreemap! { - "a".to_string() => vec![1,2,3,4,5] - }; + let m1 = json!({ + "a": [1,2,3,4,5] + }); let r0 = handlebars.render("t0", &m1).unwrap(); assert_eq!(r0, "12345"); } @@ -337,10 +343,10 @@ mod test { {{/each}}"; assert!(handlebars.register_template_string("t0", template).is_ok()); - let m = btreemap! { - "ftp".to_string() => 21, - "http".to_string() => 80 - }; + let m = json!({ + "ftp": 21, + "http": 80 + }); let r0 = handlebars.render("t0", &m); assert_eq!(r0.ok().unwrap(), "ftp:21|http:80|".to_string()); } @@ -354,10 +360,10 @@ mod test { assert!(handlebars.register_template_string("t0", template).is_ok()); - let m = btreemap! { - "ftp".to_string() => 21, - "http".to_string() => 80 - }; + let m = json!({ + "ftp": 21, + "http": 80 + }); let r0 = handlebars.render("t0", &m); assert_eq!(r0.ok().unwrap(), "ftp:21|http:80|".to_string()); } @@ -371,12 +377,12 @@ mod test { ) .is_ok()); - let data = btreemap! { - "a".to_string() => to_json(&btreemap! { - "b".to_string() => vec![btreemap!{"c".to_string() => vec![1]}] - }), - "d".to_string() => to_json(&1) - }; + let data = json!({ + "a": { + "b": [{"c": [1]}] + }, + "d": 1 + }); let r0 = handlebars.render("t0", &data); assert_eq!(r0.ok().unwrap(), "1".to_string()); @@ -389,10 +395,10 @@ mod test { {{#if @first}}template<{{/if}}{{this}}{{#if @last}}>{{else}},{{/if}}\ {{/each}}{{/each}}"; assert!(handlebars.register_template_string("t0", template).is_ok()); - let data = btreemap! { - "typearg".to_string() => vec!["T".to_string()], - "variant".to_string() => vec!["1".to_string(), "2".to_string()] - }; + let data = json!({ + "typearg": ["T"], + "variant": ["1", "2"] + }); let r0 = handlebars.render("t0", &data); assert_eq!(r0.ok().unwrap(), "templatetemplate".to_string()); } diff --git a/vendor/handlebars/src/helpers/helper_if.rs b/vendor/handlebars/src/helpers/helper_if.rs index 5a6e42fc0..342c74567 100644 --- a/vendor/handlebars/src/helpers/helper_if.rs +++ b/vendor/handlebars/src/helpers/helper_if.rs @@ -36,7 +36,7 @@ impl HelperDef for IfHelper { let tmpl = if value { h.template() } else { h.inverse() }; match tmpl { - Some(ref t) => t.render(r, ctx, rc, out), + Some(t) => t.render(r, ctx, rc, out), None => Ok(()), } } @@ -136,6 +136,12 @@ mod test { .unwrap() ); + assert_eq!( + "yes\r\n", + hbs.render_template("{{#if a}}\r\nyes\r\n{{/if}}\r\n", &json!({"a": true})) + .unwrap() + ); + assert_eq!( "x\ny", hbs.render_template("{{#if a}}x{{/if}}\ny", &json!({"a": true})) @@ -147,5 +153,37 @@ mod test { hbs.render_template("{{#if a}}\nx\n{{^}}\ny\n{{/if}}\nz", &json!({"a": false})) .unwrap() ); + + assert_eq!( + r#"yes + foo + bar + baz"#, + hbs.render_template( + r#"yes + {{#if true}} + foo + bar + {{/if}} + baz"#, + &json!({}) + ) + .unwrap() + ); + + assert_eq!( + r#" foo + bar + baz"#, + hbs.render_template( + r#" {{#if true}} + foo + bar + {{/if}} + baz"#, + &json!({}) + ) + .unwrap() + ); } } diff --git a/vendor/handlebars/src/helpers/helper_lookup.rs b/vendor/handlebars/src/helpers/helper_lookup.rs index bf887debe..8662d55a0 100644 --- a/vendor/handlebars/src/helpers/helper_lookup.rs +++ b/vendor/handlebars/src/helpers/helper_lookup.rs @@ -52,8 +52,6 @@ pub static LOOKUP_HELPER: LookupHelper = LookupHelper; mod test { use crate::registry::Registry; - use std::collections::BTreeMap; - #[test] fn test_lookup() { let mut handlebars = Registry::new(); @@ -67,13 +65,11 @@ mod test { .register_template_string("t2", "{{lookup kk \"a\"}}") .is_ok()); - let mut m: BTreeMap> = BTreeMap::new(); - m.insert("v1".to_string(), vec![1u16, 2u16, 3u16]); - m.insert("v2".to_string(), vec![9u16, 8u16, 7u16]); + let m = json!({"v1": [1,2,3], "v2": [9,8,7]}); - let m2 = btreemap! { - "kk".to_string() => btreemap!{"a".to_string() => "world".to_string()} - }; + let m2 = json!({ + "kk": {"a": "world"} + }); let r0 = handlebars.render("t0", &m); assert_eq!(r0.ok().unwrap(), "987".to_string()); diff --git a/vendor/handlebars/src/helpers/helper_with.rs b/vendor/handlebars/src/helpers/helper_with.rs index c4d31cd0e..2ea6bd4f6 100644 --- a/vendor/handlebars/src/helpers/helper_with.rs +++ b/vendor/handlebars/src/helpers/helper_with.rs @@ -25,7 +25,7 @@ impl HelperDef for WithHelper { .ok_or_else(|| RenderError::new("Param not found for helper \"with\""))?; if param.value().is_truthy(false) { - let mut block = create_block(¶m); + let mut block = create_block(param); if let Some(block_param) = h.block_param() { let mut params = BlockParams::new(); @@ -60,7 +60,6 @@ pub static WITH_HELPER: WithHelper = WithHelper; #[cfg(test)] mod test { - use crate::json::value::to_json; use crate::registry::Registry; #[derive(Serialize)] @@ -211,12 +210,12 @@ mod test { assert!(handlebars .register_template_string("t0", "{{#with a}}{{#with b}}{{../../d}}{{/with}}{{/with}}") .is_ok()); - let data = btreemap! { - "a".to_string() => to_json(&btreemap! { - "b".to_string() => vec![btreemap!{"c".to_string() => vec![1]}] - }), - "d".to_string() => to_json(1) - }; + let data = json!({ + "a": { + "b": [{"c": [1]}] + }, + "d": 1 + }); let r0 = handlebars.render("t0", &data); assert_eq!(r0.ok().unwrap(), "1".to_string()); diff --git a/vendor/handlebars/src/helpers/mod.rs b/vendor/handlebars/src/helpers/mod.rs index bfd50c1f4..ff5fa2495 100644 --- a/vendor/handlebars/src/helpers/mod.rs +++ b/vendor/handlebars/src/helpers/mod.rs @@ -32,7 +32,8 @@ pub type HelperResult = Result<(), RenderError>; /// ``` /// use handlebars::*; /// -/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc: &mut RenderContext<'_, '_>, out: &mut Output) +/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc: +/// &mut RenderContext<'_, '_>, out: &mut dyn Output) /// -> HelperResult { /// // get parameter from helper or throw an error /// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or(""); diff --git a/vendor/handlebars/src/helpers/scripting.rs b/vendor/handlebars/src/helpers/scripting.rs index cec3b9763..abd567ae9 100644 --- a/vendor/handlebars/src/helpers/scripting.rs +++ b/vendor/handlebars/src/helpers/scripting.rs @@ -98,10 +98,16 @@ mod test { let ast = engine.compile(&script).unwrap(); let params = vec![PathAndJson::new(None, ScopedJson::Derived(json!(true)))]; - let hash = btreemap! { - "me" => PathAndJson::new(None, ScopedJson::Derived(json!("no"))), - "you" => PathAndJson::new(None, ScopedJson::Derived(json!("yes"))), - }; + + let mut hash = BTreeMap::new(); + hash.insert( + "me", + PathAndJson::new(None, ScopedJson::Derived(json!("no"))), + ); + hash.insert( + "you", + PathAndJson::new(None, ScopedJson::Derived(json!("yes"))), + ); let result = call_script_helper(¶ms, &hash, &engine, &ast) .unwrap() diff --git a/vendor/handlebars/src/json/path.rs b/vendor/handlebars/src/json/path.rs index 8270371b2..17a7a91ee 100644 --- a/vendor/handlebars/src/json/path.rs +++ b/vendor/handlebars/src/json/path.rs @@ -6,7 +6,7 @@ use pest::Parser; use crate::error::RenderError; use crate::grammar::{HandlebarsParser, Rule}; -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub enum PathSeg { Named(String), Ruled(Rule), @@ -16,7 +16,7 @@ pub enum PathSeg { /// /// It can be either a local variable like `@first`, `../@index`, /// or a normal relative path like `a/b/c`. -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub enum Path { Relative((Vec, String)), Local((usize, String, String)), diff --git a/vendor/handlebars/src/lib.rs b/vendor/handlebars/src/lib.rs index 7e0aac830..1f9ab1ed3 100644 --- a/vendor/handlebars/src/lib.rs +++ b/vendor/handlebars/src/lib.rs @@ -1,4 +1,4 @@ -#![doc(html_root_url = "https://docs.rs/handlebars/4.1.0")] +#![doc(html_root_url = "https://docs.rs/handlebars/4.3.3")] #![cfg_attr(docsrs, feature(doc_cfg))] //! # Handlebars //! @@ -73,7 +73,7 @@ //! Every time I look into a templating system, I will investigate its //! support for [template inheritance][t]. //! -//! [t]: https://docs.djangoproject.com/en/1.9/ref/templates/language/#template-inheritance +//! [t]: https://docs.djangoproject.com/en/3.2/ref/templates/language/#template-inheritance //! //! Template include is not sufficient for template reuse. In most cases //! you will need a skeleton of page as parent (header, footer, etc.), and @@ -155,7 +155,7 @@ //! use handlebars::Handlebars; //! use std::collections::BTreeMap; //! -//! # fn main() -> Result<(), Box> { +//! # fn main() -> Result<(), Box> { //! let mut handlebars = Handlebars::new(); //! let source = "hello {{world}}"; //! @@ -166,6 +166,14 @@ //! # } //! ``` //! +//! #### Additional features for loading template from +//! +//! * Feature `dir_source` enables template loading +//! `register_templates_directory` from given directory. +//! * Feature `rust-embed` enables template loading +//! `register_embed_templates` from embedded resources in rust struct +//! generated with `RustEmbed`. +//! //! ### Rendering Something //! //! Since handlebars is originally based on JavaScript type system. It supports dynamic features like duck-typing, truthy/falsey values. But for a static language like Rust, this is a little difficult. As a solution, we are using the `serde_json::value::Value` internally for data rendering. @@ -188,7 +196,7 @@ //! age: i16, //! } //! -//! # fn main() -> Result<(), Box> { +//! # fn main() -> Result<(), Box> { //! let source = "Hello, {{name}}"; //! //! let mut handlebars = Handlebars::new(); @@ -367,13 +375,8 @@ #[macro_use] extern crate log; -#[cfg(test)] -#[macro_use] -extern crate maplit; #[macro_use] extern crate pest_derive; -#[macro_use] -extern crate quick_error; #[cfg(test)] #[macro_use] extern crate serde_derive; diff --git a/vendor/handlebars/src/macros.rs b/vendor/handlebars/src/macros.rs index 14cb0152c..bd1eab0bb 100644 --- a/vendor/handlebars/src/macros.rs +++ b/vendor/handlebars/src/macros.rs @@ -38,7 +38,7 @@ #[macro_export] macro_rules! handlebars_helper { - ($struct_name:ident: |$($name:ident: $tpe:tt),* + ($struct_name:ident: |$($name:ident: $tpe:tt$(<$($gen:ty),+>)?),* $($(,)?{$($hash_name:ident: $hash_tpe:tt=$dft_val:literal),*})? $($(,)?*$args:ident)? $($(,)?**$kwargs:ident)?| @@ -71,11 +71,11 @@ macro_rules! handlebars_helper { stringify!($struct_name), stringify!($name), ))) .and_then(|x| - handlebars_helper!(@as_json_value x, $tpe) + handlebars_helper!(@as_json_value x, $tpe$(<$($gen),+>)?) .ok_or_else(|| $crate::RenderError::new(&format!( "`{}` helper: Couldn't convert parameter {} to type `{}`. \ It's {:?} as JSON. Got these params: {:?}", - stringify!($struct_name), stringify!($name), stringify!($tpe), + stringify!($struct_name), stringify!($name), stringify!($tpe$(<$($gen),+>)?), x, h.params(), ))) )?; @@ -117,6 +117,7 @@ macro_rules! handlebars_helper { (@as_json_value $x:ident, bool) => { $x.as_bool() }; (@as_json_value $x:ident, null) => { $x.as_null() }; (@as_json_value $x:ident, Json) => { Some($x) }; + (@as_json_value $x:ident, $tpe:tt$(<$($gen:ty),+>)?) => { serde_json::from_value::<$tpe$(<$($gen),+>)?>($x.clone()).ok() }; } #[cfg(feature = "no_logging")] diff --git a/vendor/handlebars/src/output.rs b/vendor/handlebars/src/output.rs index f1c5865a5..67e62b849 100644 --- a/vendor/handlebars/src/output.rs +++ b/vendor/handlebars/src/output.rs @@ -46,3 +46,9 @@ impl StringOutput { String::from_utf8(self.buf) } } + +impl Default for StringOutput { + fn default() -> Self { + StringOutput::new() + } +} diff --git a/vendor/handlebars/src/partial.rs b/vendor/handlebars/src/partial.rs index a472d5d14..bcf9803fd 100644 --- a/vendor/handlebars/src/partial.rs +++ b/vendor/handlebars/src/partial.rs @@ -20,7 +20,7 @@ fn find_partial<'reg: 'rc, 'rc: 'a, 'a>( d: &Decorator<'reg, 'rc>, name: &str, ) -> Result>, RenderError> { - if let Some(ref partial) = rc.get_partial(name) { + if let Some(partial) = rc.get_partial(name) { return Ok(Some(Cow::Borrowed(partial))); } @@ -52,29 +52,38 @@ pub fn expand_partial<'reg: 'rc, 'rc>( return Err(RenderError::new("Cannot include self in >")); } - // if tname == PARTIAL_BLOCK let partial = find_partial(rc, r, d, tname)?; if let Some(t) = partial { // clone to avoid lifetime issue // FIXME refactor this to avoid let mut local_rc = rc.clone(); + + // if tname == PARTIAL_BLOCK let is_partial_block = tname == PARTIAL_BLOCK; + // add partial block depth there are consecutive partial + // blocks in the stack. if is_partial_block { local_rc.inc_partial_block_depth(); + } else { + // depth cannot be lower than 0, which is guaranted in the + // `dec_partial_block_depth` method + local_rc.dec_partial_block_depth(); } + let mut block = None; let mut block_created = false; - if let Some(ref base_path) = d.param(0).and_then(|p| p.context_path()) { + // create context if param given + if let Some(base_path) = d.param(0).and_then(|p| p.context_path()) { // path given, update base_path - let mut block = BlockContext::new(); - *block.base_path_mut() = base_path.to_vec(); - block_created = true; - local_rc.push_block(block); - } else if !d.hash().is_empty() { - let mut block = BlockContext::new(); + let mut block_inner = BlockContext::new(); + *block_inner.base_path_mut() = base_path.to_vec(); + block = Some(block_inner); + } + + if !d.hash().is_empty() { // hash given, update base_value let hash_ctx = d .hash() @@ -86,9 +95,25 @@ pub fn expand_partial<'reg: 'rc, 'rc>( local_rc.evaluate2(ctx, &Path::current())?.as_json(), &hash_ctx, ); - block.set_base_value(merged_context); + + if let Some(ref mut block_inner) = block { + block_inner.set_base_value(merged_context); + } else { + let mut block_inner = BlockContext::new(); + block_inner.set_base_value(merged_context); + block = Some(block_inner); + } + } + + if let Some(block_inner) = block { + // because block is moved here, we need another bool variable to track + // its status for later cleanup block_created = true; - local_rc.push_block(block); + // clear blocks to prevent block params from parent + // template to be leaked into partials + // see `test_partial_context_issue_495` for the case. + local_rc.clear_blocks(); + local_rc.push_block(block_inner); } // @partial-block @@ -96,6 +121,9 @@ pub fn expand_partial<'reg: 'rc, 'rc>( local_rc.push_partial_block(pb); } + // indent + local_rc.set_indent_string(d.indent()); + let result = t.render(r, ctx, &mut local_rc, out); // cleanup @@ -103,10 +131,6 @@ pub fn expand_partial<'reg: 'rc, 'rc>( local_rc.pop_block(); } - if is_partial_block { - local_rc.dec_partial_block_depth(); - } - if d.template().is_some() { local_rc.pop_partial_block(); } @@ -174,10 +198,7 @@ mod test { "include navbar".to_string() ); assert_eq!( - handlebars - .render("t6", &btreemap! {"a".to_string() => "2".to_string()}) - .ok() - .unwrap(), + handlebars.render("t6", &json!({"a": "2"})).ok().unwrap(), "2".to_string() ); assert_eq!( @@ -257,6 +278,19 @@ mod test { ); } + #[test] + fn teset_partial_context_with_both_hash_and_param() { + let mut hbs = Registry::new(); + hbs.register_template_string("one", "This is a test. {{> two this name=\"fred\" }}") + .unwrap(); + hbs.register_template_string("two", "Lets test {{name}} and {{root_name}}") + .unwrap(); + assert_eq!( + "This is a test. Lets test fred and tom", + hbs.render("one", &json!({"root_name": "tom"})).unwrap() + ); + } + #[test] fn test_partial_subexpression_context_hash() { let mut hbs = Registry::new(); @@ -297,7 +331,7 @@ mod test { } #[test] - fn test_nested_partials() { + fn test_nested_partial_block() { let mut handlebars = Registry::new(); let template1 = "{{> @partial-block }}"; let template2 = "{{#> t1 }}{{> @partial-block }}{{/ t1 }}"; @@ -330,4 +364,293 @@ mod test { "fruit: carrot,fruit: tomato," ); } + + #[test] + fn line_stripping_with_inline_and_partial() { + let tpl0 = r#"{{#*inline "foo"}}foo +{{/inline}} +{{> foo}} +{{> foo}} +{{> foo}}"#; + let tpl1 = r#"{{#*inline "foo"}}foo{{/inline}} +{{> foo}} +{{> foo}} +{{> foo}}"#; + + let hbs = Registry::new(); + assert_eq!( + r#"foo +foo +foo +"#, + hbs.render_template(tpl0, &json!({})).unwrap() + ); + assert_eq!( + r#" +foofoofoo"#, + hbs.render_template(tpl1, &json!({})).unwrap() + ); + } + + #[test] + fn test_partial_indent() { + let outer = r#" {{> inner inner_solo}} + +{{#each inners}} + {{> inner}} +{{/each}} + + {{#each inners}} + {{> inner}} + {{/each}} +"#; + let inner = r#"name: {{name}} +"#; + + let mut hbs = Registry::new(); + + hbs.register_template_string("inner", inner).unwrap(); + hbs.register_template_string("outer", outer).unwrap(); + + let result = hbs + .render( + "outer", + &json!({ + "inner_solo": {"name": "inner_solo"}, + "inners": [ + {"name": "hello"}, + {"name": "there"} + ] + }), + ) + .unwrap(); + + assert_eq!( + result, + r#" name: inner_solo + + name: hello + name: there + + name: hello + name: there +"# + ); + } + // Rule::partial_expression should not trim leading indent by default + + #[test] + fn test_partial_prevent_indent() { + let outer = r#" {{> inner inner_solo}} + +{{#each inners}} + {{> inner}} +{{/each}} + + {{#each inners}} + {{> inner}} + {{/each}} +"#; + let inner = r#"name: {{name}} +"#; + + let mut hbs = Registry::new(); + hbs.set_prevent_indent(true); + + hbs.register_template_string("inner", inner).unwrap(); + hbs.register_template_string("outer", outer).unwrap(); + + let result = hbs + .render( + "outer", + &json!({ + "inner_solo": {"name": "inner_solo"}, + "inners": [ + {"name": "hello"}, + {"name": "there"} + ] + }), + ) + .unwrap(); + + assert_eq!( + result, + r#" name: inner_solo + + name: hello + name: there + + name: hello + name: there +"# + ); + } + + #[test] + fn test_nested_partials() { + let mut hb = Registry::new(); + hb.register_template_string("partial", "{{> @partial-block}}") + .unwrap(); + hb.register_template_string( + "index", + r#"{{#>partial}} + Yo + {{#>partial}} + Yo 2 + {{/partial}} +{{/partial}}"#, + ) + .unwrap(); + assert_eq!( + r#" Yo + Yo 2 +"#, + hb.render("index", &()).unwrap() + ); + + hb.register_template_string("partial2", "{{> @partial-block}}") + .unwrap(); + let r2 = hb + .render_template( + r#"{{#> partial}} +{{#> partial2}} +:( +{{/partial2}} +{{/partial}}"#, + &(), + ) + .unwrap(); + assert_eq!(":(\n", r2); + } + + #[test] + fn test_partial_context_issue_495() { + let mut hb = Registry::new(); + hb.register_template_string( + "t1", + r#"{{~#*inline "displayName"~}} +Template:{{name}} +{{/inline}} +{{#each data as |name|}} +Name:{{name}} +{{>displayName name="aaaa"}} +{{/each}}"#, + ) + .unwrap(); + + hb.register_template_string( + "t1", + r#"{{~#*inline "displayName"~}} +Template:{{this}} +{{/inline}} +{{#each data as |name|}} +Name:{{name}} +{{>displayName}} +{{/each}}"#, + ) + .unwrap(); + + let data = json!({ + "data": ["hudel", "test"] + }); + + assert_eq!( + r#"Name:hudel +Template:hudel +Name:test +Template:test +"#, + hb.render("t1", &data).unwrap() + ); + } + + #[test] + fn test_multiline_partial_indent() { + let mut hb = Registry::new(); + + hb.register_template_string( + "t1", + r#"{{#*inline "thepartial"}} + inner first line + inner second line +{{/inline}} + {{> thepartial}} +outer third line"#, + ) + .unwrap(); + assert_eq!( + r#" inner first line + inner second line +outer third line"#, + hb.render("t1", &()).unwrap() + ); + + hb.register_template_string( + "t2", + r#"{{#*inline "thepartial"}}inner first line +inner second line +{{/inline}} + {{> thepartial}} +outer third line"#, + ) + .unwrap(); + assert_eq!( + r#" inner first line + inner second line +outer third line"#, + hb.render("t2", &()).unwrap() + ); + + hb.register_template_string( + "t3", + r#"{{#*inline "thepartial"}}{{a}}{{/inline}} + {{> thepartial}} +outer third line"#, + ) + .unwrap(); + assert_eq!( + r#" + inner first line + inner second lineouter third line"#, + hb.render("t3", &json!({"a": "inner first line\ninner second line"})) + .unwrap() + ); + + hb.register_template_string( + "t4", + r#"{{#*inline "thepartial"}} + inner first line + inner second line +{{/inline}} + {{~> thepartial}} +outer third line"#, + ) + .unwrap(); + assert_eq!( + r#" inner first line + inner second line +outer third line"#, + hb.render("t4", &()).unwrap() + ); + + let mut hb2 = Registry::new(); + hb2.set_prevent_indent(true); + + hb2.register_template_string( + "t1", + r#"{{#*inline "thepartial"}} + inner first line + inner second line +{{/inline}} + {{> thepartial}} +outer third line"#, + ) + .unwrap(); + assert_eq!( + r#" inner first line + inner second line +outer third line"#, + hb2.render("t1", &()).unwrap() + ) + } } diff --git a/vendor/handlebars/src/registry.rs b/vendor/handlebars/src/registry.rs index e7f5f1cfd..438f8573c 100644 --- a/vendor/handlebars/src/registry.rs +++ b/vendor/handlebars/src/registry.rs @@ -17,12 +17,10 @@ use crate::output::{Output, StringOutput, WriteOutput}; use crate::render::{RenderContext, Renderable}; use crate::sources::{FileSource, Source}; use crate::support::str::{self, StringWriter}; -use crate::template::Template; +use crate::template::{Template, TemplateOptions}; #[cfg(feature = "dir_source")] -use std::path; -#[cfg(feature = "dir_source")] -use walkdir::{DirEntry, WalkDir}; +use walkdir::WalkDir; #[cfg(feature = "script_helper")] use rhai::Engine; @@ -30,6 +28,9 @@ use rhai::Engine; #[cfg(feature = "script_helper")] use crate::helpers::scripting::ScriptHelper; +#[cfg(feature = "rust-embed")] +use rust_embed::RustEmbed; + /// This type represents an *escape fn*, that is a function whose purpose it is /// to escape potentially problematic characters in a string. /// @@ -62,6 +63,7 @@ pub struct Registry<'reg> { escape_fn: EscapeFn, strict_mode: bool, dev_mode: bool, + prevent_indent: bool, #[cfg(feature = "script_helper")] pub(crate) engine: Arc, @@ -90,21 +92,6 @@ impl<'reg> Default for Registry<'reg> { } } -#[cfg(feature = "dir_source")] -fn filter_file(entry: &DirEntry, suffix: &str) -> bool { - let path = entry.path(); - - // ignore hidden files, emacs buffers and files with wrong suffix - !path.is_file() - || path - .file_name() - .map(|s| { - let ds = s.to_string_lossy(); - ds.starts_with('.') || ds.starts_with('#') || !ds.ends_with(suffix) - }) - .unwrap_or(true) -} - #[cfg(feature = "script_helper")] fn rhai_engine() -> Engine { Engine::new() @@ -120,6 +107,7 @@ impl<'reg> Registry<'reg> { escape_fn: Arc::new(html_escape), strict_mode: false, dev_mode: false, + prevent_indent: false, #[cfg(feature = "script_helper")] engine: Arc::new(rhai_engine()), #[cfg(feature = "script_helper")] @@ -178,7 +166,7 @@ impl<'reg> Registry<'reg> { /// Return dev mode state, default is false /// /// With dev mode turned on, handlebars enables a set of development - /// firendly features, that may affect its performance. + /// friendly features, that may affect its performance. pub fn dev_mode(&self) -> bool { self.dev_mode } @@ -186,9 +174,30 @@ impl<'reg> Registry<'reg> { /// Enable or disable dev mode /// /// With dev mode turned on, handlebars enables a set of development - /// firendly features, that may affect its performance. + /// friendly features, that may affect its performance. + /// + /// **Note that you have to enable dev mode before adding templates to + /// the registry**. Otherwise it won't take effect at all. pub fn set_dev_mode(&mut self, enabled: bool) { self.dev_mode = enabled; + + // clear template source when disabling dev mode + if !enabled { + self.template_sources.clear(); + } + } + + /// Enable or disable indent for partial include tag `{{>}}` + /// + /// By default handlebars keeps indent whitespaces for partial + /// include tag, to change this behaviour, set this toggle to `true`. + pub fn set_prevent_indent(&mut self, enable: bool) { + self.prevent_indent = enable; + } + + /// Return state for `prevent_indent` option, default to `false`. + pub fn prevent_indent(&self) -> bool { + self.prevent_indent } /// Register a `Template` @@ -196,6 +205,9 @@ impl<'reg> Registry<'reg> { /// This is infallible since the template has already been parsed and /// insert cannot fail. If there is an existing template with this name it /// will be overwritten. + /// + /// Dev mode doesn't apply for pre-compiled template because it's lifecycle + /// is not managed by the registry. pub fn register_template(&mut self, name: &str, tpl: Template) { self.templates.insert(name.to_string(), tpl); } @@ -211,7 +223,13 @@ impl<'reg> Registry<'reg> { where S: AsRef, { - let template = Template::compile_with_name(tpl_str, name.to_owned())?; + let template = Template::compile2( + tpl_str.as_ref(), + TemplateOptions { + name: Some(name.to_owned()), + prevent_indent: self.prevent_indent, + }, + )?; self.register_template(name, template); Ok(()) } @@ -227,7 +245,10 @@ impl<'reg> Registry<'reg> { self.register_template_string(name, partial_str) } - /// Register a template from a path + /// Register a template from a path on file system + /// + /// If dev mode is enabled, the registry will keep reading the template file + /// from file system everytime it's visited. pub fn register_template_file

( &mut self, name: &str, @@ -262,11 +283,14 @@ impl<'reg> Registry<'reg> { /// /// This method is not available by default. /// You will need to enable the `dir_source` feature to use it. + /// + /// When dev_mode enabled, like `register_template_file`, templates is reloaded + /// from file system everytime it's visied. #[cfg(feature = "dir_source")] #[cfg_attr(docsrs, doc(cfg(feature = "dir_source")))] pub fn register_templates_directory

( &mut self, - tpl_extension: &'static str, + tpl_extension: &str, dir_path: P, ) -> Result<(), TemplateError> where @@ -274,40 +298,88 @@ impl<'reg> Registry<'reg> { { let dir_path = dir_path.as_ref(); - let prefix_len = if dir_path - .to_string_lossy() - .ends_with(|c| c == '\\' || c == '/') - // `/` will work on windows too so we still need to check - { - dir_path.to_string_lossy().len() - } else { - dir_path.to_string_lossy().len() + 1 - }; + // Allowing dots at the beginning as to not break old + // applications. + let tpl_extension = tpl_extension.strip_prefix('.').unwrap_or(tpl_extension); let walker = WalkDir::new(dir_path); let dir_iter = walker .min_depth(1) .into_iter() - .filter(|e| e.is_ok() && !filter_file(e.as_ref().unwrap(), tpl_extension)); + .filter_map(|e| e.ok().map(|e| e.into_path())) + // Checks if extension matches + .filter(|tpl_path| { + tpl_path + .extension() + .map(|extension| extension == tpl_extension) + .unwrap_or(false) + }) + // Rejects any hidden or temporary files. + .filter(|tpl_path| { + tpl_path + .file_stem() + .map(|stem| stem.to_string_lossy()) + .map(|stem| !(stem.starts_with('.') || stem.starts_with('#'))) + .unwrap_or(false) + }) + .filter_map(|tpl_path| { + tpl_path + .strip_prefix(dir_path) + .ok() + .map(|tpl_canonical_name| { + tpl_canonical_name + .with_extension("") + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("/") + }) + .map(|tpl_canonical_name| (tpl_canonical_name, tpl_path)) + }); + + for (tpl_canonical_name, tpl_path) in dir_iter { + self.register_template_file(&tpl_canonical_name, &tpl_path)?; + } - for entry in dir_iter { - let entry = entry?; + Ok(()) + } - let tpl_path = entry.path(); - let tpl_file_path = entry.path().to_string_lossy(); + /// Register templates using a + /// [RustEmbed](https://github.com/pyros2097/rust-embed) type + /// + /// File names from embed struct are used as template name. + /// + /// ```skip + /// #[derive(RustEmbed)] + /// #[folder = "templates"] + /// struct Assets; + /// + /// let mut hbs = Handlebars::new(); + /// hbs.register_embed_templates::(); + /// ``` + /// + #[cfg(feature = "rust-embed")] + #[cfg_attr(docsrs, doc(cfg(feature = "rust-embed")))] + pub fn register_embed_templates(&mut self) -> Result<(), TemplateError> + where + E: RustEmbed, + { + for item in E::iter() { + let file_name = item.as_ref(); + if let Some(file) = E::get(file_name) { + let data = file.data; - let tpl_name = &tpl_file_path[prefix_len..tpl_file_path.len() - tpl_extension.len()]; - // replace platform path separator with our internal one - let tpl_canonical_name = tpl_name.replace(path::MAIN_SEPARATOR, "/"); - self.register_template_file(&tpl_canonical_name, &tpl_path)?; + let tpl_content = String::from_utf8_lossy(data.as_ref()); + self.register_template_string(file_name, tpl_content)?; + } } - Ok(()) } /// Remove a template from the registry pub fn unregister_template(&mut self, name: &str) { self.templates.remove(name); + self.template_sources.remove(name); } /// Register a helper @@ -335,7 +407,6 @@ impl<'reg> Registry<'reg> { /// (value * 100).to_string() + label /// ``` /// - /// #[cfg(feature = "script_helper")] #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] pub fn register_script_helper(&mut self, name: &str, script: &str) -> Result<(), ScriptError> { @@ -347,6 +418,9 @@ impl<'reg> Registry<'reg> { } /// Register a [rhai](https://docs.rs/rhai/) script from file + /// + /// When dev mode is enable, script file is reloaded from original file + /// everytime it is called. #[cfg(feature = "script_helper")] #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] pub fn register_script_helper_file

( @@ -365,6 +439,22 @@ impl<'reg> Registry<'reg> { self.register_script_helper(name, &script) } + /// Borrow a read-only reference to current rhai engine + #[cfg(feature = "script_helper")] + #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] + pub fn engine(&self) -> &Engine { + self.engine.as_ref() + } + + /// Set a custom rhai engine for the registry. + /// + /// *Note that* you need to set custom engine before adding scripts. + #[cfg(feature = "script_helper")] + #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] + pub fn set_engine(&mut self, engine: Engine) { + self.engine = Arc::new(engine); + } + /// Register a decorator pub fn register_decorator( &mut self, @@ -389,7 +479,7 @@ impl<'reg> Registry<'reg> { /// Get a reference to the current *escape fn*. pub fn get_escape_fn(&self) -> &dyn Fn(&str) -> String { - &*self.escape_fn + self.escape_fn.as_ref() } /// Return `true` if a template is registered for the given name @@ -411,7 +501,15 @@ impl<'reg> Registry<'reg> { let r = source .load() .map_err(|e| TemplateError::from((e, name.to_owned()))) - .and_then(|tpl_str| Template::compile_with_name(tpl_str, name.to_owned())) + .and_then(|tpl_str| { + Template::compile2( + tpl_str.as_ref(), + TemplateOptions { + name: Some(name.to_owned()), + prevent_indent: self.prevent_indent, + }, + ) + }) .map(Cow::Owned) .map_err(RenderError::from); Some(r) @@ -433,6 +531,7 @@ impl<'reg> Registry<'reg> { } /// Return a registered helper + #[inline] pub(crate) fn get_or_load_helper( &'reg self, name: &str, @@ -460,6 +559,7 @@ impl<'reg> Registry<'reg> { } /// Return a registered decorator + #[inline] pub(crate) fn get_decorator( &self, name: &str, @@ -468,6 +568,10 @@ impl<'reg> Registry<'reg> { } /// Return all templates registered + /// + /// **Note that** in dev mode, the template returned from this method may + /// not reflect its latest state. This method doesn't try to reload templates + /// from its source. pub fn get_templates(&self) -> &HashMap { &self.templates } @@ -475,6 +579,7 @@ impl<'reg> Registry<'reg> { /// Unregister all templates pub fn clear_templates(&mut self) { self.templates.clear(); + self.template_sources.clear(); } #[inline] @@ -489,7 +594,7 @@ impl<'reg> Registry<'reg> { { self.get_or_load_template(name).and_then(|t| { let mut render_context = RenderContext::new(t.name.as_ref()); - t.render(self, &ctx, &mut render_context, output) + t.render(self, ctx, &mut render_context, output) }) } @@ -516,7 +621,7 @@ impl<'reg> Registry<'reg> { output.into_string().map_err(RenderError::from) } - /// Render a registered template and write some data to the `std::io::Write` + /// Render a registered template and write data to the `std::io::Write` pub fn render_to_write(&self, name: &str, data: &T, writer: W) -> Result<(), RenderError> where T: Serialize, @@ -527,6 +632,21 @@ impl<'reg> Registry<'reg> { self.render_to_output(name, &ctx, &mut output) } + /// Render a registered template using reusable `Context`, and write data to + /// the `std::io::Write` + pub fn render_with_context_to_write( + &self, + name: &str, + ctx: &Context, + writer: W, + ) -> Result<(), RenderError> + where + W: Write, + { + let mut output = WriteOutput::new(writer); + self.render_to_output(name, ctx, &mut output) + } + /// Render a template string using current registry without registering it pub fn render_template(&self, template_string: &str, data: &T) -> Result where @@ -537,23 +657,52 @@ impl<'reg> Registry<'reg> { Ok(writer.into_string()) } - /// Render a template string using reused context data + /// Render a template string using reusable context data pub fn render_template_with_context( &self, template_string: &str, ctx: &Context, ) -> Result { - let tpl = Template::compile(template_string)?; + let tpl = Template::compile2( + template_string, + TemplateOptions { + prevent_indent: self.prevent_indent, + ..Default::default() + }, + )?; let mut out = StringOutput::new(); { let mut render_context = RenderContext::new(None); - tpl.render(self, &ctx, &mut render_context, &mut out)?; + tpl.render(self, ctx, &mut render_context, &mut out)?; } out.into_string().map_err(RenderError::from) } + /// Render a template string using resuable context, and write data into + /// `std::io::Write` + pub fn render_template_with_context_to_write( + &self, + template_string: &str, + ctx: &Context, + writer: W, + ) -> Result<(), RenderError> + where + W: Write, + { + let tpl = Template::compile2( + template_string, + TemplateOptions { + prevent_indent: self.prevent_indent, + ..Default::default() + }, + )?; + let mut render_context = RenderContext::new(None); + let mut out = WriteOutput::new(writer); + tpl.render(self, ctx, &mut render_context, &mut out) + } + /// Render a template string using current registry without registering it pub fn render_template_to_write( &self, @@ -565,11 +714,8 @@ impl<'reg> Registry<'reg> { T: Serialize, W: Write, { - let tpl = Template::compile(template_string)?; let ctx = Context::wraps(data)?; - let mut render_context = RenderContext::new(None); - let mut out = WriteOutput::new(writer); - tpl.render(self, &ctx, &mut render_context, &mut out) + self.render_template_with_context_to_write(template_string, &ctx, writer) } } @@ -944,8 +1090,7 @@ mod test { .unwrap(); assert_eq!( "0123", - reg.render_with_context("t0", &Context::wraps(&data).unwrap()) - .unwrap() + reg.render_with_context("t0", &Context::from(data)).unwrap() ); } @@ -1089,4 +1234,17 @@ mod test { dir.close().unwrap(); } + + #[test] + #[cfg(feature = "script_helper")] + fn test_engine_access() { + use rhai::Engine; + + let mut registry = Registry::new(); + let mut eng = Engine::new(); + eng.set_max_string_size(1000); + registry.set_engine(eng); + + assert_eq!(1000, registry.engine().max_string_size()); + } } diff --git a/vendor/handlebars/src/render.rs b/vendor/handlebars/src/render.rs index 188ea221a..036352b3a 100644 --- a/vendor/handlebars/src/render.rs +++ b/vendor/handlebars/src/render.rs @@ -14,6 +14,7 @@ use crate::json::value::{JsonRender, PathAndJson, ScopedJson}; use crate::output::{Output, StringOutput}; use crate::partial; use crate::registry::Registry; +use crate::support; use crate::template::TemplateElement::*; use crate::template::{ BlockParam, DecoratorTemplate, HelperTemplate, Parameter, Template, TemplateElement, @@ -47,10 +48,11 @@ pub struct RenderContextInner<'reg: 'rc, 'rc> { /// root template name root_template: Option<&'reg String>, disable_escape: bool, + indent_string: Option<&'reg String>, } impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { - /// Create a render context from a `Write` + /// Create a render context pub fn new(root_template: Option<&'reg String>) -> RenderContext<'reg, 'rc> { let inner = Rc::new(RenderContextInner { partials: BTreeMap::new(), @@ -60,6 +62,7 @@ impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { current_template: None, root_template, disable_escape: false, + indent_string: None, }); let mut blocks = VecDeque::with_capacity(5); @@ -73,7 +76,6 @@ impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { } } - // TODO: better name pub(crate) fn new_for_block(&self) -> RenderContext<'reg, 'rc> { let inner = self.inner.clone(); @@ -101,6 +103,10 @@ impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { self.blocks.pop_front(); } + pub(crate) fn clear_blocks(&mut self) { + self.blocks.clear(); + } + /// Borrow a reference to current block context pub fn block(&self) -> Option<&BlockContext<'reg>> { self.blocks.front() @@ -190,7 +196,19 @@ impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { } pub(crate) fn dec_partial_block_depth(&mut self) { - self.inner_mut().partial_block_depth -= 1; + let depth = &mut self.inner_mut().partial_block_depth; + if *depth > 0 { + *depth -= 1; + } + } + + pub(crate) fn set_indent_string(&mut self, indent: Option<&'reg String>) { + self.inner_mut().indent_string = indent; + } + + #[inline] + pub(crate) fn get_indent_string(&self) -> Option<&'reg String> { + self.inner.indent_string } /// Remove a registered partial @@ -201,7 +219,7 @@ impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { fn get_local_var(&self, level: usize, name: &str) -> Option<&Json> { self.blocks .get(level) - .and_then(|blk| blk.get_local_var(&name)) + .and_then(|blk| blk.get_local_var(name)) } /// Test if given template name is current template. @@ -275,9 +293,10 @@ impl<'reg, 'rc> fmt::Debug for RenderContextInner<'reg, 'rc> { f.debug_struct("RenderContextInner") .field("partials", &self.partials) .field("partial_block_stack", &self.partial_block_stack) + .field("partial_block_depth", &self.partial_block_depth) .field("root_template", &self.root_template) .field("current_template", &self.current_template) - .field("disable_eacape", &self.disable_escape) + .field("disable_escape", &self.disable_escape) .finish() } } @@ -435,6 +454,7 @@ pub struct Decorator<'reg, 'rc> { params: Vec>, hash: BTreeMap<&'reg str, PathAndJson<'reg, 'rc>>, template: Option<&'reg Template>, + indent: Option<&'reg String>, } impl<'reg: 'rc, 'rc> Decorator<'reg, 'rc> { @@ -463,6 +483,7 @@ impl<'reg: 'rc, 'rc> Decorator<'reg, 'rc> { params: pv, hash: hm, template: dt.template.as_ref(), + indent: dt.indent.as_ref(), }) } @@ -495,6 +516,10 @@ impl<'reg: 'rc, 'rc> Decorator<'reg, 'rc> { pub fn template(&self) -> Option<&'reg Template> { self.template } + + pub fn indent(&self) -> Option<&'reg String> { + self.indent + } } /// Render trait @@ -747,6 +772,20 @@ pub(crate) fn do_escape(r: &Registry<'_>, rc: &RenderContext<'_, '_>, content: S } } +#[inline] +fn indent_aware_write( + v: &str, + rc: &mut RenderContext<'_, '_>, + out: &mut dyn Output, +) -> Result<(), RenderError> { + if let Some(indent) = rc.get_indent_string() { + out.write(support::str::with_indent(v, indent).as_ref())?; + } else { + out.write(v.as_ref())?; + } + Ok(()) +} + impl Renderable for TemplateElement { fn render<'reg: 'rc, 'rc>( &'reg self, @@ -755,11 +794,8 @@ impl Renderable for TemplateElement { rc: &mut RenderContext<'reg, 'rc>, out: &mut dyn Output, ) -> Result<(), RenderError> { - match *self { - RawString(ref v) => { - out.write(v.as_ref())?; - Ok(()) - } + match self { + RawString(ref v) => indent_aware_write(v.as_ref(), rc, out), Expression(ref ht) | HtmlExpression(ref ht) => { let is_html_expression = matches!(self, HtmlExpression(_)); if is_html_expression { @@ -789,8 +825,7 @@ impl Renderable for TemplateElement { } else { let rendered = context_json.value().render(); let output = do_escape(registry, rc, rendered); - out.write(output.as_ref())?; - Ok(()) + indent_aware_write(output.as_ref(), rc, out) } } } else { @@ -1117,3 +1152,37 @@ fn test_zero_args_heler() { "Output name: first_name not resolved" ); } + +#[test] +fn test_identifiers_starting_with_numbers() { + let mut r = Registry::new(); + + assert!(r + .register_template_string("r1", "{{#if 0a}}true{{/if}}") + .is_ok()); + let r1 = r.render("r1", &json!({"0a": true})).unwrap(); + assert_eq!(r1, "true"); + + assert!(r.register_template_string("r2", "{{eq 1a 1}}").is_ok()); + let r2 = r.render("r2", &json!({"1a": 2, "a": 1})).unwrap(); + assert_eq!(r2, "false"); + + assert!(r + .register_template_string("r3", "0: {{0}} {{#if (eq 0 true)}}resolved from context{{/if}}\n1a: {{1a}} {{#if (eq 1a true)}}resolved from context{{/if}}\n2_2: {{2_2}} {{#if (eq 2_2 true)}}resolved from context{{/if}}") // YUP it is just eq that barfs! is if handled specially? maybe this test should go nearer to specific helpers that fail? + .is_ok()); + let r3 = r + .render("r3", &json!({"0": true, "1a": true, "2_2": true})) + .unwrap(); + assert_eq!( + r3, + "0: true \n1a: true resolved from context\n2_2: true resolved from context" + ); + + // these should all be errors: + assert!(r.register_template_string("r4", "{{eq 1}}").is_ok()); + assert!(r.register_template_string("r5", "{{eq a1}}").is_ok()); + assert!(r.register_template_string("r6", "{{eq 1a}}").is_ok()); + assert!(r.render("r4", &()).is_err()); + assert!(r.render("r5", &()).is_err()); + assert!(r.render("r6", &()).is_err()); +} diff --git a/vendor/handlebars/src/support.rs b/vendor/handlebars/src/support.rs index bd5564d32..b02aca6db 100644 --- a/vendor/handlebars/src/support.rs +++ b/vendor/handlebars/src/support.rs @@ -57,6 +57,64 @@ pub mod str { output } + /// add indent for lines but last + pub fn with_indent(s: &str, indent: &str) -> String { + let mut output = String::new(); + + let mut it = s.chars().peekable(); + while let Some(c) = it.next() { + output.push(c); + // check if c is not the last character, we don't append + // indent for last line break + if c == '\n' && it.peek().is_some() { + output.push_str(indent); + } + } + + output + } + + #[inline] + pub(crate) fn whitespace_matcher(c: char) -> bool { + c == ' ' || c == '\t' + } + + #[inline] + pub(crate) fn newline_matcher(c: char) -> bool { + c == '\n' || c == '\r' + } + + #[inline] + pub(crate) fn strip_first_newline(s: &str) -> &str { + if let Some(s) = s.strip_prefix("\r\n") { + s + } else if let Some(s) = s.strip_prefix('\n') { + s + } else { + s + } + } + + pub(crate) fn find_trailing_whitespace_chars(s: &str) -> Option<&str> { + let trimmed = s.trim_end_matches(whitespace_matcher); + if trimmed.len() == s.len() { + None + } else { + Some(&s[trimmed.len()..]) + } + } + + pub(crate) fn ends_with_empty_line(text: &str) -> bool { + let s = text.trim_end_matches(whitespace_matcher); + // also matches when text is just whitespaces + s.ends_with(newline_matcher) || s.is_empty() + } + + pub(crate) fn starts_with_empty_line(text: &str) -> bool { + text.trim_start_matches(whitespace_matcher) + .starts_with(newline_matcher) + } + #[cfg(test)] mod test { use crate::support::str::StringWriter; diff --git a/vendor/handlebars/src/template.rs b/vendor/handlebars/src/template.rs index 87f853799..617f47711 100644 --- a/vendor/handlebars/src/template.rs +++ b/vendor/handlebars/src/template.rs @@ -9,23 +9,39 @@ use pest::{Parser, Position, Span}; use serde_json::value::Value as Json; use crate::error::{TemplateError, TemplateErrorReason}; -use crate::grammar::{self, HandlebarsParser, Rule}; +use crate::grammar::{HandlebarsParser, Rule}; use crate::json::path::{parse_json_path_from_iter, Path}; +use crate::support; use self::TemplateElement::*; -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub struct TemplateMapping(pub usize, pub usize); /// A handlebars template -#[derive(PartialEq, Clone, Debug, Default)] +#[derive(PartialEq, Eq, Clone, Debug, Default)] pub struct Template { pub name: Option, pub elements: Vec, pub mapping: Vec, } -#[derive(PartialEq, Clone, Debug)] +#[derive(Default)] +pub(crate) struct TemplateOptions { + pub(crate) prevent_indent: bool, + pub(crate) name: Option, +} + +impl TemplateOptions { + fn name(&self) -> String { + self.name + .as_ref() + .cloned() + .unwrap_or_else(|| "Unnamed".to_owned()) + } +} + +#[derive(PartialEq, Eq, Clone, Debug)] pub struct Subexpression { // we use box here avoid resursive struct definition pub element: Box, @@ -84,13 +100,13 @@ impl Subexpression { } } -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub enum BlockParam { Single(Parameter), Pair((Parameter, Parameter)), } -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub struct ExpressionSpec { pub name: Parameter, pub params: Vec, @@ -100,7 +116,7 @@ pub struct ExpressionSpec { pub omit_pro_ws: bool, } -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub enum Parameter { // for helper name only Name(String), @@ -110,7 +126,7 @@ pub enum Parameter { Subexpression(Subexpression), } -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub struct HelperTemplate { pub name: Parameter, pub params: Vec, @@ -122,6 +138,18 @@ pub struct HelperTemplate { } impl HelperTemplate { + pub fn new(exp: ExpressionSpec, block: bool) -> HelperTemplate { + HelperTemplate { + name: exp.name, + params: exp.params, + hash: exp.hash, + block_param: exp.block_param, + block, + template: None, + inverse: None, + } + } + // test only pub(crate) fn with_path(path: Path) -> HelperTemplate { HelperTemplate { @@ -140,12 +168,26 @@ impl HelperTemplate { } } -#[derive(PartialEq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] pub struct DecoratorTemplate { pub name: Parameter, pub params: Vec, pub hash: HashMap, pub template: Option

{} - - pub trait _ValueParserViaValueEnumSealed {} - impl _ValueParserViaValueEnumSealed for &_AutoValueParser {} - - pub trait _ValueParserViaFromStrSealed {} - impl _ValueParserViaFromStrSealed for _AutoValueParser - where - FromStr: std::str::FromStr + std::any::Any + Send + Sync + 'static, - ::Err: - Into>, - { - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn ensure_typed_applies_to_parse() { - fn parse(_: &str) -> Result { - Ok(10) - } - let cmd = crate::Command::new("cmd"); - let arg = None; - assert_eq!( - TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(), - 10 - ); - } -} diff --git a/vendor/clap/src/derive.rs b/vendor/clap/src/derive.rs deleted file mode 100644 index bfb7bdfa2..000000000 --- a/vendor/clap/src/derive.rs +++ /dev/null @@ -1,585 +0,0 @@ -//! This module contains traits that are usable with the `#[derive(...)].` -//! macros in [`clap_derive`]. - -use crate::{ArgMatches, Command, Error, PossibleValue}; - -use std::ffi::OsString; - -/// Parse command-line arguments into `Self`. -/// -/// The primary one-stop-shop trait used to create an instance of a `clap` -/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back -/// into concrete instance of the user struct. -/// -/// This trait is primarily a convenience on top of [`FromArgMatches`] + -/// [`CommandFactory`] which uses those two underlying traits to build the two -/// fundamental functions `parse` which uses the `std::env::args_os` iterator, -/// and `parse_from` which allows the consumer to supply the iterator (along -/// with fallible options for each). -/// -/// See also [`Subcommand`] and [`Args`]. -/// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. -/// -/// **NOTE:** Deriving requires the `derive` feature flag -/// -/// # Examples -/// -/// The following example creates a `Context` struct that would be used -/// throughout the application representing the normalized values coming from -/// the CLI. -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// /// My super CLI -/// #[derive(clap::Parser)] -/// #[clap(name = "demo")] -/// struct Context { -/// /// More verbose output -/// #[clap(long)] -/// verbose: bool, -/// /// An optional name -/// #[clap(short, long)] -/// name: Option, -/// } -/// ``` -/// -/// The equivalent [`Command`] struct + `From` implementation: -/// -/// ```rust -/// # use clap::{Command, Arg, ArgMatches, ArgAction}; -/// Command::new("demo") -/// .about("My super CLI") -/// .arg(Arg::new("verbose") -/// .long("verbose") -/// .action(ArgAction::SetTrue) -/// .help("More verbose output")) -/// .arg(Arg::new("name") -/// .long("name") -/// .short('n') -/// .help("An optional name") -/// .takes_value(true)); -/// -/// struct Context { -/// verbose: bool, -/// name: Option, -/// } -/// -/// impl From for Context { -/// fn from(m: ArgMatches) -> Self { -/// Context { -/// verbose: *m.get_one::("verbose").expect("defaulted_by_clap"), -/// name: m.get_one::("name").cloned(), -/// } -/// } -/// } -/// ``` -/// -pub trait Parser: FromArgMatches + CommandFactory + Sized { - /// Parse from `std::env::args_os()`, exit on error - fn parse() -> Self { - let mut matches = ::command().get_matches(); - let res = ::from_arg_matches_mut(&mut matches) - .map_err(format_error::); - match res { - Ok(s) => s, - Err(e) => { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches` - e.exit() - } - } - } - - /// Parse from `std::env::args_os()`, return Err on error. - fn try_parse() -> Result { - let mut matches = ::command().try_get_matches()?; - ::from_arg_matches_mut(&mut matches).map_err(format_error::) - } - - /// Parse from iterator, exit on error - fn parse_from(itr: I) -> Self - where - I: IntoIterator, - T: Into + Clone, - { - let mut matches = ::command().get_matches_from(itr); - let res = ::from_arg_matches_mut(&mut matches) - .map_err(format_error::); - match res { - Ok(s) => s, - Err(e) => { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches_from` - e.exit() - } - } - } - - /// Parse from iterator, return Err on error. - fn try_parse_from(itr: I) -> Result - where - I: IntoIterator, - T: Into + Clone, - { - let mut matches = ::command().try_get_matches_from(itr)?; - ::from_arg_matches_mut(&mut matches).map_err(format_error::) - } - - /// Update from iterator, exit on error - fn update_from(&mut self, itr: I) - where - I: IntoIterator, - T: Into + Clone, - { - let mut matches = ::command_for_update().get_matches_from(itr); - let res = ::update_from_arg_matches_mut(self, &mut matches) - .map_err(format_error::); - if let Err(e) = res { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches_from` - e.exit() - } - } - - /// Update from iterator, return Err on error. - fn try_update_from(&mut self, itr: I) -> Result<(), Error> - where - I: IntoIterator, - T: Into + Clone, - { - let mut matches = - ::command_for_update().try_get_matches_from(itr)?; - ::update_from_arg_matches_mut(self, &mut matches) - .map_err(format_error::) - } - - /// Deprecated, `StructOpt::clap` replaced with [`IntoCommand::command`] (derive as part of - /// [`Parser`]) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::clap` is replaced with `IntoCommand::command` (derived as part of `Parser`)" - ) - )] - #[doc(hidden)] - fn clap<'help>() -> Command<'help> { - ::command() - } - - /// Deprecated, `StructOpt::from_clap` replaced with [`FromArgMatches::from_arg_matches_mut`] (derive as part of - /// [`Parser`]) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::from_clap` is replaced with `FromArgMatches::from_arg_matches_mut` (derived as part of `Parser`)" - ) - )] - #[doc(hidden)] - fn from_clap(matches: &ArgMatches) -> Self { - ::from_arg_matches(matches).unwrap() - } - - /// Deprecated, `StructOpt::from_args` replaced with `Parser::parse` (note the change in derives) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::from_args` is replaced with `Parser::parse` (note the change in derives)" - ) - )] - #[doc(hidden)] - fn from_args() -> Self { - Self::parse() - } - - /// Deprecated, `StructOpt::from_args_safe` replaced with `Parser::try_parse` (note the change in derives) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::from_args_safe` is replaced with `Parser::try_parse` (note the change in derives)" - ) - )] - #[doc(hidden)] - fn from_args_safe() -> Result { - Self::try_parse() - } - - /// Deprecated, `StructOpt::from_iter` replaced with `Parser::parse_from` (note the change in derives) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::from_iter` is replaced with `Parser::parse_from` (note the change in derives)" - ) - )] - #[doc(hidden)] - fn from_iter(itr: I) -> Self - where - I: IntoIterator, - T: Into + Clone, - { - Self::parse_from(itr) - } - - /// Deprecated, `StructOpt::from_iter_safe` replaced with `Parser::try_parse_from` (note the - /// change in derives) - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "`StructOpt::from_iter_safe` is replaced with `Parser::try_parse_from` (note the change in derives)" - ) - )] - #[doc(hidden)] - fn from_iter_safe(itr: I) -> Result - where - I: IntoIterator, - T: Into + Clone, - { - Self::try_parse_from(itr) - } -} - -/// Create a [`Command`] relevant for a user-defined container. -/// -/// Derived as part of [`Parser`]. -pub trait CommandFactory: Sized { - /// Build a [`Command`] that can instantiate `Self`. - /// - /// See [`FromArgMatches::from_arg_matches_mut`] for instantiating `Self`. - fn command<'help>() -> Command<'help> { - #[allow(deprecated)] - Self::into_app() - } - /// Deprecated, replaced with `CommandFactory::command` - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `CommandFactory::command") - )] - fn into_app<'help>() -> Command<'help>; - /// Build a [`Command`] that can update `self`. - /// - /// See [`FromArgMatches::update_from_arg_matches_mut`] for updating `self`. - fn command_for_update<'help>() -> Command<'help> { - #[allow(deprecated)] - Self::into_app_for_update() - } - /// Deprecated, replaced with `CommandFactory::command_for_update` - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `CommandFactory::command_for_update" - ) - )] - fn into_app_for_update<'help>() -> Command<'help>; -} - -/// Converts an instance of [`ArgMatches`] to a user-defined container. -/// -/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`]. -pub trait FromArgMatches: Sized { - /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. - /// - /// Motivation: If our application had two CLI options, `--name - /// ` and the flag `--debug`, we may create a struct as follows: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// struct Context { - /// name: String, - /// debug: bool - /// } - /// ``` - /// - /// We then need to convert the `ArgMatches` that `clap` generated into our struct. - /// `from_arg_matches` serves as the equivalent of: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// # use clap::ArgMatches; - /// # struct Context { - /// # name: String, - /// # debug: bool - /// # } - /// impl From for Context { - /// fn from(m: ArgMatches) -> Self { - /// Context { - /// name: m.get_one::("name").unwrap().clone(), - /// debug: *m.get_one::("debug").expect("defaulted by clap"), - /// } - /// } - /// } - /// ``` - fn from_arg_matches(matches: &ArgMatches) -> Result; - - /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. - /// - /// Motivation: If our application had two CLI options, `--name - /// ` and the flag `--debug`, we may create a struct as follows: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// struct Context { - /// name: String, - /// debug: bool - /// } - /// ``` - /// - /// We then need to convert the `ArgMatches` that `clap` generated into our struct. - /// `from_arg_matches_mut` serves as the equivalent of: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// # use clap::ArgMatches; - /// # struct Context { - /// # name: String, - /// # debug: bool - /// # } - /// impl From for Context { - /// fn from(m: ArgMatches) -> Self { - /// Context { - /// name: m.get_one::("name").unwrap().to_string(), - /// debug: *m.get_one::("debug").expect("defaulted by clap"), - /// } - /// } - /// } - /// ``` - fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { - Self::from_arg_matches(matches) - } - - /// Assign values from `ArgMatches` to `self`. - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>; - - /// Assign values from `ArgMatches` to `self`. - fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { - self.update_from_arg_matches(matches) - } -} - -/// Parse a set of arguments into a user-defined container. -/// -/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`. -/// with: -/// - `#[clap(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl -/// `Args`. -/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. -/// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. -/// -/// **NOTE:** Deriving requires the `derive` feature flag -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[clap(flatten)] -/// logging: LogArgs, -/// } -/// -/// #[derive(clap::Args)] -/// struct LogArgs { -/// #[clap(long, short = 'v', parse(from_occurrences))] -/// verbose: i8, -/// } -/// ``` -pub trait Args: FromArgMatches + Sized { - /// Append to [`Command`] so it can instantiate `Self`. - /// - /// See also [`CommandFactory`]. - fn augment_args(cmd: Command<'_>) -> Command<'_>; - /// Append to [`Command`] so it can update `self`. - /// - /// This is used to implement `#[clap(flatten)]` - /// - /// See also [`CommandFactory`]. - fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>; -} - -/// Parse a sub-command into a user-defined enum. -/// -/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`. -/// with: -/// - `#[clap(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum -/// variants that impl `Subcommand`. -/// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl -/// `Subcommand`. -/// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. -/// -/// **NOTE:** Deriving requires the `derive` feature flag -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[clap(subcommand)] -/// action: Action, -/// } -/// -/// #[derive(clap::Subcommand)] -/// enum Action { -/// Add, -/// Remove, -/// } -/// ``` -pub trait Subcommand: FromArgMatches + Sized { - /// Append to [`Command`] so it can instantiate `Self`. - /// - /// See also [`CommandFactory`]. - fn augment_subcommands(cmd: Command<'_>) -> Command<'_>; - /// Append to [`Command`] so it can update `self`. - /// - /// This is used to implement `#[clap(flatten)]` - /// - /// See also [`CommandFactory`]. - fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>; - /// Test whether `Self` can parse a specific subcommand - fn has_subcommand(name: &str) -> bool; -} - -/// Parse arguments into enums. -/// -/// When deriving [`Parser`], a field whose type implements `ValueEnum` can have the attribute -/// `#[clap(value_enum)]` which will -/// - Call [`Arg::possible_values`][crate::Arg::possible_values] -/// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`. -/// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. -/// -/// **NOTE:** Deriving requires the `derive` feature flag -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[clap(value_enum)] -/// level: Level, -/// } -/// -/// #[derive(clap::ValueEnum, Clone)] -/// enum Level { -/// Debug, -/// Info, -/// Warning, -/// Error, -/// } -/// ``` -pub trait ValueEnum: Sized + Clone { - /// All possible argument values, in display order. - fn value_variants<'a>() -> &'a [Self]; - - /// Parse an argument into `Self`. - fn from_str(input: &str, ignore_case: bool) -> Result { - Self::value_variants() - .iter() - .find(|v| { - v.to_possible_value() - .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value") - .matches(input, ignore_case) - }) - .cloned() - .ok_or_else(|| format!("Invalid variant: {}", input)) - } - - /// The canonical argument value. - /// - /// The value is `None` for skipped variants. - fn to_possible_value<'a>(&self) -> Option>; -} - -impl Parser for Box { - fn parse() -> Self { - Box::new(::parse()) - } - - fn try_parse() -> Result { - ::try_parse().map(Box::new) - } - - fn parse_from(itr: I) -> Self - where - I: IntoIterator, - It: Into + Clone, - { - Box::new(::parse_from(itr)) - } - - fn try_parse_from(itr: I) -> Result - where - I: IntoIterator, - It: Into + Clone, - { - ::try_parse_from(itr).map(Box::new) - } -} - -#[allow(deprecated)] -impl CommandFactory for Box { - fn into_app<'help>() -> Command<'help> { - ::into_app() - } - fn into_app_for_update<'help>() -> Command<'help> { - ::into_app_for_update() - } -} - -impl FromArgMatches for Box { - fn from_arg_matches(matches: &ArgMatches) -> Result { - ::from_arg_matches(matches).map(Box::new) - } - fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { - ::from_arg_matches_mut(matches).map(Box::new) - } - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { - ::update_from_arg_matches(self, matches) - } - fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { - ::update_from_arg_matches_mut(self, matches) - } -} - -impl Args for Box { - fn augment_args(cmd: Command<'_>) -> Command<'_> { - ::augment_args(cmd) - } - fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> { - ::augment_args_for_update(cmd) - } -} - -impl Subcommand for Box { - fn augment_subcommands(cmd: Command<'_>) -> Command<'_> { - ::augment_subcommands(cmd) - } - fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> { - ::augment_subcommands_for_update(cmd) - } - fn has_subcommand(name: &str) -> bool { - ::has_subcommand(name) - } -} - -fn format_error(err: crate::Error) -> crate::Error { - let mut cmd = I::command(); - err.format(&mut cmd) -} diff --git a/vendor/clap/src/error/context.rs b/vendor/clap/src/error/context.rs deleted file mode 100644 index 985cd4d70..000000000 --- a/vendor/clap/src/error/context.rs +++ /dev/null @@ -1,55 +0,0 @@ -/// Semantics for a piece of error information -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum ContextKind { - /// The cause of the error - InvalidSubcommand, - /// The cause of the error - InvalidArg, - /// Existing arguments - PriorArg, - /// Accepted values - ValidValue, - /// Rejected values - InvalidValue, - /// Number of values present - ActualNumValues, - /// Number of allowed values - ExpectedNumValues, - /// Minimum number of allowed values - MinValues, - /// Number of occurrences present - ActualNumOccurrences, - /// Maximum number of allowed occurrences - MaxOccurrences, - /// Potential fix for the user - SuggestedCommand, - /// Potential fix for the user - SuggestedSubcommand, - /// Potential fix for the user - SuggestedArg, - /// Potential fix for the user - SuggestedValue, - /// Trailing argument - TrailingArg, - /// A usage string - Usage, - /// An opaque message to the user - Custom, -} - -/// A piece of error information -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum ContextValue { - /// [`ContextKind`] is self-sufficient, no additional information needed - None, - /// A single value - Bool(bool), - /// A single value - String(String), - /// Many values - Strings(Vec), - /// A single value - Number(isize), -} diff --git a/vendor/clap/src/error/kind.rs b/vendor/clap/src/error/kind.rs deleted file mode 100644 index 21256609a..000000000 --- a/vendor/clap/src/error/kind.rs +++ /dev/null @@ -1,440 +0,0 @@ -/// Command line argument parser kind of error -#[derive(Debug, Copy, Clone, PartialEq)] -#[non_exhaustive] -pub enum ErrorKind { - /// Occurs when an [`Arg`][crate::Arg] has a set of possible values, - /// and the user provides a value which isn't in that set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("speed") - /// .value_parser(["fast", "slow"])) - /// .try_get_matches_from(vec!["prog", "other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue); - /// ``` - InvalidValue, - - /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(arg!(--flag "some flag")) - /// .try_get_matches_from(vec!["prog", "--other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - UnknownArgument, - - /// Occurs when the user provides an unrecognized [`Subcommand`] which meets the threshold for - /// being similar enough to an existing subcommand. - /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, - /// the more general [`UnknownArgument`] error is returned. - /// - /// # Examples - /// - #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] - #[cfg_attr(feature = "suggestions", doc = " ```")] - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog", "confi"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`UnknownArgument`]: ErrorKind::UnknownArgument - InvalidSubcommand, - - /// Occurs when the user provides an unrecognized [`Subcommand`] which either - /// doesn't meet the threshold for being similar enough to an existing subcommand, - /// or the 'suggestions' feature is disabled. - /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. - /// - /// This error typically happens when passing additional subcommand names to the `help` - /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog", "help", "nothing"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`InvalidSubcommand`]: ErrorKind::InvalidSubcommand - /// [`UnknownArgument`]: ErrorKind::UnknownArgument - UnrecognizedSubcommand, - - /// Occurs when the user provides an empty value for an option that does not allow empty - /// values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("color") - /// .takes_value(true) - /// .forbid_empty_values(true) - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--color="]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); - /// ``` - EmptyValue, - - /// Occurs when the user doesn't use equals for an option that requires equal - /// sign to provide values. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("color") - /// .takes_value(true) - /// .require_equals(true) - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--color", "red"]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - NoEquals, - - /// Occurs when the user provides a value for an argument with a custom validation and the - /// value fails that validation. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// fn is_numeric(val: &str) -> Result<(), String> { - /// match val.parse::() { - /// Ok(..) => Ok(()), - /// Err(..) => Err(String::from("Value wasn't a number!")), - /// } - /// } - /// - /// let result = Command::new("prog") - /// .arg(Arg::new("num") - /// .validator(is_numeric)) - /// .try_get_matches_from(vec!["prog", "NotANumber"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation); - /// ``` - ValueValidation, - - /// Occurs when a user provides more values for an argument than were defined by setting - /// [`Arg::max_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("arg") - /// .max_values(2)) - /// .try_get_matches_from(vec!["prog", "too", "many", "values"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues); - /// ``` - /// [`Arg::max_values`]: crate::Arg::max_values() - TooManyValues, - - /// Occurs when the user provides fewer values for an argument than were defined by setting - /// [`Arg::min_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .min_values(3)) - /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues); - /// ``` - /// [`Arg::min_values`]: crate::Arg::min_values() - TooFewValues, - - /// Occurs when a user provides more occurrences for an argument than were defined by setting - /// [`Arg::max_occurrences`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("verbosity") - /// .short('v') - /// .max_occurrences(2)) - /// .try_get_matches_from(vec!["prog", "-vvv"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyOccurrences); - /// ``` - /// [`Arg::max_occurrences`]: crate::Arg::max_occurrences() - TooManyOccurrences, - - /// Occurs when the user provides a different number of values for an argument than what's - /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by - /// [`Arg::value_names`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .takes_value(true) - /// .number_of_values(2)) - /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// [`Arg::number_of_values`]: crate::Arg::number_of_values() - /// [`Arg::value_names`]: crate::Arg::value_names() - WrongNumberOfValues, - - /// Occurs when the user provides two values which conflict with each other and can't be used - /// together. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .conflicts_with("color")) - /// .arg(Arg::new("color") - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--debug", "--color"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - ArgumentConflict, - - /// Occurs when the user does not provide one or more required arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .required(true)) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - MissingRequiredArgument, - - /// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]), - /// but the user does not provide one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let err = Command::new("prog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`Command::subcommand_required`]: crate::Command::subcommand_required - MissingSubcommand, - - /// Occurs when the user provides multiple values to an argument which doesn't allow that. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .multiple_occurrences(false)) - /// .try_get_matches_from(vec!["prog", "--debug", "--debug"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage); - /// ``` - UnexpectedMultipleUsage, - - /// Occurs when the user provides a value containing invalid UTF-8. - /// - /// To allow arbitrary data - /// - Set [`Arg::allow_invalid_utf8`] for argument values - /// - Set [`Command::allow_invalid_utf8_for_external_subcommands`] for external-subcommand - /// values - /// - /// # Platform Specific - /// - /// Non-Windows platforms only (such as Linux, Unix, OSX, etc.) - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, Arg, ErrorKind}; - /// # use std::os::unix::ffi::OsStringExt; - /// # use std::ffi::OsString; - /// let result = Command::new("prog") - /// .arg(Arg::new("utf8") - /// .short('u') - /// .takes_value(true)) - /// .try_get_matches_from(vec![OsString::from("myprog"), - /// OsString::from("-u"), - /// OsString::from_vec(vec![0xE9])]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8); - /// ``` - /// - /// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8 - /// [`Command::allow_invalid_utf8_for_external_subcommands`]: crate::Command::allow_invalid_utf8_for_external_subcommands - InvalidUtf8, - - /// Not a true "error" as it means `--help` or similar was used. - /// The help message will be sent to `stdout`. - /// - /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will - /// be sent to `stderr` instead of `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .try_get_matches_from(vec!["prog", "--help"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp); - /// ``` - DisplayHelp, - - /// Occurs when either an argument or a [`Subcommand`] is required, as defined by - /// [`Command::arg_required_else_help`] , but the user did not provide - /// one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .arg_required_else_help(true) - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help - DisplayHelpOnMissingArgumentOrSubcommand, - - /// Not a true "error" as it means `--version` or similar was used. - /// The message will be sent to `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .version("3.0") - /// .try_get_matches_from(vec!["prog", "--version"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion); - /// ``` - DisplayVersion, - - /// Occurs when using the [`ArgMatches::value_of_t`] and friends to convert an argument value - /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument - /// with name `config` to be converted, but `config` wasn't used by the user. - /// - /// [`ArgMatches::value_of_t`]: crate::ArgMatches::value_of_t() - ArgumentNotFound, - - /// Represents an [I/O error]. - /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. - /// - /// [I/O error]: std::io::Error - Io, - - /// Represents a [Format error] (which is a part of [`Display`]). - /// Typically caused by writing to `stderr` or `stdout`. - /// - /// [`Display`]: std::fmt::Display - /// [Format error]: std::fmt::Error - Format, -} - -impl ErrorKind { - /// End-user description of the error case, where relevant - pub fn as_str(self) -> Option<&'static str> { - match self { - Self::InvalidValue => Some("One of the values isn't valid for an argument"), - Self::UnknownArgument => { - Some("Found an argument which wasn't expected or isn't valid in this context") - } - Self::InvalidSubcommand => Some("A subcommand wasn't recognized"), - Self::UnrecognizedSubcommand => Some("A subcommand wasn't recognized"), - Self::EmptyValue => Some("An argument requires a value but none was supplied"), - Self::NoEquals => Some("Equal is needed when assigning values to one of the arguments"), - Self::ValueValidation => Some("Invalid for for one of the arguments"), - Self::TooManyValues => Some("An argument received an unexpected value"), - Self::TooFewValues => Some("An argument requires more values"), - Self::TooManyOccurrences => Some("An argument occurred too many times"), - Self::WrongNumberOfValues => Some("An argument received too many or too few values"), - Self::ArgumentConflict => { - Some("An argument cannot be used with one or more of the other specified arguments") - } - Self::MissingRequiredArgument => { - Some("One or more required arguments were not provided") - } - Self::MissingSubcommand => Some("A subcommand is required but one was not provided"), - Self::UnexpectedMultipleUsage => { - Some("An argument was provided more than once but cannot be used multiple times") - } - Self::InvalidUtf8 => Some("Invalid UTF-8 was detected in one or more arguments"), - Self::DisplayHelp => None, - Self::DisplayHelpOnMissingArgumentOrSubcommand => None, - Self::DisplayVersion => None, - Self::ArgumentNotFound => Some("An argument wasn't found"), - Self::Io => None, - Self::Format => None, - } - } -} - -impl std::fmt::Display for ErrorKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.as_str().unwrap_or_default().fmt(f) - } -} diff --git a/vendor/clap/src/error/mod.rs b/vendor/clap/src/error/mod.rs deleted file mode 100644 index df9a84c56..000000000 --- a/vendor/clap/src/error/mod.rs +++ /dev/null @@ -1,1158 +0,0 @@ -//! Error reporting -#![allow(deprecated)] - -// Std -use std::{ - borrow::Cow, - convert::From, - error, - fmt::{self, Debug, Display, Formatter}, - io::{self, BufRead}, - result::Result as StdResult, -}; - -// Internal -use crate::output::fmt::Colorizer; -use crate::output::fmt::Stream; -use crate::parser::features::suggestions; -use crate::util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}; -use crate::AppSettings; -use crate::Command; - -mod context; -mod kind; - -pub use context::ContextKind; -pub use context::ContextValue; -pub use kind::ErrorKind; - -/// Short hand for [`Result`] type -/// -/// [`Result`]: std::result::Result -pub type Result = StdResult; - -/// Command Line Argument Parser Error -/// -/// See [`Command::error`] to create an error. -/// -/// [`Command::error`]: crate::Command::error -#[derive(Debug)] -pub struct Error { - inner: Box, - /// Deprecated, replaced with [`Error::kind()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Error::kind()`") - )] - pub kind: ErrorKind, - /// Deprecated, replaced with [`Error::context()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Error::context()`") - )] - pub info: Vec, -} - -#[derive(Debug)] -struct ErrorInner { - kind: ErrorKind, - context: Vec<(ContextKind, ContextValue)>, - message: Option, - source: Option>, - help_flag: Option<&'static str>, - color_when: ColorChoice, - wait_on_exit: bool, - backtrace: Option, -} - -impl Error { - /// Create an unformatted error - /// - /// This is for you need to pass the error up to - /// a place that has access to the `Command` at which point you can call [`Error::format`]. - /// - /// Prefer [`Command::error`] for generating errors. - /// - /// [`Command::error`]: crate::Command::error - pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { - Self::new(kind).set_message(message.to_string()) - } - - /// Format the existing message with the Command's context - #[must_use] - pub fn format(mut self, cmd: &mut Command) -> Self { - cmd._build_self(); - let usage = cmd.render_usage(); - if let Some(message) = self.inner.message.as_mut() { - message.format(cmd, usage); - } - self.with_cmd(cmd) - } - - /// Type of error for programmatic processing - pub fn kind(&self) -> ErrorKind { - self.inner.kind - } - - /// Additional information to further qualify the error - pub fn context(&self) -> impl Iterator { - self.inner.context.iter().map(|(k, v)| (*k, v)) - } - - /// Should the message be written to `stdout` or not? - #[inline] - pub fn use_stderr(&self) -> bool { - self.stream() == Stream::Stderr - } - - pub(crate) fn stream(&self) -> Stream { - match self.kind() { - ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => Stream::Stdout, - _ => Stream::Stderr, - } - } - - /// Prints the error and exits. - /// - /// Depending on the error kind, this either prints to `stderr` and exits with a status of `2` - /// or prints to `stdout` and exits with a status of `0`. - pub fn exit(&self) -> ! { - if self.use_stderr() { - // Swallow broken pipe errors - let _ = self.print(); - - if self.inner.wait_on_exit { - wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); - let mut s = String::new(); - let i = io::stdin(); - i.lock().read_line(&mut s).unwrap(); - } - - safe_exit(USAGE_CODE); - } - - // Swallow broken pipe errors - let _ = self.print(); - safe_exit(SUCCESS_CODE) - } - - /// Prints formatted and colored error to `stdout` or `stderr` according to its error kind - /// - /// # Example - /// ```no_run - /// use clap::Command; - /// - /// match Command::new("Command").try_get_matches() { - /// Ok(matches) => { - /// // do_something - /// }, - /// Err(err) => { - /// err.print().expect("Error writing Error"); - /// // do_something - /// }, - /// }; - /// ``` - pub fn print(&self) -> io::Result<()> { - self.formatted().print() - } - - /// Deprecated, replaced with [`Command::error`] - /// - /// [`Command::error`]: crate::Command::error - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::error`") - )] - #[doc(hidden)] - pub fn with_description(description: String, kind: ErrorKind) -> Self { - Error::raw(kind, description) - } - - fn new(kind: ErrorKind) -> Self { - Self { - inner: Box::new(ErrorInner { - kind, - context: Vec::new(), - message: None, - source: None, - help_flag: None, - color_when: ColorChoice::Never, - wait_on_exit: false, - backtrace: Backtrace::new(), - }), - kind, - info: vec![], - } - } - - #[inline(never)] - fn for_app(kind: ErrorKind, cmd: &Command, colorizer: Colorizer, info: Vec) -> Self { - Self::new(kind) - .set_message(colorizer) - .with_cmd(cmd) - .set_info(info) - } - - pub(crate) fn with_cmd(self, cmd: &Command) -> Self { - self.set_wait_on_exit(cmd.is_set(AppSettings::WaitOnError)) - .set_color(cmd.get_color()) - .set_help_flag(get_help_flag(cmd)) - } - - pub(crate) fn set_message(mut self, message: impl Into) -> Self { - self.inner.message = Some(message.into()); - self - } - - pub(crate) fn set_info(mut self, info: Vec) -> Self { - self.info = info; - self - } - - pub(crate) fn set_source(mut self, source: Box) -> Self { - self.inner.source = Some(source); - self - } - - pub(crate) fn set_color(mut self, color_when: ColorChoice) -> Self { - self.inner.color_when = color_when; - self - } - - pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self { - self.inner.help_flag = help_flag; - self - } - - pub(crate) fn set_wait_on_exit(mut self, yes: bool) -> Self { - self.inner.wait_on_exit = yes; - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - pub(crate) fn insert_context_unchecked( - mut self, - kind: ContextKind, - value: ContextValue, - ) -> Self { - self.inner.context.push((kind, value)); - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - pub(crate) fn extend_context_unchecked( - mut self, - context: [(ContextKind, ContextValue); N], - ) -> Self { - self.inner.context.extend(context); - self - } - - #[inline(never)] - fn get_context(&self, kind: ContextKind) -> Option<&ContextValue> { - self.inner - .context - .iter() - .find_map(|(k, v)| (*k == kind).then(|| v)) - } - - pub(crate) fn display_help(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app(ErrorKind::DisplayHelp, cmd, colorizer, vec![]) - } - - pub(crate) fn display_help_error(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app( - ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, - cmd, - colorizer, - vec![], - ) - } - - pub(crate) fn display_version(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app(ErrorKind::DisplayVersion, cmd, colorizer, vec![]) - } - - pub(crate) fn argument_conflict( - cmd: &Command, - arg: String, - mut others: Vec, - usage: String, - ) -> Self { - let info = others.clone(); - let others = match others.len() { - 0 => ContextValue::None, - 1 => ContextValue::String(others.pop().unwrap()), - _ => ContextValue::Strings(others), - }; - Self::new(ErrorKind::ArgumentConflict) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::PriorArg, others), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn empty_value(cmd: &Command, good_vals: &[&str], arg: String) -> Self { - let info = vec![arg.clone()]; - let mut err = Self::new(ErrorKind::EmptyValue) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]); - if !good_vals.is_empty() { - err = err.insert_context_unchecked( - ContextKind::ValidValue, - ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), - ); - } - err - } - - pub(crate) fn no_equals(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::NoEquals) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn invalid_value( - cmd: &Command, - bad_val: String, - good_vals: &[&str], - arg: String, - ) -> Self { - let mut info = vec![arg.clone(), bad_val.clone()]; - info.extend(good_vals.iter().map(|s| (*s).to_owned())); - - let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); - let mut err = Self::new(ErrorKind::InvalidValue) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(bad_val)), - ( - ContextKind::ValidValue, - ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), - ), - ]); - if let Some(suggestion) = suggestion { - err = err.insert_context_unchecked( - ContextKind::SuggestedValue, - ContextValue::String(suggestion), - ); - } - err - } - - pub(crate) fn invalid_subcommand( - cmd: &Command, - subcmd: String, - did_you_mean: String, - name: String, - usage: String, - ) -> Self { - let info = vec![subcmd.clone()]; - let suggestion = format!("{} -- {}", name, subcmd); - Self::new(ErrorKind::InvalidSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), - ( - ContextKind::SuggestedSubcommand, - ContextValue::String(did_you_mean), - ), - ( - ContextKind::SuggestedCommand, - ContextValue::String(suggestion), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unrecognized_subcommand(cmd: &Command, subcmd: String, usage: String) -> Self { - let info = vec![subcmd.clone()]; - Self::new(ErrorKind::UnrecognizedSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn missing_required_argument( - cmd: &Command, - required: Vec, - usage: String, - ) -> Self { - let info = required.clone(); - Self::new(ErrorKind::MissingRequiredArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::Strings(required)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn missing_subcommand(cmd: &Command, name: String, usage: String) -> Self { - let info = vec![]; - Self::new(ErrorKind::MissingSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(name)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn invalid_utf8(cmd: &Command, usage: String) -> Self { - let info = vec![]; - Self::new(ErrorKind::InvalidUtf8) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([(ContextKind::Usage, ContextValue::String(usage))]) - } - - pub(crate) fn too_many_occurrences( - cmd: &Command, - arg: String, - max_occurs: usize, - curr_occurs: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_occurs.to_string(), max_occurs.to_string()]; - Self::new(ErrorKind::TooManyOccurrences) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::MaxOccurrences, - ContextValue::Number(max_occurs as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_occurs as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn too_many_values(cmd: &Command, val: String, arg: String, usage: String) -> Self { - let info = vec![arg.clone(), val.clone()]; - Self::new(ErrorKind::TooManyValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn too_few_values( - cmd: &Command, - arg: String, - min_vals: usize, - curr_vals: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_vals.to_string(), min_vals.to_string()]; - Self::new(ErrorKind::TooFewValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::MinValues, - ContextValue::Number(min_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn value_validation( - arg: String, - val: String, - err: Box, - ) -> Self { - let info = vec![arg.clone(), val.to_string(), err.to_string()]; - Self::new(ErrorKind::ValueValidation) - .set_info(info) - .set_source(err) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - ]) - } - - pub(crate) fn wrong_number_of_values( - cmd: &Command, - arg: String, - num_vals: usize, - curr_vals: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_vals.to_string(), num_vals.to_string()]; - Self::new(ErrorKind::WrongNumberOfValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::ExpectedNumValues, - ContextValue::Number(num_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unexpected_multiple_usage(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::UnexpectedMultipleUsage) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unknown_argument( - cmd: &Command, - arg: String, - did_you_mean: Option<(String, Option)>, - usage: String, - ) -> Self { - let info = vec![arg.clone()]; - let mut err = Self::new(ErrorKind::UnknownArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]); - if let Some((flag, sub)) = did_you_mean { - err = err.insert_context_unchecked( - ContextKind::SuggestedArg, - ContextValue::String(format!("--{}", flag)), - ); - if let Some(sub) = sub { - err = err.insert_context_unchecked( - ContextKind::SuggestedSubcommand, - ContextValue::String(sub), - ); - } - } - err - } - - pub(crate) fn unnecessary_double_dash(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::UnknownArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::TrailingArg, ContextValue::Bool(true)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn argument_not_found_auto(arg: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::ArgumentNotFound) - .set_info(info) - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]) - } - - fn formatted(&self) -> Cow<'_, Colorizer> { - if let Some(message) = self.inner.message.as_ref() { - message.formatted() - } else { - let mut c = Colorizer::new(self.stream(), self.inner.color_when); - - start_error(&mut c); - - if !self.write_dynamic_context(&mut c) { - if let Some(msg) = self.kind().as_str() { - c.none(msg.to_owned()); - } else if let Some(source) = self.inner.source.as_ref() { - c.none(source.to_string()); - } else { - c.none("Unknown cause"); - } - } - - let usage = self.get_context(ContextKind::Usage); - if let Some(ContextValue::String(usage)) = usage { - put_usage(&mut c, usage); - } - - try_help(&mut c, self.inner.help_flag); - - Cow::Owned(c) - } - } - - #[must_use] - fn write_dynamic_context(&self, c: &mut Colorizer) -> bool { - match self.kind() { - ErrorKind::ArgumentConflict => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let prior_arg = self.get_context(ContextKind::PriorArg); - if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) = - (invalid_arg, prior_arg) - { - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' cannot be used with"); - - match prior_arg { - ContextValue::Strings(values) => { - c.none(":"); - for v in values { - c.none("\n "); - c.warning(&**v); - } - } - ContextValue::String(value) => { - c.none(" '"); - c.warning(value); - c.none("'"); - } - _ => { - c.none(" one or more of the other specified arguments"); - } - } - true - } else { - false - } - } - ErrorKind::EmptyValue => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires a value but none was supplied"); - - let possible_values = self.get_context(ContextKind::ValidValue); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - c.none("\n\t[possible values: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - c.good(escape(v)); - c.none(", "); - } - c.good(escape(last)); - } - c.none("]"); - } - true - } else { - false - } - } - ErrorKind::NoEquals => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("Equal sign is needed when assigning values to '"); - c.warning(invalid_arg); - c.none("'."); - true - } else { - false - } - } - ErrorKind::InvalidValue => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none(quote(invalid_value)); - c.none(" isn't a valid value for '"); - c.warning(invalid_arg); - c.none("'"); - - let possible_values = self.get_context(ContextKind::ValidValue); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - c.none("\n\t[possible values: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - c.good(escape(v)); - c.none(", "); - } - c.good(escape(last)); - } - c.none("]"); - } - - let suggestion = self.get_context(ContextKind::SuggestedValue); - if let Some(ContextValue::String(suggestion)) = suggestion { - c.none("\n\n\tDid you mean "); - c.good(quote(suggestion)); - c.none("?"); - } - true - } else { - false - } - } - ErrorKind::InvalidSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("The subcommand '"); - c.warning(invalid_sub); - c.none("' wasn't recognized"); - - let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); - if let Some(ContextValue::String(valid_sub)) = valid_sub { - c.none("\n\n\tDid you mean "); - c.good(valid_sub); - c.none("?"); - } - - let suggestion = self.get_context(ContextKind::SuggestedCommand); - if let Some(ContextValue::String(suggestion)) = suggestion { - c.none( - "\n\nIf you believe you received this message in error, try re-running with '", - ); - c.good(suggestion); - c.none("'"); - } - true - } else { - false - } - } - ErrorKind::UnrecognizedSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("The subcommand '"); - c.warning(invalid_sub); - c.none("' wasn't recognized"); - true - } else { - false - } - } - ErrorKind::MissingRequiredArgument => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg { - c.none("The following required arguments were not provided:"); - for v in invalid_arg { - c.none("\n "); - c.good(&**v); - } - true - } else { - false - } - } - ErrorKind::MissingSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("'"); - c.warning(invalid_sub); - c.none("' requires a subcommand but one was not provided"); - true - } else { - false - } - } - ErrorKind::InvalidUtf8 => false, - ErrorKind::TooManyOccurrences => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_occurs = self.get_context(ContextKind::ActualNumOccurrences); - let max_occurs = self.get_context(ContextKind::MaxOccurrences); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_occurs)), - Some(ContextValue::Number(max_occurs)), - ) = (invalid_arg, actual_num_occurs, max_occurs) - { - let were_provided = Error::singular_or_plural(*actual_num_occurs as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' allows at most "); - c.warning(max_occurs.to_string()); - c.none(" occurrences but "); - c.warning(actual_num_occurs.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::TooManyValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none("The value '"); - c.warning(invalid_value); - c.none("' was provided to '"); - c.warning(invalid_arg); - c.none("' but it wasn't expecting any more values"); - true - } else { - false - } - } - ErrorKind::TooFewValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_values = self.get_context(ContextKind::ActualNumValues); - let min_values = self.get_context(ContextKind::MinValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(min_values)), - ) = (invalid_arg, actual_num_values, min_values) - { - let were_provided = Error::singular_or_plural(*actual_num_values as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires at least "); - c.warning(min_values.to_string()); - c.none(" values but only "); - c.warning(actual_num_values.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::ValueValidation => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none("Invalid value "); - c.warning(quote(invalid_value)); - c.none(" for '"); - c.warning(invalid_arg); - if let Some(source) = self.inner.source.as_deref() { - c.none("': "); - c.none(source.to_string()); - } else { - c.none("'"); - } - true - } else { - false - } - } - ErrorKind::WrongNumberOfValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_values = self.get_context(ContextKind::ActualNumValues); - let num_values = self.get_context(ContextKind::ExpectedNumValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(num_values)), - ) = (invalid_arg, actual_num_values, num_values) - { - let were_provided = Error::singular_or_plural(*actual_num_values as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires "); - c.warning(num_values.to_string()); - c.none(" values, but "); - c.warning(actual_num_values.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::UnexpectedMultipleUsage => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg.to_string()); - c.none("' was provided more than once, but cannot be used multiple times"); - true - } else { - false - } - } - ErrorKind::UnknownArgument => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("Found argument '"); - c.warning(invalid_arg.to_string()); - c.none("' which wasn't expected, or isn't valid in this context"); - - let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); - let valid_arg = self.get_context(ContextKind::SuggestedArg); - match (valid_sub, valid_arg) { - ( - Some(ContextValue::String(valid_sub)), - Some(ContextValue::String(valid_arg)), - ) => { - c.none("\n\n\tDid you mean "); - c.none("to put '"); - c.good(valid_arg); - c.none("' after the subcommand '"); - c.good(valid_sub); - c.none("'?"); - } - (None, Some(ContextValue::String(valid_arg))) => { - c.none("\n\n\tDid you mean '"); - c.good(valid_arg); - c.none("'?"); - } - (_, _) => {} - } - - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - if invalid_arg.starts_with('-') { - c.none(format!( - "\n\n\tIf you tried to supply `{}` as a value rather than a flag, use `-- {}`", - invalid_arg, invalid_arg - )); - } - - let trailing_arg = self.get_context(ContextKind::TrailingArg); - if trailing_arg == Some(&ContextValue::Bool(true)) { - c.none(format!( - "\n\n\tIf you tried to supply `{}` as a subcommand, remove the '--' before it.", - invalid_arg - )); - } - } - true - } else { - false - } - } - ErrorKind::ArgumentNotFound => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg.to_string()); - c.none("' wasn't found"); - true - } else { - false - } - } - ErrorKind::DisplayHelp - | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand - | ErrorKind::DisplayVersion - | ErrorKind::Io - | ErrorKind::Format => false, - } - } - - /// Returns the singular or plural form on the verb to be based on the argument's value. - fn singular_or_plural(n: usize) -> &'static str { - if n > 1 { - " were provided" - } else { - " was provided" - } - } -} - -impl From for Error { - fn from(e: io::Error) -> Self { - Error::raw(ErrorKind::Io, e) - } -} - -impl From for Error { - fn from(e: fmt::Error) -> Self { - Error::raw(ErrorKind::Format, e) - } -} - -impl error::Error for Error { - #[allow(trivial_casts)] - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - self.inner.source.as_ref().map(|e| e.as_ref() as _) - } -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // Assuming `self.message` already has a trailing newline, from `try_help` or similar - write!(f, "{}", self.formatted())?; - if let Some(backtrace) = self.inner.backtrace.as_ref() { - writeln!(f)?; - writeln!(f, "Backtrace:")?; - writeln!(f, "{}", backtrace)?; - } - Ok(()) - } -} - -fn start_error(c: &mut Colorizer) { - c.error("error:"); - c.none(" "); -} - -fn put_usage(c: &mut Colorizer, usage: impl Into) { - c.none("\n\n"); - c.none(usage); -} - -fn get_help_flag(cmd: &Command) -> Option<&'static str> { - if !cmd.is_disable_help_flag_set() { - Some("--help") - } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() { - Some("help") - } else { - None - } -} - -fn try_help(c: &mut Colorizer, help: Option<&str>) { - if let Some(help) = help { - c.none("\n\nFor more information try "); - c.good(help); - c.none("\n"); - } else { - c.none("\n"); - } -} - -fn quote(s: impl AsRef) -> String { - let s = s.as_ref(); - format!("{:?}", s) -} - -fn escape(s: impl AsRef) -> String { - let s = s.as_ref(); - if s.contains(char::is_whitespace) { - quote(s) - } else { - s.to_owned() - } -} - -#[derive(Clone, Debug)] -pub(crate) enum Message { - Raw(String), - Formatted(Colorizer), -} - -impl Message { - fn format(&mut self, cmd: &Command, usage: String) { - match self { - Message::Raw(s) => { - let mut c = Colorizer::new(Stream::Stderr, cmd.get_color()); - - let mut message = String::new(); - std::mem::swap(s, &mut message); - start_error(&mut c); - c.none(message); - put_usage(&mut c, usage); - try_help(&mut c, get_help_flag(cmd)); - *self = Self::Formatted(c); - } - Message::Formatted(_) => {} - } - } - - fn formatted(&self) -> Cow { - match self { - Message::Raw(s) => { - let mut c = Colorizer::new(Stream::Stderr, ColorChoice::Never); - start_error(&mut c); - c.none(s); - Cow::Owned(c) - } - Message::Formatted(c) => Cow::Borrowed(c), - } - } -} - -impl From for Message { - fn from(inner: String) -> Self { - Self::Raw(inner) - } -} - -impl From for Message { - fn from(inner: Colorizer) -> Self { - Self::Formatted(inner) - } -} - -#[cfg(feature = "debug")] -#[derive(Debug)] -struct Backtrace(backtrace::Backtrace); - -#[cfg(feature = "debug")] -impl Backtrace { - fn new() -> Option { - Some(Self(backtrace::Backtrace::new())) - } -} - -#[cfg(feature = "debug")] -impl Display for Backtrace { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // `backtrace::Backtrace` uses `Debug` instead of `Display` - write!(f, "{:?}", self.0) - } -} - -#[cfg(not(feature = "debug"))] -#[derive(Debug)] -struct Backtrace; - -#[cfg(not(feature = "debug"))] -impl Backtrace { - fn new() -> Option { - None - } -} - -#[cfg(not(feature = "debug"))] -impl Display for Backtrace { - fn fmt(&self, _: &mut Formatter) -> fmt::Result { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - /// Check `clap::Error` impls Send and Sync. - mod clap_error_impl_send_sync { - use crate::Error; - trait Foo: std::error::Error + Send + Sync + 'static {} - impl Foo for Error {} - } -} diff --git a/vendor/clap/src/lib.rs b/vendor/clap/src/lib.rs deleted file mode 100644 index d9a97715f..000000000 --- a/vendor/clap/src/lib.rs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/graphs/contributors). -// Licensed under the MIT license -// (see LICENSE or ) All files in the project carrying such -// notice may not be copied, modified, or distributed except according to those terms. - -#![cfg_attr(docsrs, feature(doc_auto_cfg))] -#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] -#![cfg_attr(feature = "derive", doc = include_str!("../README.md"))] -//! -#![warn( - missing_docs, - missing_debug_implementations, - missing_copy_implementations, - trivial_casts, - unused_allocation, - trivial_numeric_casts, - clippy::single_char_pattern -)] -#![forbid(unsafe_code)] -// HACK https://github.com/rust-lang/rust-clippy/issues/7290 -#![allow(clippy::single_component_path_imports)] -#![allow(clippy::branches_sharing_code)] -// Doesn't allow for debug statements, etc to be unique -#![allow(clippy::if_same_then_else)] - -#[cfg(not(feature = "std"))] -compile_error!("`std` feature is currently required to build `clap`"); - -pub use crate::builder::ArgAction; -pub use crate::builder::Command; -pub use crate::builder::{Arg, ArgGroup}; -pub use crate::error::Error; -pub use crate::parser::ArgMatches; -#[cfg(feature = "color")] -pub use crate::util::color::ColorChoice; -#[cfg(not(feature = "color"))] -#[allow(unused_imports)] -pub(crate) use crate::util::color::ColorChoice; - -pub use crate::derive::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; - -#[allow(deprecated)] -pub use crate::builder::App; -pub use crate::builder::{AppFlags, AppSettings, ArgFlags, ArgSettings, PossibleValue, ValueHint}; -pub use crate::error::{ErrorKind, Result}; -#[allow(deprecated)] -pub use crate::parser::{Indices, OsValues, ValueSource, Values}; - -#[cfg(feature = "yaml")] -#[doc(hidden)] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) -)] -#[doc(hidden)] -pub use yaml_rust::YamlLoader; - -#[cfg(feature = "derive")] -#[doc(hidden)] -pub use clap_derive::{self, *}; - -/// Deprecated, replaced with [`CommandFactory`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `CommandFactory`") -)] -pub use CommandFactory as IntoApp; -/// Deprecated, replaced with [`Parser`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Parser`") -)] -#[doc(hidden)] -pub use Parser as StructOpt; -/// Deprecated, replaced with [`ValueEnum`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ValueEnum`") -)] -pub use ValueEnum as ArgEnum; - -#[cfg(any(feature = "derive", feature = "cargo"))] -#[doc(hidden)] -pub use once_cell; - -#[macro_use] -#[allow(missing_docs)] -mod macros; - -mod derive; - -#[cfg(feature = "regex")] -pub use crate::builder::RegexRef; - -pub mod builder; -pub mod error; -pub mod parser; - -mod mkeymap; -mod output; -mod util; - -const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ - report at https://github.com/clap-rs/clap/issues"; -const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; - -/// Deprecated, replaced with [`Command::new`], unless you were looking for [Subcommand] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `Command::new` unless you intended the `Subcommand` trait" - ) -)] -#[doc(hidden)] -#[derive(Debug, Copy, Clone)] -pub struct SubCommand {} - -#[allow(deprecated)] -impl SubCommand { - /// Deprecated, replaced with [`Command::new`]. - /// Did you mean Subcommand (lower-case c)? - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::new`") - )] - #[doc(hidden)] - pub fn with_name<'help>(name: &str) -> App<'help> { - Command::new(name) - } - - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - #[cfg(feature = "yaml")] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) - )] - #[doc(hidden)] - pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App { - #![allow(deprecated)] - Command::from_yaml(yaml) - } -} diff --git a/vendor/clap/src/macros.rs b/vendor/clap/src/macros.rs deleted file mode 100644 index 0b671a37a..000000000 --- a/vendor/clap/src/macros.rs +++ /dev/null @@ -1,1062 +0,0 @@ -/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? -#[cfg(feature = "yaml")] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) -)] -#[doc(hidden)] -#[macro_export] -macro_rules! load_yaml { - ($yaml:expr) => { - &$crate::YamlLoader::load_from_str(include_str!($yaml)).expect("failed to load YAML file") - [0] - }; -} - -/// Deprecated, replaced with [`ArgMatches::value_of_t`][crate::ArgMatches::value_of_t] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::value_of_t`") -)] -#[doc(hidden)] -macro_rules! value_t { - ($m:ident, $v:expr, $t:ty) => { - $crate::value_t!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - $m.value_of_t::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::value_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `ArgMatches::value_of_t_or_exit`" - ) -)] -#[doc(hidden)] -macro_rules! value_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - value_t_or_exit!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - $m.value_of_t_or_exit::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::values_of_t`][crate::ArgMatches::value_of_t] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::values_of_t`") -)] -#[doc(hidden)] -macro_rules! values_t { - ($m:ident, $v:expr, $t:ty) => { - values_t!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - $m.values_of_t::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::values_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `ArgMatches::values_of_t_or_exit`" - ) -)] -#[doc(hidden)] -macro_rules! values_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - values_t_or_exit!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - $m.values_of_t_or_exit::<$t>($v) - }; -} - -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`") -)] -#[doc(hidden)] -#[macro_export] -macro_rules! _clap_count_exprs { - () => { 0 }; - ($e:expr) => { 1 }; - ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; -} - -/// Deprecated, replaced with [`ArgEnum`][crate::ArgEnum] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`") -)] -#[doc(hidden)] -#[macro_export] -macro_rules! arg_enum { - (@as_item $($i:item)*) => ($($i)*); - (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { - $crate::arg_enum!(@as_item - $($tts)* - - impl ::std::str::FromStr for $e { - type Err = String; - - fn from_str(s: &str) -> ::std::result::Result { - #[allow(deprecated, unused_imports)] - use ::std::ascii::AsciiExt; - match s { - $(stringify!($v) | - _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, - _ => Err({ - let v = vec![ - $(stringify!($v),)+ - ]; - format!("valid values: {}", - v.join(", ")) - }), - } - } - } - impl ::std::fmt::Display for $e { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { - $($e::$v => write!(f, stringify!($v)),)+ - } - } - } - impl $e { - #[allow(dead_code)] - pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { - [ - $(stringify!($v),)+ - ] - } - }); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; -} - -/// Allows you to pull the version from your Cargo.toml at compile time as -/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .version(crate_version!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_version { - () => { - env!("CARGO_PKG_VERSION") - }; -} - -/// Allows you to pull the authors for the command from your Cargo.toml at -/// compile time in the form: -/// `"author1 lastname :author2 lastname "` -/// -/// You can replace the colons with a custom separator by supplying a -/// replacement string, so, for example, -/// `crate_authors!(",\n")` would become -/// `"author1 lastname ,\nauthor2 lastname ,\nauthor3 lastname "` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .author(crate_authors!("\n")) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_authors { - ($sep:expr) => {{ - static CACHED: clap::once_cell::sync::Lazy = - clap::once_cell::sync::Lazy::new(|| env!("CARGO_PKG_AUTHORS").replace(':', $sep)); - - let s: &'static str = &*CACHED; - s - }}; - () => { - env!("CARGO_PKG_AUTHORS") - }; -} - -/// Allows you to pull the description from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .about(crate_description!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_description { - () => { - env!("CARGO_PKG_DESCRIPTION") - }; -} - -/// Allows you to pull the name from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new(crate_name!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_name { - () => { - env!("CARGO_PKG_NAME") - }; -} - -/// Allows you to build the `Command` instance from your Cargo.toml at compile time. -/// -/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, -/// and therefore won't change the generated output until you recompile. -/// -/// In some cases you can "trick" the compiler into triggering a rebuild when your -/// `Cargo.toml` is changed by including this in your `src/main.rs` file -/// `include_str!("../Cargo.toml");` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let m = command!().get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! command { - () => {{ - $crate::command!($crate::crate_name!()) - }}; - ($name:expr) => {{ - let mut cmd = $crate::Command::new($name).version($crate::crate_version!()); - - let author = $crate::crate_authors!(); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; -} - -/// Requires `cargo` feature flag to be enabled. -#[cfg(not(feature = "cargo"))] -#[macro_export] -macro_rules! command { - () => {{ - compile_error!("`cargo` feature flag is required"); - }}; - ($name:expr) => {{ - compile_error!("`cargo` feature flag is required"); - }}; -} - -/// Deprecated, replaced with [`clap::command!`][crate::command] -#[cfg(feature = "cargo")] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `clap::command!") -)] -#[macro_export] -macro_rules! app_from_crate { - () => {{ - let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); - - let author = $crate::crate_authors!(", "); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; - ($sep:expr) => {{ - let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); - - let author = $crate::crate_authors!($sep); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! arg_impl { - ( @string $val:ident ) => { - stringify!($val) - }; - ( @string $val:literal ) => {{ - let ident_or_string_literal: &str = $val; - ident_or_string_literal - }}; - ( @string $val:tt ) => { - ::std::compile_error!("Only identifiers or string literals supported"); - }; - ( @string ) => { - None - }; - - ( @char $val:ident ) => {{ - let ident_or_char_literal = stringify!($val); - debug_assert_eq!( - ident_or_char_literal.len(), - 1, - "Single-letter identifier expected, got {}", - ident_or_char_literal - ); - ident_or_char_literal.chars().next().unwrap() - }}; - ( @char $val:literal ) => {{ - let ident_or_char_literal: char = $val; - ident_or_char_literal - }}; - ( @char ) => {{ - None - }}; - - ( - @arg - ($arg:expr) - --$long:ident - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id().is_empty() { - arg = arg.id(long); - } - arg.long(long) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - --$long:literal - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id().is_empty() { - arg = arg.id(long); - } - arg.long(long) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - -$short:ident - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - $arg.short($crate::arg_impl! { @char $short }) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - -$short:literal - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - $arg.short($crate::arg_impl! { @char $short }) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - <$value_name:ident> - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - arg = arg.required(true); - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - <$value_name:literal> - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - arg = arg.required(true); - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - [$value_name:ident] - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.min_values(0).max_values(1); - } - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - [$value_name:literal] - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.min_values(0).max_values(1); - } - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - ... - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({#[allow(deprecated)]{ - $arg.multiple_occurrences(true) - }}) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - $help:literal - ) => { - $arg.help($help) - }; - ( - @arg - ($arg:expr) - ) => { - $arg - }; -} - -/// Create an [`Arg`] from a usage string. -/// -/// Allows creation of basic settings for the [`Arg`]. -/// -/// **NOTE**: Not all settings may be set using the usage string method. Some properties are -/// only available via the builder pattern. -/// -/// # Syntax -/// -/// Usage strings typically following the form: -/// -/// ```notrust -/// [explicit name] [short] [long] [value names] [...] [help string] -/// ``` -/// -/// ### Explicit Name -/// -/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or -/// `"name":`. -/// -/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional -/// fields as the name using the following priority order: -/// -/// 1. Explicit Name -/// 2. Long -/// 3. Value Name -/// -/// See [`Arg::name`][crate::Arg::name]. -/// -/// ### Short -/// -/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or -/// `-'f'`. -/// -/// See [`Arg::short`][crate::Arg::short]. -/// -/// ### Long -/// -/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or -/// `--"foo"`. -/// -/// See [`Arg::long`][crate::Arg::long]. -/// -/// ### Values (Value Notation) -/// -/// This is set by placing bare-word between: -/// - `[]` like `[FOO]` -/// - Positional argument: optional -/// - Named argument: optional value -/// - `<>` like ``: required -/// -/// See [`Arg::value_name`][crate::Arg::value_name]. -/// -/// ### `...` -/// -/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple -/// times (not to be confused with multiple values per occurrence). -/// -/// See [`Arg::multiple_occurrences`][crate::Arg::multiple_occurrences]. -/// -/// ### Help String -/// -/// The help string is denoted between a pair of double quotes `""` and may contain any -/// characters. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, arg}; -/// Command::new("prog") -/// .args(&[ -/// arg!(--config "a required file for the configuration and no short"), -/// arg!(-d --debug ... "turns on debugging information and allows multiples"), -/// arg!([input] "an optional input file to use") -/// ]) -/// # ; -/// ``` -/// [`Arg`]: ./struct.Arg.html -#[macro_export] -macro_rules! arg { - ( $name:ident: $($tail:tt)+ ) => { - $crate::arg_impl! { - @arg ($crate::Arg::new($crate::arg_impl! { @string $name })) $($tail)+ - } - }; - ( $($tail:tt)+ ) => {{ - let arg = $crate::arg_impl! { - @arg ($crate::Arg::default()) $($tail)+ - }; - debug_assert!(!arg.get_id().is_empty(), "Without a value or long flag, the `name:` prefix is required"); - arg - }}; -} - -/// Deprecated, replaced with [`clap::Parser`][crate::Parser] and [`clap::arg!`][crate::arg] (Issue clap-rs/clap#2835) -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `clap::Parser` for a declarative API (Issue clap-rs/clap#2835)" - ) -)] -#[doc(hidden)] -#[macro_export] -macro_rules! clap_app { - (@app ($builder:expr)) => { $builder }; - (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.arg( - $crate::clap_app!{ @arg ($crate::Arg::new($name)) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.arg( - $crate::clap_app!{ @arg ($crate::Arg::new(stringify!($name))) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.setting($crate::AppSettings::$setting)) - $($tt)* - } - }; -// Treat the application builder as an argument to set its attributes - (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } - }; - (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name))) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(false)) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(true)) $($tail)* }) - $($tt)* - } - }; -// Handle subcommand creation - (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.subcommand( - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } - )) - $($tt)* - } - }; -// Yaml like function calls - used for setting various meta directly against the app - (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { -// $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } - $crate::clap_app!{ @app - ($builder.$ident($($v),*)) - $($tt)* - } - }; - -// Add members to group and continue argument handling with the parent builder - (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; - // Treat the group builder as an argument to set its attributes - (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @group ($builder, $crate::clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } - }; - (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @group - ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, - $group.arg(stringify!($name))) - $($tt)* - } - }; - -// No more tokens to munch - (@arg ($arg:expr) $modes:tt) => { $arg }; -// Shorthand tokens influenced by the usage_string - (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* } - }; - (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } - }; - (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } - }; - (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes +multiple +takes_value $($tail)* } - }; -// Shorthand magic - (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* } - }; -// !foo -> .foo(false) - (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } - }; -// +foo -> .foo(true) - (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } - }; -// Validator - (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } - }; - (@as_expr $expr:expr) => { $expr }; -// Help - (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help($crate::clap_app!{ @as_expr $desc }) }; -// Handle functions that need to be called multiple times for each argument - (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } - }; -// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; -// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; - -// Build a subcommand outside of an app. - (@subcommand $name:ident => $($tail:tt)*) => { - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } - }; -// Start the magic - (($name:expr) => $($tail:tt)*) => {{ - $crate::clap_app!{ @app ($crate::Command::new($name)) $($tail)*} - }}; - - ($name:ident => $($tail:tt)*) => {{ - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)*} - }}; -} - -macro_rules! impl_settings { - ($settings:ident, $flags:ident, - $( - $(#[$inner:ident $($args:tt)*])* - $setting:ident => $flag:path - ),+ - ) => { - impl $flags { - #[allow(dead_code)] - pub(crate) fn empty() -> Self { - $flags(Flags::empty()) - } - - #[allow(dead_code)] - pub(crate) fn insert(&mut self, rhs: Self) { - self.0.insert(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn remove(&mut self, rhs: Self) { - self.0.remove(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn set(&mut self, s: $settings) { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.insert($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn unset(&mut self, s: $settings) { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.remove($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn is_set(&self, s: $settings) -> bool { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.contains($flag), - )* - } - } - } - - impl BitOr for $flags { - type Output = Self; - - fn bitor(mut self, rhs: Self) -> Self::Output { - self.0.insert(rhs.0); - self - } - } - - impl From<$settings> for $flags { - fn from(setting: $settings) -> Self { - let mut flags = $flags::empty(); - flags.set(setting); - flags - } - } - - impl BitOr<$settings> for $flags { - type Output = Self; - - fn bitor(mut self, rhs: $settings) -> Self::Output { - self.set(rhs); - self - } - } - - impl BitOr for $settings { - type Output = $flags; - - fn bitor(self, rhs: Self) -> Self::Output { - let mut flags = $flags::empty(); - flags.set(self); - flags.set(rhs); - flags - } - } - } -} - -// Convenience for writing to stderr thanks to https://github.com/BurntSushi -macro_rules! wlnerr { - ($($arg:tt)*) => ({ - use std::io::{Write, stderr}; - writeln!(&mut stderr(), $($arg)*).ok(); - }) -} - -#[cfg(feature = "debug")] -macro_rules! debug { - ($($arg:tt)*) => ({ - let prefix = format!("[{:>w$}] \t", module_path!(), w = 28); - let body = format!($($arg)*); - let mut color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto); - color.hint(prefix); - color.hint(body); - color.none("\n"); - let _ = color.print(); - }) -} - -#[cfg(not(feature = "debug"))] -macro_rules! debug { - ($($arg:tt)*) => {}; -} diff --git a/vendor/clap/src/mkeymap.rs b/vendor/clap/src/mkeymap.rs deleted file mode 100644 index 97ecdda77..000000000 --- a/vendor/clap/src/mkeymap.rs +++ /dev/null @@ -1,193 +0,0 @@ -use std::iter::Iterator; -use std::ops::Index; -use std::{ffi::OsStr, ffi::OsString}; - -use crate::util::Id; -use crate::Arg; -use crate::INTERNAL_ERROR_MSG; - -#[derive(PartialEq, Eq, Debug, Clone)] -pub(crate) struct Key { - key: KeyType, - index: usize, -} - -#[derive(Default, PartialEq, Eq, Debug, Clone)] -pub(crate) struct MKeyMap<'help> { - /// All of the arguments. - args: Vec>, - - // Cache part: - /// Will be set after `_build()`. - keys: Vec, -} - -#[derive(Debug, PartialEq, Eq, Hash, Clone)] -pub(crate) enum KeyType { - Short(char), - Long(OsString), - Position(usize), -} - -impl KeyType { - pub(crate) fn is_position(&self) -> bool { - matches!(self, KeyType::Position(_)) - } -} - -impl PartialEq for KeyType { - fn eq(&self, rhs: &usize) -> bool { - match self { - KeyType::Position(x) => x == rhs, - _ => false, - } - } -} - -impl PartialEq<&str> for KeyType { - fn eq(&self, rhs: &&str) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq for KeyType { - fn eq(&self, rhs: &str) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq for KeyType { - fn eq(&self, rhs: &OsStr) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq for KeyType { - fn eq(&self, rhs: &char) -> bool { - match self { - KeyType::Short(c) => c == rhs, - _ => false, - } - } -} - -impl<'help> MKeyMap<'help> { - /// If any arg has corresponding key in this map, we can search the key with - /// u64(for positional argument), char(for short flag), &str and OsString - /// (for long flag) - pub(crate) fn contains(&self, key: K) -> bool - where - KeyType: PartialEq, - { - self.keys.iter().any(|x| x.key == key) - } - - /// Reserves capacity for at least additional more elements to be inserted - pub(crate) fn reserve(&mut self, additional: usize) { - self.args.reserve(additional); - } - - /// Push an argument in the map. - pub(crate) fn push(&mut self, new_arg: Arg<'help>) { - self.args.push(new_arg); - } - - /// Find the arg have corresponding key in this map, we can search the key - /// with u64(for positional argument), char(for short flag), &str and - /// OsString (for long flag) - pub(crate) fn get(&self, key: &K) -> Option<&Arg<'help>> - where - KeyType: PartialEq, - { - self.keys - .iter() - .find(|k| &k.key == key) - .map(|k| &self.args[k.index]) - } - - /// Find out if the map have no arg. - pub(crate) fn is_empty(&self) -> bool { - self.args.is_empty() - } - - /// Return iterators of all keys. - pub(crate) fn keys(&self) -> impl Iterator { - self.keys.iter().map(|x| &x.key) - } - - /// Return iterators of all args. - pub(crate) fn args(&self) -> impl Iterator> { - self.args.iter() - } - - /// Return mutable iterators of all args. - pub(crate) fn args_mut<'map>(&'map mut self) -> impl Iterator> { - self.args.iter_mut() - } - - /// We need a lazy build here since some we may change args after creating - /// the map, you can checkout who uses `args_mut`. - pub(crate) fn _build(&mut self) { - for (i, arg) in self.args.iter().enumerate() { - append_keys(&mut self.keys, arg, i); - } - } - - /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return - /// `Some(arg)` if removed. - pub(crate) fn remove_by_name(&mut self, name: &Id) -> Option> { - self.args - .iter() - .position(|arg| &arg.id == name) - // since it's a cold function, using this wouldn't hurt much - .map(|i| self.args.remove(i)) - } - - /// Remove an arg based on index - pub(crate) fn remove(&mut self, index: usize) -> Arg<'help> { - self.args.remove(index) - } -} - -impl<'help> Index<&'_ KeyType> for MKeyMap<'help> { - type Output = Arg<'help>; - - fn index(&self, key: &KeyType) -> &Self::Output { - self.get(key).expect(INTERNAL_ERROR_MSG) - } -} - -/// Generate key types for an specific Arg. -fn append_keys(keys: &mut Vec, arg: &Arg, index: usize) { - if let Some(pos_index) = arg.index { - let key = KeyType::Position(pos_index); - keys.push(Key { key, index }); - } else { - if let Some(short) = arg.short { - let key = KeyType::Short(short); - keys.push(Key { key, index }); - } - if let Some(long) = arg.long { - let key = KeyType::Long(OsString::from(long)); - keys.push(Key { key, index }); - } - - for (short, _) in arg.short_aliases.iter() { - let key = KeyType::Short(*short); - keys.push(Key { key, index }); - } - for (long, _) in arg.aliases.iter() { - let key = KeyType::Long(OsString::from(long)); - keys.push(Key { key, index }); - } - } -} diff --git a/vendor/clap/src/output/fmt.rs b/vendor/clap/src/output/fmt.rs deleted file mode 100644 index dc1f46e08..000000000 --- a/vendor/clap/src/output/fmt.rs +++ /dev/null @@ -1,158 +0,0 @@ -use crate::util::color::ColorChoice; - -use std::{ - fmt::{self, Display, Formatter}, - io::{self, Write}, -}; - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum Stream { - Stdout, - Stderr, -} - -#[derive(Clone, Debug)] -pub(crate) struct Colorizer { - stream: Stream, - #[allow(unused)] - color_when: ColorChoice, - pieces: Vec<(String, Style)>, -} - -impl Colorizer { - #[inline(never)] - pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self { - Colorizer { - stream, - color_when, - pieces: vec![], - } - } - - #[inline(never)] - pub(crate) fn good(&mut self, msg: impl Into) { - self.pieces.push((msg.into(), Style::Good)); - } - - #[inline(never)] - pub(crate) fn warning(&mut self, msg: impl Into) { - self.pieces.push((msg.into(), Style::Warning)); - } - - #[inline(never)] - pub(crate) fn error(&mut self, msg: impl Into) { - self.pieces.push((msg.into(), Style::Error)); - } - - #[inline(never)] - #[allow(dead_code)] - pub(crate) fn hint(&mut self, msg: impl Into) { - self.pieces.push((msg.into(), Style::Hint)); - } - - #[inline(never)] - pub(crate) fn none(&mut self, msg: impl Into) { - self.pieces.push((msg.into(), Style::Default)); - } -} - -/// Printing methods. -impl Colorizer { - #[cfg(feature = "color")] - pub(crate) fn print(&self) -> io::Result<()> { - use termcolor::{BufferWriter, ColorChoice as DepColorChoice, ColorSpec, WriteColor}; - - let color_when = match self.color_when { - ColorChoice::Always => DepColorChoice::Always, - ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto, - _ => DepColorChoice::Never, - }; - - let writer = match self.stream { - Stream::Stderr => BufferWriter::stderr(color_when), - Stream::Stdout => BufferWriter::stdout(color_when), - }; - - let mut buffer = writer.buffer(); - - for piece in &self.pieces { - let mut color = ColorSpec::new(); - match piece.1 { - Style::Good => { - color.set_fg(Some(termcolor::Color::Green)); - } - Style::Warning => { - color.set_fg(Some(termcolor::Color::Yellow)); - } - Style::Error => { - color.set_fg(Some(termcolor::Color::Red)); - color.set_bold(true); - } - Style::Hint => { - color.set_dimmed(true); - } - Style::Default => {} - } - - buffer.set_color(&color)?; - buffer.write_all(piece.0.as_bytes())?; - buffer.reset()?; - } - - writer.print(&buffer) - } - - #[cfg(not(feature = "color"))] - pub(crate) fn print(&self) -> io::Result<()> { - // [e]println can't be used here because it panics - // if something went wrong. We don't want that. - match self.stream { - Stream::Stdout => { - let stdout = std::io::stdout(); - let mut stdout = stdout.lock(); - write!(stdout, "{}", self) - } - Stream::Stderr => { - let stderr = std::io::stderr(); - let mut stderr = stderr.lock(); - write!(stderr, "{}", self) - } - } - } -} - -/// Color-unaware printing. Never uses coloring. -impl Display for Colorizer { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - for piece in &self.pieces { - Display::fmt(&piece.0, f)?; - } - - Ok(()) - } -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum Style { - Good, - Warning, - Error, - Hint, - Default, -} - -impl Default for Style { - fn default() -> Self { - Self::Default - } -} - -#[cfg(feature = "color")] -fn is_a_tty(stream: Stream) -> bool { - let stream = match stream { - Stream::Stdout => atty::Stream::Stdout, - Stream::Stderr => atty::Stream::Stderr, - }; - - atty::is(stream) -} diff --git a/vendor/clap/src/output/help.rs b/vendor/clap/src/output/help.rs deleted file mode 100644 index eb53bfa54..000000000 --- a/vendor/clap/src/output/help.rs +++ /dev/null @@ -1,1176 +0,0 @@ -// Std -use std::borrow::Cow; -use std::cmp; -use std::fmt::Write as _; -use std::io::{self, Write}; -use std::usize; - -// Internal -use crate::builder::{display_arg_val, Arg, Command}; -use crate::output::{fmt::Colorizer, Usage}; -use crate::PossibleValue; - -// Third party -use indexmap::IndexSet; -use textwrap::core::display_width; - -/// `clap` Help Writer. -/// -/// Wraps a writer stream providing different methods to generate help for `clap` objects. -pub(crate) struct Help<'help, 'cmd, 'writer> { - writer: HelpWriter<'writer>, - cmd: &'cmd Command<'help>, - usage: &'cmd Usage<'help, 'cmd>, - next_line_help: bool, - term_w: usize, - use_long: bool, -} - -// Public Functions -impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { - #[cfg(feature = "unstable-v4")] - const DEFAULT_TEMPLATE: &'static str = "\ - {before-help}{name} {version}\n\ - {author-with-newline}{about-with-newline}\n\ - {usage-heading}\n {usage}\n\ - \n\ - {all-args}{after-help}\ - "; - #[cfg(not(feature = "unstable-v4"))] - const DEFAULT_TEMPLATE: &'static str = "\ - {before-help}{bin} {version}\n\ - {author-with-newline}{about-with-newline}\n\ - {usage-heading}\n {usage}\n\ - \n\ - {all-args}{after-help}\ - "; - - #[cfg(feature = "unstable-v4")] - const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ - {before-help}{name} {version}\n\ - {author-with-newline}{about-with-newline}\n\ - {usage-heading}\n {usage}{after-help}\ - "; - #[cfg(not(feature = "unstable-v4"))] - const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ - {before-help}{bin} {version}\n\ - {author-with-newline}{about-with-newline}\n\ - {usage-heading}\n {usage}{after-help}\ - "; - - /// Create a new `Help` instance. - pub(crate) fn new( - writer: HelpWriter<'writer>, - cmd: &'cmd Command<'help>, - usage: &'cmd Usage<'help, 'cmd>, - use_long: bool, - ) -> Self { - debug!("Help::new cmd={}, use_long={}", cmd.get_name(), use_long); - let term_w = match cmd.get_term_width() { - Some(0) => usize::MAX, - Some(w) => w, - None => cmp::min( - dimensions().map_or(100, |(w, _)| w), - match cmd.get_max_term_width() { - None | Some(0) => usize::MAX, - Some(mw) => mw, - }, - ), - }; - let next_line_help = cmd.is_next_line_help_set(); - - Help { - writer, - cmd, - usage, - next_line_help, - term_w, - use_long, - } - } - - /// Writes the parser help to the wrapped stream. - pub(crate) fn write_help(&mut self) -> io::Result<()> { - debug!("Help::write_help"); - - if let Some(h) = self.cmd.get_override_help() { - self.none(h)?; - } else if let Some(tmpl) = self.cmd.get_help_template() { - self.write_templated_help(tmpl)?; - } else { - let pos = self - .cmd - .get_positionals() - .any(|arg| should_show_arg(self.use_long, arg)); - let non_pos = self - .cmd - .get_non_positionals() - .any(|arg| should_show_arg(self.use_long, arg)); - let subcmds = self.cmd.has_visible_subcommands(); - - if non_pos || pos || subcmds { - self.write_templated_help(Self::DEFAULT_TEMPLATE)?; - } else { - self.write_templated_help(Self::DEFAULT_NO_ARGS_TEMPLATE)?; - } - } - - self.none("\n")?; - - Ok(()) - } -} - -macro_rules! write_method { - ($_self:ident, $msg:ident, $meth:ident) => { - match &mut $_self.writer { - HelpWriter::Buffer(c) => { - c.$meth(($msg).into()); - Ok(()) - } - HelpWriter::Normal(w) => w.write_all($msg.as_ref()), - } - }; -} - -// Methods to write Arg help. -impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { - #[inline(never)] - fn good + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { - write_method!(self, msg, good) - } - - #[inline(never)] - fn warning + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { - write_method!(self, msg, warning) - } - - #[inline(never)] - fn none + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { - write_method!(self, msg, none) - } - - #[inline(never)] - fn spaces(&mut self, n: usize) -> io::Result<()> { - // A string with 64 consecutive spaces. - const SHORT_SPACE: &str = - " "; - if let Some(short) = SHORT_SPACE.get(..n) { - self.none(short) - } else { - self.none(" ".repeat(n)) - } - } - - /// Writes help for each argument in the order they were declared to the wrapped stream. - fn write_args_unsorted(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { - debug!("Help::write_args_unsorted"); - // The shortest an arg can legally be is 2 (i.e. '-x') - let mut longest = 2; - let mut arg_v = Vec::with_capacity(10); - - for &arg in args - .iter() - .filter(|arg| should_show_arg(self.use_long, *arg)) - { - if arg.longest_filter() { - longest = longest.max(display_width(&arg.to_string())); - debug!( - "Help::write_args_unsorted: arg={:?} longest={}", - arg.get_id(), - longest - ); - } - arg_v.push(arg) - } - - let next_line_help = self.will_args_wrap(args, longest); - - let argc = arg_v.len(); - for (i, arg) in arg_v.iter().enumerate() { - self.write_arg(arg, i + 1 == argc, next_line_help, longest)?; - } - Ok(()) - } - - /// Sorts arguments by length and display order and write their help to the wrapped stream. - fn write_args(&mut self, args: &[&Arg<'help>], _category: &str) -> io::Result<()> { - debug!("Help::write_args {}", _category); - // The shortest an arg can legally be is 2 (i.e. '-x') - let mut longest = 2; - let mut ord_v = Vec::new(); - - // Determine the longest - for &arg in args.iter().filter(|arg| { - // If it's NextLineHelp we don't care to compute how long it is because it may be - // NextLineHelp on purpose simply *because* it's so long and would throw off all other - // args alignment - should_show_arg(self.use_long, *arg) - }) { - if arg.longest_filter() { - longest = longest.max(display_width(&arg.to_string())); - debug!( - "Help::write_args: arg={:?} longest={}", - arg.get_id(), - longest - ); - } - - // Formatting key like this to ensure that: - // 1. Argument has long flags are printed just after short flags. - // 2. For two args both have short flags like `-c` and `-C`, the - // `-C` arg is printed just after the `-c` arg - // 3. For args without short or long flag, print them at last(sorted - // by arg name). - // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x - - let key = if let Some(x) = arg.short { - let mut s = x.to_ascii_lowercase().to_string(); - s.push(if x.is_ascii_lowercase() { '0' } else { '1' }); - s - } else if let Some(x) = arg.long { - x.to_string() - } else { - let mut s = '{'.to_string(); - s.push_str(arg.name); - s - }; - ord_v.push((arg.get_display_order(), key, arg)); - } - ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); - - let next_line_help = self.will_args_wrap(args, longest); - - for (i, (_, _, arg)) in ord_v.iter().enumerate() { - let last_arg = i + 1 == ord_v.len(); - self.write_arg(arg, last_arg, next_line_help, longest)?; - } - Ok(()) - } - - /// Writes help for an argument to the wrapped stream. - fn write_arg( - &mut self, - arg: &Arg<'help>, - last_arg: bool, - next_line_help: bool, - longest: usize, - ) -> io::Result<()> { - let spec_vals = &self.spec_vals(arg); - - self.short(arg)?; - self.long(arg)?; - self.val(arg)?; - self.align_to_about(arg, next_line_help, longest)?; - - let about = if self.use_long { - arg.long_help.or(arg.help).unwrap_or("") - } else { - arg.help.or(arg.long_help).unwrap_or("") - }; - - self.help(Some(arg), about, spec_vals, next_line_help, longest)?; - - if !last_arg { - self.none("\n")?; - if next_line_help { - self.none("\n")?; - } - } - Ok(()) - } - - /// Writes argument's short command to the wrapped stream. - fn short(&mut self, arg: &Arg<'help>) -> io::Result<()> { - debug!("Help::short"); - - self.none(TAB)?; - - if let Some(s) = arg.short { - self.good(format!("-{}", s)) - } else if !arg.is_positional() { - self.none(TAB) - } else { - Ok(()) - } - } - - /// Writes argument's long command to the wrapped stream. - fn long(&mut self, arg: &Arg<'help>) -> io::Result<()> { - debug!("Help::long"); - if let Some(long) = arg.long { - if arg.short.is_some() { - self.none(", ")?; - } - self.good(format!("--{}", long))?; - } - Ok(()) - } - - /// Writes argument's possible values to the wrapped stream. - fn val(&mut self, arg: &Arg<'help>) -> io::Result<()> { - debug!("Help::val: arg={}", arg.name); - let mut need_closing_bracket = false; - if arg.is_takes_value_set() && !arg.is_positional() { - let is_optional_val = arg.min_vals == Some(0); - let sep = if arg.is_require_equals_set() { - if is_optional_val { - need_closing_bracket = true; - "[=" - } else { - "=" - } - } else if is_optional_val { - need_closing_bracket = true; - " [" - } else { - " " - }; - self.none(sep)?; - } - - if arg.is_takes_value_set() || arg.is_positional() { - display_arg_val( - arg, - |s, good| if good { self.good(s) } else { self.none(s) }, - )?; - } - - if need_closing_bracket { - self.none("]")?; - } - Ok(()) - } - - /// Write alignment padding between arg's switches/values and its about message. - fn align_to_about( - &mut self, - arg: &Arg<'help>, - next_line_help: bool, - longest: usize, - ) -> io::Result<()> { - debug!( - "Help::align_to_about: arg={}, next_line_help={}, longest={}", - arg.name, next_line_help, longest - ); - if self.use_long || next_line_help { - // long help prints messages on the next line so it doesn't need to align text - debug!("Help::align_to_about: printing long help so skip alignment"); - } else if !arg.is_positional() { - let self_len = display_width(&arg.to_string()); - // Since we're writing spaces from the tab point we first need to know if we - // had a long and short, or just short - let padding = if arg.long.is_some() { - // Only account 4 after the val - 4 - } else { - // Only account for ', --' + 4 after the val - 8 - }; - let spcs = longest + padding - self_len; - debug!( - "Help::align_to_about: positional=false arg_len={}, spaces={}", - self_len, spcs - ); - - self.spaces(spcs)?; - } else { - let self_len = display_width(&arg.to_string()); - let padding = 4; - let spcs = longest + padding - self_len; - debug!( - "Help::align_to_about: positional=true arg_len={}, spaces={}", - self_len, spcs - ); - - self.spaces(spcs)?; - } - Ok(()) - } - - fn write_before_help(&mut self) -> io::Result<()> { - debug!("Help::write_before_help"); - let before_help = if self.use_long { - self.cmd - .get_before_long_help() - .or_else(|| self.cmd.get_before_help()) - } else { - self.cmd.get_before_help() - }; - if let Some(output) = before_help { - self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; - self.none("\n\n")?; - } - Ok(()) - } - - fn write_after_help(&mut self) -> io::Result<()> { - debug!("Help::write_after_help"); - let after_help = if self.use_long { - self.cmd - .get_after_long_help() - .or_else(|| self.cmd.get_after_help()) - } else { - self.cmd.get_after_help() - }; - if let Some(output) = after_help { - self.none("\n\n")?; - self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; - } - Ok(()) - } - - /// Writes argument's help to the wrapped stream. - fn help( - &mut self, - arg: Option<&Arg<'help>>, - about: &str, - spec_vals: &str, - next_line_help: bool, - longest: usize, - ) -> io::Result<()> { - debug!("Help::help"); - let mut help = String::from(about) + spec_vals; - debug!("Help::help: Next Line...{:?}", next_line_help); - - let spaces = if next_line_help { - 12 // "tab" * 3 - } else { - longest + 12 - }; - - let too_long = spaces + display_width(&help) >= self.term_w; - - // Is help on next line, if so then indent - if next_line_help { - self.none(format!("\n{}{}{}", TAB, TAB, TAB))?; - } - - debug!("Help::help: Too long..."); - if too_long && spaces <= self.term_w || help.contains("{n}") { - debug!("Yes"); - debug!("Help::help: help...{}", help); - debug!("Help::help: help width...{}", display_width(&help)); - // Determine how many newlines we need to insert - let avail_chars = self.term_w - spaces; - debug!("Help::help: Usable space...{}", avail_chars); - help = text_wrapper(&help.replace("{n}", "\n"), avail_chars); - } else { - debug!("No"); - } - if let Some(part) = help.lines().next() { - self.none(part)?; - } - - // indent of help - let spaces = if next_line_help { - TAB_WIDTH * 3 - } else if let Some(true) = arg.map(|a| a.is_positional()) { - longest + TAB_WIDTH * 2 - } else { - longest + TAB_WIDTH * 3 - }; - - for part in help.lines().skip(1) { - self.none("\n")?; - self.spaces(spaces)?; - self.none(part)?; - } - - #[cfg(feature = "unstable-v4")] - if let Some(arg) = arg { - const DASH_SPACE: usize = "- ".len(); - const COLON_SPACE: usize = ": ".len(); - let possible_vals = arg.get_possible_values2(); - if self.use_long - && !arg.is_hide_possible_values_set() - && possible_vals.iter().any(PossibleValue::should_show_help) - { - debug!("Help::help: Found possible vals...{:?}", possible_vals); - if !help.is_empty() { - self.none("\n\n")?; - self.spaces(spaces)?; - } - self.none("Possible values:")?; - let longest = possible_vals - .iter() - .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name))) - .max() - .expect("Only called with possible value"); - let help_longest = possible_vals - .iter() - .filter_map(|f| f.get_visible_help().map(display_width)) - .max() - .expect("Only called with possible value with help"); - // should new line - let taken = longest + spaces + DASH_SPACE; - - let possible_value_new_line = - self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest; - - let spaces = spaces + TAB_WIDTH - DASH_SPACE; - let spaces_help = if possible_value_new_line { - spaces + DASH_SPACE - } else { - spaces + longest + DASH_SPACE + COLON_SPACE - }; - - for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) { - self.none("\n")?; - self.spaces(spaces)?; - self.none("- ")?; - self.good(pv.get_name())?; - if let Some(help) = pv.get_help() { - debug!("Help::help: Possible Value help"); - - if possible_value_new_line { - self.none(":\n")?; - self.spaces(spaces_help)?; - } else { - self.none(": ")?; - // To align help messages - self.spaces(longest - display_width(pv.get_name()))?; - } - - let avail_chars = if self.term_w > spaces_help { - self.term_w - spaces_help - } else { - usize::MAX - }; - - let help = text_wrapper(help, avail_chars); - let mut help = help.lines(); - - self.none(help.next().unwrap_or_default())?; - for part in help { - self.none("\n")?; - self.spaces(spaces_help)?; - self.none(part)?; - } - } - } - } - } - Ok(()) - } - - /// Will use next line help on writing args. - fn will_args_wrap(&self, args: &[&Arg<'help>], longest: usize) -> bool { - args.iter() - .filter(|arg| should_show_arg(self.use_long, *arg)) - .any(|arg| { - let spec_vals = &self.spec_vals(arg); - self.arg_next_line_help(arg, spec_vals, longest) - }) - } - - fn arg_next_line_help(&self, arg: &Arg<'help>, spec_vals: &str, longest: usize) -> bool { - if self.next_line_help || arg.is_next_line_help_set() || self.use_long { - // setting_next_line - true - } else { - // force_next_line - let h = arg.help.unwrap_or(""); - let h_w = display_width(h) + display_width(spec_vals); - let taken = longest + 12; - self.term_w >= taken - && (taken as f32 / self.term_w as f32) > 0.40 - && h_w > (self.term_w - taken) - } - } - - fn spec_vals(&self, a: &Arg) -> String { - debug!("Help::spec_vals: a={}", a); - let mut spec_vals = vec![]; - #[cfg(feature = "env")] - if let Some(ref env) = a.env { - if !a.is_hide_env_set() { - debug!( - "Help::spec_vals: Found environment variable...[{:?}:{:?}]", - env.0, env.1 - ); - let env_val = if !a.is_hide_env_values_set() { - format!( - "={}", - env.1 - .as_ref() - .map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) - ) - } else { - String::new() - }; - let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val); - spec_vals.push(env_info); - } - } - if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() { - debug!( - "Help::spec_vals: Found default value...[{:?}]", - a.default_vals - ); - - let pvs = a - .default_vals - .iter() - .map(|&pvs| pvs.to_string_lossy()) - .map(|pvs| { - if pvs.contains(char::is_whitespace) { - Cow::from(format!("{:?}", pvs)) - } else { - pvs - } - }) - .collect::>() - .join(" "); - - spec_vals.push(format!("[default: {}]", pvs)); - } - if !a.aliases.is_empty() { - debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); - - let als = a - .aliases - .iter() - .filter(|&als| als.1) // visible - .map(|&als| als.0) // name - .collect::>() - .join(", "); - - if !als.is_empty() { - spec_vals.push(format!("[aliases: {}]", als)); - } - } - - if !a.short_aliases.is_empty() { - debug!( - "Help::spec_vals: Found short aliases...{:?}", - a.short_aliases - ); - - let als = a - .short_aliases - .iter() - .filter(|&als| als.1) // visible - .map(|&als| als.0.to_string()) // name - .collect::>() - .join(", "); - - if !als.is_empty() { - spec_vals.push(format!("[short aliases: {}]", als)); - } - } - - let possible_vals = a.get_possible_values2(); - if !(a.is_hide_possible_values_set() - || possible_vals.is_empty() - || cfg!(feature = "unstable-v4") - && self.use_long - && possible_vals.iter().any(PossibleValue::should_show_help)) - { - debug!("Help::spec_vals: Found possible vals...{:?}", possible_vals); - - let pvs = possible_vals - .iter() - .filter_map(PossibleValue::get_visible_quoted_name) - .collect::>() - .join(", "); - - spec_vals.push(format!("[possible values: {}]", pvs)); - } - let connector = if self.use_long { "\n" } else { " " }; - let prefix = if !spec_vals.is_empty() && !a.get_help().unwrap_or("").is_empty() { - if self.use_long { - "\n\n" - } else { - " " - } - } else { - "" - }; - prefix.to_string() + &spec_vals.join(connector) - } - - fn write_about(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { - let about = if self.use_long { - self.cmd.get_long_about().or_else(|| self.cmd.get_about()) - } else { - self.cmd.get_about() - }; - if let Some(output) = about { - if before_new_line { - self.none("\n")?; - } - self.none(text_wrapper(output, self.term_w))?; - if after_new_line { - self.none("\n")?; - } - } - Ok(()) - } - - fn write_author(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { - if let Some(author) = self.cmd.get_author() { - if before_new_line { - self.none("\n")?; - } - self.none(text_wrapper(author, self.term_w))?; - if after_new_line { - self.none("\n")?; - } - } - Ok(()) - } - - fn write_version(&mut self) -> io::Result<()> { - let version = self - .cmd - .get_version() - .or_else(|| self.cmd.get_long_version()); - if let Some(output) = version { - self.none(text_wrapper(output, self.term_w))?; - } - Ok(()) - } -} - -/// Methods to write a single subcommand -impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { - fn write_subcommand( - &mut self, - sc_str: &str, - cmd: &Command<'help>, - next_line_help: bool, - longest: usize, - ) -> io::Result<()> { - debug!("Help::write_subcommand"); - - let spec_vals = &self.sc_spec_vals(cmd); - - let about = cmd - .get_about() - .or_else(|| cmd.get_long_about()) - .unwrap_or(""); - - self.subcmd(sc_str, next_line_help, longest)?; - self.help(None, about, spec_vals, next_line_help, longest) - } - - fn sc_spec_vals(&self, a: &Command) -> String { - debug!("Help::sc_spec_vals: a={}", a.get_name()); - let mut spec_vals = vec![]; - if 0 < a.get_all_aliases().count() || 0 < a.get_all_short_flag_aliases().count() { - debug!( - "Help::spec_vals: Found aliases...{:?}", - a.get_all_aliases().collect::>() - ); - debug!( - "Help::spec_vals: Found short flag aliases...{:?}", - a.get_all_short_flag_aliases().collect::>() - ); - - let mut short_als = a - .get_visible_short_flag_aliases() - .map(|a| format!("-{}", a)) - .collect::>(); - - let als = a.get_visible_aliases().map(|s| s.to_string()); - - short_als.extend(als); - - let all_als = short_als.join(", "); - - if !all_als.is_empty() { - spec_vals.push(format!(" [aliases: {}]", all_als)); - } - } - spec_vals.join(" ") - } - - fn subcommand_next_line_help( - &self, - cmd: &Command<'help>, - spec_vals: &str, - longest: usize, - ) -> bool { - if self.next_line_help | self.use_long { - // setting_next_line - true - } else { - // force_next_line - let h = cmd.get_about().unwrap_or(""); - let h_w = display_width(h) + display_width(spec_vals); - let taken = longest + 12; - self.term_w >= taken - && (taken as f32 / self.term_w as f32) > 0.40 - && h_w > (self.term_w - taken) - } - } - - /// Writes subcommand to the wrapped stream. - fn subcmd(&mut self, sc_str: &str, next_line_help: bool, longest: usize) -> io::Result<()> { - self.none(TAB)?; - self.good(sc_str)?; - if !next_line_help { - let width = display_width(sc_str); - self.spaces(width.max(longest + 4) - width)?; - } - Ok(()) - } -} - -// Methods to write Parser help. -impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { - /// Writes help for all arguments (options, flags, args, subcommands) - /// including titles of a Parser Object to the wrapped stream. - pub(crate) fn write_all_args(&mut self) -> io::Result<()> { - debug!("Help::write_all_args"); - let pos = self - .cmd - .get_positionals_with_no_heading() - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::>(); - let non_pos = self - .cmd - .get_non_positionals_with_no_heading() - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::>(); - let subcmds = self.cmd.has_visible_subcommands(); - - let custom_headings = self - .cmd - .get_arguments() - .filter_map(|arg| arg.get_help_heading()) - .collect::>(); - - let mut first = if !pos.is_empty() { - // Write positional args if any - self.warning("ARGS:\n")?; - self.write_args_unsorted(&pos)?; - false - } else { - true - }; - - if !non_pos.is_empty() { - if !first { - self.none("\n\n")?; - } - self.warning("OPTIONS:\n")?; - self.write_args(&non_pos, "OPTIONS")?; - first = false; - } - if !custom_headings.is_empty() { - for heading in custom_headings { - let args = self - .cmd - .get_arguments() - .filter(|a| { - if let Some(help_heading) = a.get_help_heading() { - return help_heading == heading; - } - false - }) - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::>(); - - if !args.is_empty() { - if !first { - self.none("\n\n")?; - } - self.warning(format!("{}:\n", heading))?; - self.write_args(&args, heading)?; - first = false - } - } - } - - if subcmds { - if !first { - self.none("\n\n")?; - } - - self.warning( - self.cmd - .get_subcommand_help_heading() - .unwrap_or("SUBCOMMANDS"), - )?; - self.warning(":\n")?; - - self.write_subcommands(self.cmd)?; - } - - Ok(()) - } - - /// Will use next line help on writing subcommands. - fn will_subcommands_wrap<'a>( - &self, - subcommands: impl IntoIterator>, - longest: usize, - ) -> bool - where - 'help: 'a, - { - subcommands - .into_iter() - .filter(|&subcommand| should_show_subcommand(subcommand)) - .any(|subcommand| { - let spec_vals = &self.sc_spec_vals(subcommand); - self.subcommand_next_line_help(subcommand, spec_vals, longest) - }) - } - - /// Writes help for subcommands of a Parser Object to the wrapped stream. - fn write_subcommands(&mut self, cmd: &Command<'help>) -> io::Result<()> { - debug!("Help::write_subcommands"); - // The shortest an arg can legally be is 2 (i.e. '-x') - let mut longest = 2; - let mut ord_v = Vec::new(); - for subcommand in cmd - .get_subcommands() - .filter(|subcommand| should_show_subcommand(subcommand)) - { - let mut sc_str = String::new(); - sc_str.push_str(subcommand.get_name()); - if let Some(short) = subcommand.get_short_flag() { - write!(sc_str, " -{}", short).unwrap(); - } - if let Some(long) = subcommand.get_long_flag() { - write!(sc_str, " --{}", long).unwrap(); - } - longest = longest.max(display_width(&sc_str)); - ord_v.push((subcommand.get_display_order(), sc_str, subcommand)); - } - ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); - - debug!("Help::write_subcommands longest = {}", longest); - - let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest); - - let mut first = true; - for (_, sc_str, sc) in &ord_v { - if first { - first = false; - } else { - self.none("\n")?; - } - self.write_subcommand(sc_str, sc, next_line_help, longest)?; - } - Ok(()) - } - - /// Writes binary name of a Parser Object to the wrapped stream. - fn write_display_name(&mut self) -> io::Result<()> { - debug!("Help::write_display_name"); - - let display_name = text_wrapper( - &self - .cmd - .get_display_name() - .unwrap_or_else(|| self.cmd.get_name()) - .replace("{n}", "\n"), - self.term_w, - ); - self.good(&display_name)?; - Ok(()) - } - - /// Writes binary name of a Parser Object to the wrapped stream. - fn write_bin_name(&mut self) -> io::Result<()> { - debug!("Help::write_bin_name"); - - let bin_name = if let Some(bn) = self.cmd.get_bin_name() { - if bn.contains(' ') { - // In case we're dealing with subcommands i.e. git mv is translated to git-mv - bn.replace(' ', "-") - } else { - text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) - } - } else { - text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) - }; - self.good(&bin_name)?; - Ok(()) - } -} - -// Methods to write Parser help using templates. -impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { - /// Write help to stream for the parser in the format defined by the template. - /// - /// For details about the template language see [`Command::help_template`]. - /// - /// [`Command::help_template`]: Command::help_template() - fn write_templated_help(&mut self, template: &str) -> io::Result<()> { - debug!("Help::write_templated_help"); - - // The strategy is to copy the template from the reader to wrapped stream - // until a tag is found. Depending on its value, the appropriate content is copied - // to the wrapped stream. - // The copy from template is then resumed, repeating this sequence until reading - // the complete template. - - macro_rules! tags { - ( - match $part:ident { - $( $tag:expr => $action:stmt )* - } - ) => { - match $part { - $( - part if part.starts_with(concat!($tag, "}")) => { - $action - let rest = &part[$tag.len()+1..]; - self.none(rest)?; - } - )* - - // Unknown tag, write it back. - part => { - self.none("{")?; - self.none(part)?; - } - } - }; - } - - let mut parts = template.split('{'); - if let Some(first) = parts.next() { - self.none(first)?; - } - - for part in parts { - tags! { - match part { - "name" => { - self.write_display_name()?; - } - "bin" => { - self.write_bin_name()?; - } - "version" => { - self.write_version()?; - } - "author" => { - self.write_author(false, false)?; - } - "author-with-newline" => { - self.write_author(false, true)?; - } - "author-section" => { - self.write_author(true, true)?; - } - "about" => { - self.write_about(false, false)?; - } - "about-with-newline" => { - self.write_about(false, true)?; - } - "about-section" => { - self.write_about(true, true)?; - } - "usage-heading" => { - self.warning("USAGE:")?; - } - "usage" => { - self.none(self.usage.create_usage_no_title(&[]))?; - } - "all-args" => { - self.write_all_args()?; - } - "options" => { - // Include even those with a heading as we don't have a good way of - // handling help_heading in the template. - self.write_args(&self.cmd.get_non_positionals().collect::>(), "options")?; - } - "positionals" => { - self.write_args(&self.cmd.get_positionals().collect::>(), "positionals")?; - } - "subcommands" => { - self.write_subcommands(self.cmd)?; - } - "after-help" => { - self.write_after_help()?; - } - "before-help" => { - self.write_before_help()?; - } - } - } - } - - Ok(()) - } -} - -pub(crate) fn dimensions() -> Option<(usize, usize)> { - #[cfg(not(feature = "wrap_help"))] - return None; - - #[cfg(feature = "wrap_help")] - terminal_size::terminal_size().map(|(w, h)| (w.0.into(), h.0.into())) -} - -const TAB: &str = " "; -const TAB_WIDTH: usize = 4; - -pub(crate) enum HelpWriter<'writer> { - Normal(&'writer mut dyn Write), - Buffer(&'writer mut Colorizer), -} - -fn should_show_arg(use_long: bool, arg: &Arg) -> bool { - debug!("should_show_arg: use_long={:?}, arg={}", use_long, arg.name); - if arg.is_hide_set() { - return false; - } - (!arg.is_hide_long_help_set() && use_long) - || (!arg.is_hide_short_help_set() && !use_long) - || arg.is_next_line_help_set() -} - -fn should_show_subcommand(subcommand: &Command) -> bool { - !subcommand.is_hide_set() -} - -fn text_wrapper(help: &str, width: usize) -> String { - let wrapper = textwrap::Options::new(width) - .break_words(false) - .word_splitter(textwrap::WordSplitter::NoHyphenation); - help.lines() - .map(|line| textwrap::fill(line, &wrapper)) - .collect::>() - .join("\n") -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn wrap_help_last_word() { - let help = String::from("foo bar baz"); - assert_eq!(text_wrapper(&help, 5), "foo\nbar\nbaz"); - } - - #[test] - fn display_width_handles_non_ascii() { - // Popular Danish tongue-twister, the name of a fruit dessert. - let text = "rødgrød med fløde"; - assert_eq!(display_width(text), 17); - // Note that the string width is smaller than the string - // length. This is due to the precomposed non-ASCII letters: - assert_eq!(text.len(), 20); - } - - #[test] - fn display_width_handles_emojis() { - let text = "😂"; - // There is a single `char`... - assert_eq!(text.chars().count(), 1); - // but it is double-width: - assert_eq!(display_width(text), 2); - // This is much less than the byte length: - assert_eq!(text.len(), 4); - } -} diff --git a/vendor/clap/src/output/mod.rs b/vendor/clap/src/output/mod.rs deleted file mode 100644 index e32aac26a..000000000 --- a/vendor/clap/src/output/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -mod help; -mod usage; - -pub(crate) mod fmt; - -pub(crate) use self::help::{Help, HelpWriter}; -pub(crate) use self::usage::Usage; diff --git a/vendor/clap/src/output/usage.rs b/vendor/clap/src/output/usage.rs deleted file mode 100644 index 7adaf58c6..000000000 --- a/vendor/clap/src/output/usage.rs +++ /dev/null @@ -1,458 +0,0 @@ -use indexmap::IndexSet; - -// Internal -use crate::builder::AppSettings as AS; -use crate::builder::{Arg, ArgPredicate, Command}; -use crate::parser::ArgMatcher; -use crate::util::ChildGraph; -use crate::util::Id; -use crate::INTERNAL_ERROR_MSG; - -pub(crate) struct Usage<'help, 'cmd> { - cmd: &'cmd Command<'help>, - required: Option<&'cmd ChildGraph>, -} - -impl<'help, 'cmd> Usage<'help, 'cmd> { - pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { - Usage { - cmd, - required: None, - } - } - - pub(crate) fn required(mut self, required: &'cmd ChildGraph) -> Self { - self.required = Some(required); - self - } - - // Creates a usage string for display. This happens just after all arguments were parsed, but before - // any subcommands have been parsed (so as to give subcommands their own usage recursively) - pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> String { - debug!("Usage::create_usage_with_title"); - let mut usage = String::with_capacity(75); - usage.push_str("USAGE:\n "); - usage.push_str(&*self.create_usage_no_title(used)); - usage - } - - // Creates a usage string (*without title*) if one was not provided by the user manually. - pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> String { - debug!("Usage::create_usage_no_title"); - if let Some(u) = self.cmd.get_override_usage() { - String::from(&*u) - } else if used.is_empty() { - self.create_help_usage(true) - } else { - self.create_smart_usage(used) - } - } - - // Creates a usage string for display in help messages (i.e. not for errors) - fn create_help_usage(&self, incl_reqs: bool) -> String { - debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs); - let mut usage = String::with_capacity(75); - let name = self - .cmd - .get_usage_name() - .or_else(|| self.cmd.get_bin_name()) - .unwrap_or_else(|| self.cmd.get_name()); - usage.push_str(name); - let req_string = if incl_reqs { - self.get_required_usage_from(&[], None, false) - .iter() - .fold(String::new(), |a, s| a + " " + s) - } else { - String::new() - }; - - if self.needs_options_tag() { - usage.push_str(" [OPTIONS]"); - } - - let allow_missing_positional = self.cmd.is_allow_missing_positional_set(); - if !allow_missing_positional { - usage.push_str(&req_string); - } - - let has_last = self.cmd.get_positionals().any(|p| p.is_last_set()); - // places a '--' in the usage string if there are args and options - // supporting multiple values - if self - .cmd - .get_non_positionals() - .any(|o| o.is_multiple_values_set()) - && self.cmd.get_positionals().any(|p| !p.is_required_set()) - && !(self.cmd.has_visible_subcommands() || self.cmd.is_allow_external_subcommands_set()) - && !has_last - { - usage.push_str(" [--]"); - } - let not_req_or_hidden = - |p: &Arg| (!p.is_required_set() || p.is_last_set()) && !p.is_hide_set(); - if self.cmd.get_positionals().any(not_req_or_hidden) { - if let Some(args_tag) = self.get_args_tag(incl_reqs) { - usage.push_str(&*args_tag); - } else { - usage.push_str(" [ARGS]"); - } - if has_last && incl_reqs { - let pos = self - .cmd - .get_positionals() - .find(|p| p.is_last_set()) - .expect(INTERNAL_ERROR_MSG); - debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name); - let req = pos.is_required_set(); - if req && self.cmd.get_positionals().any(|p| !p.is_required_set()) { - usage.push_str(" -- <"); - } else if req { - usage.push_str(" [--] <"); - } else { - usage.push_str(" [-- <"); - } - usage.push_str(&*pos.name_no_brackets()); - usage.push('>'); - usage.push_str(pos.multiple_str()); - if !req { - usage.push(']'); - } - } - } - - if allow_missing_positional { - usage.push_str(&req_string); - } - - // incl_reqs is only false when this function is called recursively - if self.cmd.has_visible_subcommands() && incl_reqs - || self.cmd.is_allow_external_subcommands_set() - { - let placeholder = self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND"); - #[allow(deprecated)] - if self.cmd.is_subcommand_negates_reqs_set() - || self.cmd.is_args_conflicts_with_subcommands_set() - { - usage.push_str("\n "); - if !self.cmd.is_args_conflicts_with_subcommands_set() { - usage.push_str(&*self.create_help_usage(false)); - } else { - usage.push_str(&*name); - } - usage.push_str(" <"); - usage.push_str(placeholder); - usage.push('>'); - } else if self.cmd.is_subcommand_required_set() - || self.cmd.is_set(AS::SubcommandRequiredElseHelp) - { - usage.push_str(" <"); - usage.push_str(placeholder); - usage.push('>'); - } else { - usage.push_str(" ["); - usage.push_str(placeholder); - usage.push(']'); - } - } - let usage = usage.trim().to_owned(); - debug!("Usage::create_help_usage: usage={}", usage); - usage - } - - // Creates a context aware usage string, or "smart usage" from currently used - // args, and requirements - fn create_smart_usage(&self, used: &[Id]) -> String { - debug!("Usage::create_smart_usage"); - let mut usage = String::with_capacity(75); - - let r_string = self - .get_required_usage_from(used, None, true) - .iter() - .fold(String::new(), |acc, s| acc + " " + s); - - usage.push_str( - self.cmd - .get_usage_name() - .or_else(|| self.cmd.get_bin_name()) - .unwrap_or_else(|| self.cmd.get_name()), - ); - usage.push_str(&*r_string); - if self.cmd.is_subcommand_required_set() { - usage.push_str(" <"); - usage.push_str(self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND")); - usage.push('>'); - } - usage.shrink_to_fit(); - usage - } - - // Gets the `[ARGS]` tag for the usage string - fn get_args_tag(&self, incl_reqs: bool) -> Option { - debug!("Usage::get_args_tag; incl_reqs = {:?}", incl_reqs); - let mut count = 0; - for pos in self - .cmd - .get_positionals() - .filter(|pos| !pos.is_required_set()) - .filter(|pos| !pos.is_hide_set()) - .filter(|pos| !pos.is_last_set()) - { - debug!("Usage::get_args_tag:iter:{}", pos.name); - let required = self.cmd.groups_for_arg(&pos.id).any(|grp_s| { - debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); - // if it's part of a required group we don't want to count it - self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) - }); - if !required { - count += 1; - debug!( - "Usage::get_args_tag:iter: {} Args not required or hidden", - count - ); - } - } - - if !self.cmd.is_dont_collapse_args_in_usage_set() && count > 1 { - debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]"); - - // [ARGS] - None - } else if count == 1 && incl_reqs { - let pos = self - .cmd - .get_positionals() - .find(|pos| { - !pos.is_required_set() - && !pos.is_hide_set() - && !pos.is_last_set() - && !self.cmd.groups_for_arg(&pos.id).any(|grp_s| { - debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); - // if it's part of a required group we don't want to count it - self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) - }) - }) - .expect(INTERNAL_ERROR_MSG); - - debug!( - "Usage::get_args_tag:iter: Exactly one, returning '{}'", - pos.name - ); - - Some(format!( - " [{}]{}", - pos.name_no_brackets(), - pos.multiple_str() - )) - } else if self.cmd.is_dont_collapse_args_in_usage_set() - && self.cmd.has_positionals() - && incl_reqs - { - debug!("Usage::get_args_tag:iter: Don't collapse returning all"); - Some( - self.cmd - .get_positionals() - .filter(|pos| !pos.is_required_set()) - .filter(|pos| !pos.is_hide_set()) - .filter(|pos| !pos.is_last_set()) - .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) - .collect::>() - .join(""), - ) - } else if !incl_reqs { - debug!("Usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); - let highest_req_pos = self - .cmd - .get_positionals() - .filter_map(|pos| { - if pos.is_required_set() && !pos.is_last_set() { - Some(pos.index) - } else { - None - } - }) - .max() - .unwrap_or_else(|| Some(self.cmd.get_positionals().count())); - Some( - self.cmd - .get_positionals() - .filter(|pos| pos.index <= highest_req_pos) - .filter(|pos| !pos.is_required_set()) - .filter(|pos| !pos.is_hide_set()) - .filter(|pos| !pos.is_last_set()) - .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) - .collect::>() - .join(""), - ) - } else { - Some("".into()) - } - } - - // Determines if we need the `[OPTIONS]` tag in the usage string - fn needs_options_tag(&self) -> bool { - debug!("Usage::needs_options_tag"); - 'outer: for f in self.cmd.get_non_positionals() { - debug!("Usage::needs_options_tag:iter: f={}", f.name); - - // Don't print `[OPTIONS]` just for help or version - if f.long == Some("help") || f.long == Some("version") { - debug!("Usage::needs_options_tag:iter Option is built-in"); - continue; - } - - if f.is_hide_set() { - debug!("Usage::needs_options_tag:iter Option is hidden"); - continue; - } - if f.is_required_set() { - debug!("Usage::needs_options_tag:iter Option is required"); - continue; - } - for grp_s in self.cmd.groups_for_arg(&f.id) { - debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s); - if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) { - debug!("Usage::needs_options_tag:iter:iter: Group is required"); - continue 'outer; - } - } - - debug!("Usage::needs_options_tag:iter: [OPTIONS] required"); - return true; - } - - debug!("Usage::needs_options_tag: [OPTIONS] not required"); - false - } - - // Returns the required args in usage string form by fully unrolling all groups - // `incl_last`: should we include args that are Arg::Last? (i.e. `prog [foo] -- [last]). We - // can't do that for required usages being built for subcommands because it would look like: - // `prog [foo] -- [last] ` which is totally wrong. - pub(crate) fn get_required_usage_from( - &self, - incls: &[Id], - matcher: Option<&ArgMatcher>, - incl_last: bool, - ) -> IndexSet { - debug!( - "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}", - incls, - matcher.is_some(), - incl_last - ); - let mut ret_val = IndexSet::new(); - - let mut unrolled_reqs = IndexSet::new(); - - let required_owned; - let required = if let Some(required) = self.required { - required - } else { - required_owned = self.cmd.required_graph(); - &required_owned - }; - - for a in required.iter() { - let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option { - let required = match val { - ArgPredicate::Equals(_) => { - if let Some(matcher) = matcher { - matcher.check_explicit(a, *val) - } else { - false - } - } - ArgPredicate::IsPresent => true, - }; - required.then(|| req_arg.clone()) - }; - - for aa in self.cmd.unroll_arg_requires(is_relevant, a) { - // if we don't check for duplicates here this causes duplicate error messages - // see https://github.com/clap-rs/clap/issues/2770 - unrolled_reqs.insert(aa); - } - // always include the required arg itself. it will not be enumerated - // by unroll_requirements_for_arg. - unrolled_reqs.insert(a.clone()); - } - - debug!( - "Usage::get_required_usage_from: unrolled_reqs={:?}", - unrolled_reqs - ); - - let args_in_groups = self - .cmd - .get_groups() - .filter(|gn| required.contains(&gn.id)) - .flat_map(|g| self.cmd.unroll_args_in_group(&g.id)) - .collect::>(); - - for a in unrolled_reqs - .iter() - .chain(incls.iter()) - .filter(|name| !self.cmd.get_positionals().any(|p| &&p.id == name)) - .filter(|name| !self.cmd.get_groups().any(|g| &&g.id == name)) - .filter(|name| !args_in_groups.contains(name)) - .filter(|name| { - !(matcher.is_some() - && matcher - .as_ref() - .unwrap() - .check_explicit(name, ArgPredicate::IsPresent)) - }) - { - debug!("Usage::get_required_usage_from:iter:{:?}", a); - let arg = self.cmd.find(a).expect(INTERNAL_ERROR_MSG).to_string(); - ret_val.insert(arg); - } - let mut g_vec: Vec = vec![]; - for g in unrolled_reqs - .iter() - .filter(|n| self.cmd.get_groups().any(|g| g.id == **n)) - { - // don't print requirement for required groups that have an arg. - if let Some(m) = matcher { - let have_group_entry = self - .cmd - .unroll_args_in_group(g) - .iter() - .any(|arg| m.check_explicit(arg, ArgPredicate::IsPresent)); - if have_group_entry { - continue; - } - } - - let elem = self.cmd.format_group(g); - if !g_vec.contains(&elem) { - g_vec.push(elem); - } - } - ret_val.extend(g_vec); - - let mut pvec = unrolled_reqs - .iter() - .chain(incls.iter()) - .filter(|a| self.cmd.get_positionals().any(|p| &&p.id == a)) - .filter(|&pos| { - matcher.map_or(true, |m| !m.check_explicit(pos, ArgPredicate::IsPresent)) - }) - .filter_map(|pos| self.cmd.find(pos)) - .filter(|&pos| incl_last || !pos.is_last_set()) - .filter(|pos| !args_in_groups.contains(&pos.id)) - .map(|pos| (pos.index.unwrap(), pos)) - .collect::>(); - pvec.sort_by_key(|(ind, _)| *ind); // sort by index - - for (_, p) in pvec { - debug!("Usage::get_required_usage_from:push:{:?}", p.id); - if !args_in_groups.contains(&p.id) { - ret_val.insert(p.to_string()); - } - } - - debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val); - ret_val - } -} diff --git a/vendor/clap/src/parser/arg_matcher.rs b/vendor/clap/src/parser/arg_matcher.rs deleted file mode 100644 index 8d15c5799..000000000 --- a/vendor/clap/src/parser/arg_matcher.rs +++ /dev/null @@ -1,282 +0,0 @@ -// Std -use std::collections::HashMap; -use std::ffi::OsString; -use std::mem; -use std::ops::Deref; - -// Internal -use crate::builder::{Arg, ArgPredicate, Command}; -use crate::parser::AnyValue; -use crate::parser::Identifier; -use crate::parser::PendingArg; -use crate::parser::{ArgMatches, MatchedArg, SubCommand, ValueSource}; -use crate::util::Id; -use crate::INTERNAL_ERROR_MSG; - -#[derive(Debug, Default)] -pub(crate) struct ArgMatcher { - matches: ArgMatches, - pending: Option, -} - -impl ArgMatcher { - pub(crate) fn new(_cmd: &Command) -> Self { - ArgMatcher { - matches: ArgMatches { - #[cfg(debug_assertions)] - valid_args: { - let args = _cmd.get_arguments().map(|a| a.id.clone()); - let groups = _cmd.get_groups().map(|g| g.id.clone()); - args.chain(groups).collect() - }, - #[cfg(debug_assertions)] - valid_subcommands: _cmd.get_subcommands().map(|sc| sc.get_id()).collect(), - // HACK: Allow an external subcommand's ArgMatches be a stand-in for any ArgMatches - // since users can't detect it and avoid the asserts. - // - // See clap-rs/clap#3263 - #[cfg(debug_assertions)] - #[cfg(not(feature = "unstable-v4"))] - disable_asserts: _cmd.is_allow_external_subcommands_set(), - #[cfg(debug_assertions)] - #[cfg(feature = "unstable-v4")] - disable_asserts: false, - ..Default::default() - }, - pending: None, - } - } - - pub(crate) fn into_inner(self) -> ArgMatches { - self.matches - } - - pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) { - debug!( - "ArgMatcher::get_global_values: global_arg_vec={:?}", - global_arg_vec - ); - let mut vals_map = HashMap::new(); - self.fill_in_global_values(global_arg_vec, &mut vals_map); - } - - fn fill_in_global_values( - &mut self, - global_arg_vec: &[Id], - vals_map: &mut HashMap, - ) { - for global_arg in global_arg_vec { - if let Some(ma) = self.get(global_arg) { - // We have to check if the parent's global arg wasn't used but still exists - // such as from a default value. - // - // For example, `myprog subcommand --global-arg=value` where `--global-arg` defines - // a default value of `other` myprog would have an existing MatchedArg for - // `--global-arg` where the value is `other` - let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { - if parent_ma.check_explicit(ArgPredicate::IsPresent) - && !ma.check_explicit(ArgPredicate::IsPresent) - { - parent_ma - } else { - ma - } - } else { - ma - } - .clone(); - vals_map.insert(global_arg.clone(), to_update); - } - } - if let Some(ref mut sc) = self.matches.subcommand { - let mut am = ArgMatcher { - matches: mem::take(&mut sc.matches), - pending: None, - }; - am.fill_in_global_values(global_arg_vec, vals_map); - mem::swap(&mut am.matches, &mut sc.matches); - } - - for (name, matched_arg) in vals_map.iter_mut() { - self.matches.args.insert(name.clone(), matched_arg.clone()); - } - } - - pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> { - self.matches.args.get(arg) - } - - pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> { - self.matches.args.get_mut(arg) - } - - pub(crate) fn remove(&mut self, arg: &Id) { - self.matches.args.swap_remove(arg); - } - - pub(crate) fn contains(&self, arg: &Id) -> bool { - self.matches.args.contains_key(arg) - } - - pub(crate) fn arg_ids(&self) -> indexmap::map::Keys { - self.matches.args.keys() - } - - pub(crate) fn entry(&mut self, arg: &Id) -> indexmap::map::Entry { - self.matches.args.entry(arg.clone()) - } - - pub(crate) fn subcommand(&mut self, sc: SubCommand) { - self.matches.subcommand = Some(Box::new(sc)); - } - - pub(crate) fn subcommand_name(&self) -> Option<&str> { - self.matches.subcommand_name() - } - - pub(crate) fn iter(&self) -> indexmap::map::Iter { - self.matches.args.iter() - } - - pub(crate) fn check_explicit<'a>(&self, arg: &Id, predicate: ArgPredicate<'a>) -> bool { - self.get(arg).map_or(false, |a| a.check_explicit(predicate)) - } - - pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) { - let id = &arg.id; - debug!( - "ArgMatcher::start_custom_arg: id={:?}, source={:?}", - id, source - ); - let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg)); - debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id())); - ma.set_source(source); - ma.new_val_group(); - } - - pub(crate) fn start_custom_group(&mut self, id: &Id, source: ValueSource) { - debug!( - "ArgMatcher::start_custom_arg: id={:?}, source={:?}", - id, source - ); - let ma = self.entry(id).or_insert(MatchedArg::new_group()); - debug_assert_eq!(ma.type_id(), None); - ma.set_source(source); - ma.new_val_group(); - } - - pub(crate) fn start_occurrence_of_arg(&mut self, arg: &Arg) { - let id = &arg.id; - debug!("ArgMatcher::start_occurrence_of_arg: id={:?}", id); - let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg)); - debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id())); - ma.set_source(ValueSource::CommandLine); - #[allow(deprecated)] - ma.inc_occurrences(); - ma.new_val_group(); - } - - pub(crate) fn start_occurrence_of_group(&mut self, id: &Id) { - debug!("ArgMatcher::start_occurrence_of_group: id={:?}", id); - let ma = self.entry(id).or_insert(MatchedArg::new_group()); - debug_assert_eq!(ma.type_id(), None); - ma.set_source(ValueSource::CommandLine); - #[allow(deprecated)] - ma.inc_occurrences(); - ma.new_val_group(); - } - - pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) { - let id = &Id::empty_hash(); - debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,); - let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd)); - debug_assert_eq!( - ma.type_id(), - Some( - cmd.get_external_subcommand_value_parser() - .expect(INTERNAL_ERROR_MSG) - .type_id() - ) - ); - ma.set_source(ValueSource::CommandLine); - #[allow(deprecated)] - ma.inc_occurrences(); - ma.new_val_group(); - } - - pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) { - let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); - ma.append_val(val, raw_val); - } - - pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) { - let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); - ma.push_index(idx); - } - - pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool { - let num_resolved = self.get(&o.id).map(|ma| ma.num_vals()).unwrap_or(0); - let num_pending = self - .pending - .as_ref() - .and_then(|p| (p.id == o.id).then(|| p.raw_vals.len())) - .unwrap_or(0); - let current_num = num_resolved + num_pending; - debug!( - "ArgMatcher::needs_more_vals: o={}, resolved={}, pending={}", - o.name, num_resolved, num_pending - ); - if current_num == 0 { - true - } else if let Some(num) = o.num_vals { - debug!("ArgMatcher::needs_more_vals: num_vals...{}", num); - #[allow(deprecated)] - if o.is_multiple_occurrences_set() { - (current_num % num) != 0 - } else { - num != current_num - } - } else if let Some(num) = o.max_vals { - debug!("ArgMatcher::needs_more_vals: max_vals...{}", num); - current_num < num - } else if o.min_vals.is_some() { - debug!("ArgMatcher::needs_more_vals: min_vals...true"); - true - } else { - o.is_multiple_values_set() - } - } - - pub(crate) fn pending_arg_id(&self) -> Option<&Id> { - self.pending.as_ref().map(|p| &p.id) - } - - pub(crate) fn pending_values_mut( - &mut self, - id: &Id, - ident: Option, - ) -> &mut Vec { - let pending = self.pending.get_or_insert_with(|| PendingArg { - id: id.clone(), - ident, - raw_vals: Default::default(), - }); - debug_assert_eq!(pending.id, *id, "{}", INTERNAL_ERROR_MSG); - if ident.is_some() { - debug_assert_eq!(pending.ident, ident, "{}", INTERNAL_ERROR_MSG); - } - &mut pending.raw_vals - } - - pub(crate) fn take_pending(&mut self) -> Option { - self.pending.take() - } -} - -impl Deref for ArgMatcher { - type Target = ArgMatches; - - fn deref(&self) -> &Self::Target { - &self.matches - } -} diff --git a/vendor/clap/src/parser/error.rs b/vendor/clap/src/parser/error.rs deleted file mode 100644 index bdafa9ae5..000000000 --- a/vendor/clap/src/parser/error.rs +++ /dev/null @@ -1,56 +0,0 @@ -use crate::util::Id; - -/// Violation of [`ArgMatches`][crate::ArgMatches] assumptions -#[derive(Clone, Debug)] -#[allow(missing_copy_implementations)] // We might add non-Copy types in the future -#[non_exhaustive] -pub enum MatchesError { - /// Failed to downcast `AnyValue` to the specified type - #[non_exhaustive] - Downcast { - /// Type for value stored in [`ArgMatches`][crate::ArgMatches] - actual: super::AnyValueId, - /// The target type to downcast to - expected: super::AnyValueId, - }, - /// Argument not defined in [`Command`][crate::Command] - #[non_exhaustive] - UnknownArgument { - // Missing `id` but blocked on a public id type which will hopefully come with `unstable-v4` - }, -} - -impl MatchesError { - #[track_caller] - pub(crate) fn unwrap(id: &Id, r: Result) -> T { - let err = match r { - Ok(t) => { - return t; - } - Err(err) => err, - }; - panic!( - "Mismatch between definition and access of `{:?}`. {}", - id, err - ) - } -} - -impl std::error::Error for MatchesError {} - -impl std::fmt::Display for MatchesError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Self::Downcast { actual, expected } => { - writeln!( - f, - "Could not downcast to {:?}, need to downcast to {:?}", - expected, actual - ) - } - Self::UnknownArgument {} => { - writeln!(f, "Unknown argument or group id. Make sure you are using the argument id and not the short or long flags") - } - } - } -} diff --git a/vendor/clap/src/parser/features/mod.rs b/vendor/clap/src/parser/features/mod.rs deleted file mode 100644 index bdeb766ec..000000000 --- a/vendor/clap/src/parser/features/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod suggestions; diff --git a/vendor/clap/src/parser/features/suggestions.rs b/vendor/clap/src/parser/features/suggestions.rs deleted file mode 100644 index 9e46f3c9e..000000000 --- a/vendor/clap/src/parser/features/suggestions.rs +++ /dev/null @@ -1,105 +0,0 @@ -#[cfg(feature = "suggestions")] -use std::cmp::Ordering; - -// Internal -use crate::builder::Command; - -/// Produces multiple strings from a given list of possible values which are similar -/// to the passed in value `v` within a certain confidence by least confidence. -/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield -/// `Some("foo")`, whereas "blark" would yield `None`. -#[cfg(feature = "suggestions")] -pub(crate) fn did_you_mean(v: &str, possible_values: I) -> Vec -where - T: AsRef, - I: IntoIterator, -{ - let mut candidates: Vec<(f64, String)> = possible_values - .into_iter() - .map(|pv| (strsim::jaro_winkler(v, pv.as_ref()), pv.as_ref().to_owned())) - .filter(|(confidence, _)| *confidence > 0.8) - .collect(); - candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)); - candidates.into_iter().map(|(_, pv)| pv).collect() -} - -#[cfg(not(feature = "suggestions"))] -pub(crate) fn did_you_mean(_: &str, _: I) -> Vec -where - T: AsRef, - I: IntoIterator, -{ - Vec::new() -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -pub(crate) fn did_you_mean_flag<'a, 'help, I, T>( - arg: &str, - remaining_args: &[&str], - longs: I, - subcommands: impl IntoIterator>, -) -> Option<(String, Option)> -where - 'help: 'a, - T: AsRef, - I: IntoIterator, -{ - use crate::mkeymap::KeyType; - - match did_you_mean(arg, longs).pop() { - Some(candidate) => Some((candidate, None)), - None => subcommands - .into_iter() - .filter_map(|subcommand| { - subcommand._build_self(); - - let longs = subcommand.get_keymap().keys().filter_map(|a| { - if let KeyType::Long(v) = a { - Some(v.to_string_lossy().into_owned()) - } else { - None - } - }); - - let subcommand_name = subcommand.get_name(); - - let candidate = did_you_mean(arg, longs).pop()?; - let score = remaining_args.iter().position(|x| *x == subcommand_name)?; - Some((score, (candidate, Some(subcommand_name.to_string())))) - }) - .min_by_key(|(x, _)| *x) - .map(|(_, suggestion)| suggestion), - } -} - -#[cfg(all(test, features = "suggestions"))] -mod test { - use super::*; - - #[test] - fn possible_values_match() { - let p_vals = ["test", "possible", "values"]; - assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test")); - } - - #[test] - fn possible_values_match() { - let p_vals = ["test", "temp"]; - assert_eq!(did_you_mean("te", p_vals.iter()), Some("test")); - } - - #[test] - fn possible_values_nomatch() { - let p_vals = ["test", "possible", "values"]; - assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); - } - - #[test] - fn flag() { - let p_vals = ["test", "possible", "values"]; - assert_eq!( - did_you_mean_flag("tst", p_vals.iter(), []), - Some(("test", None)) - ); - } -} diff --git a/vendor/clap/src/parser/matches/any_value.rs b/vendor/clap/src/parser/matches/any_value.rs deleted file mode 100644 index a9277e75f..000000000 --- a/vendor/clap/src/parser/matches/any_value.rs +++ /dev/null @@ -1,112 +0,0 @@ -#[derive(Clone)] -pub(crate) struct AnyValue { - inner: std::sync::Arc, - // While we can extract `TypeId` from `inner`, the debug repr is of a number, so let's track - // the type_name in debug builds. - id: AnyValueId, -} - -impl AnyValue { - pub(crate) fn new(inner: V) -> Self { - let id = AnyValueId::of::(); - let inner = std::sync::Arc::new(inner); - Self { inner, id } - } - - pub(crate) fn downcast_ref( - &self, - ) -> Option<&T> { - self.inner.downcast_ref::() - } - - pub(crate) fn downcast_into(self) -> Result { - let id = self.id; - let value = - std::sync::Arc::downcast::(self.inner).map_err(|inner| Self { inner, id })?; - let value = std::sync::Arc::try_unwrap(value).unwrap_or_else(|arc| (*arc).clone()); - Ok(value) - } - - pub(crate) fn type_id(&self) -> AnyValueId { - self.id - } -} - -impl std::fmt::Debug for AnyValue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - f.debug_struct("AnyValue").field("inner", &self.id).finish() - } -} - -#[derive(Copy, Clone)] -pub struct AnyValueId { - type_id: std::any::TypeId, - #[cfg(debug_assertions)] - type_name: &'static str, -} - -impl AnyValueId { - pub(crate) fn of() -> Self { - Self { - type_id: std::any::TypeId::of::(), - #[cfg(debug_assertions)] - type_name: std::any::type_name::(), - } - } -} - -impl PartialEq for AnyValueId { - fn eq(&self, other: &Self) -> bool { - self.type_id == other.type_id - } -} - -impl Eq for AnyValueId {} - -impl PartialOrd for AnyValueId { - fn partial_cmp(&self, other: &Self) -> Option { - self.type_id.partial_cmp(&other.type_id) - } -} - -impl Ord for AnyValueId { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.type_id.cmp(&other.type_id) - } -} - -impl std::hash::Hash for AnyValueId { - fn hash(&self, state: &mut H) { - self.type_id.hash(state); - } -} - -impl std::fmt::Debug for AnyValueId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - #[cfg(not(debug_assertions))] - { - self.type_id.fmt(f) - } - #[cfg(debug_assertions)] - { - f.debug_struct(self.type_name).finish() - } - } -} - -impl<'a, A: ?Sized + 'static> From<&'a A> for AnyValueId { - fn from(_: &'a A) -> Self { - Self::of::() - } -} - -#[cfg(test)] -mod test { - #[test] - #[cfg(debug_assertions)] - fn debug_impl() { - use super::*; - - assert_eq!(format!("{:?}", AnyValue::new(5)), "AnyValue { inner: i32 }"); - } -} diff --git a/vendor/clap/src/parser/matches/arg_matches.rs b/vendor/clap/src/parser/matches/arg_matches.rs deleted file mode 100644 index 17fa63ca6..000000000 --- a/vendor/clap/src/parser/matches/arg_matches.rs +++ /dev/null @@ -1,1828 +0,0 @@ -// Std -use std::any::Any; -use std::borrow::Cow; -use std::ffi::{OsStr, OsString}; -use std::fmt::{Debug, Display}; -use std::iter::{Cloned, Flatten, Map}; -use std::slice::Iter; -use std::str::FromStr; - -// Third Party -use indexmap::IndexMap; - -// Internal -use crate::parser::AnyValue; -use crate::parser::AnyValueId; -use crate::parser::MatchedArg; -use crate::parser::MatchesError; -use crate::parser::ValueSource; -use crate::util::{Id, Key}; -use crate::Error; -use crate::INTERNAL_ERROR_MSG; - -/// Container for parse results. -/// -/// Used to get information about the arguments that were supplied to the program at runtime by -/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of -/// methods. -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{Command, Arg, ValueSource}; -/// let matches = Command::new("MyApp") -/// .arg(Arg::new("out") -/// .long("output") -/// .required(true) -/// .takes_value(true) -/// .default_value("-")) -/// .arg(Arg::new("cfg") -/// .short('c') -/// .takes_value(true)) -/// .get_matches(); // builds the instance of ArgMatches -/// -/// // to get information about the "cfg" argument we created, such as the value supplied we use -/// // various ArgMatches methods, such as [ArgMatches::get_one] -/// if let Some(c) = matches.get_one::("cfg") { -/// println!("Value for -c: {}", c); -/// } -/// -/// // The ArgMatches::get_one method returns an Option because the user may not have supplied -/// // that argument at runtime. But if we specified that the argument was "required" as we did -/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually -/// // used at runtime. -/// println!("Value for --output: {}", matches.get_one::("out").unwrap()); -/// -/// // You can check the presence of an argument's values -/// if matches.contains_id("out") { -/// // However, if you want to know where the value came from -/// if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine { -/// println!("`out` set by user"); -/// } else { -/// println!("`out` is defaulted"); -/// } -/// } -/// ``` -/// [`Command::get_matches`]: crate::Command::get_matches() -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ArgMatches { - #[cfg(debug_assertions)] - pub(crate) valid_args: Vec, - #[cfg(debug_assertions)] - pub(crate) valid_subcommands: Vec, - #[cfg(debug_assertions)] - pub(crate) disable_asserts: bool, - pub(crate) args: IndexMap, - pub(crate) subcommand: Option>, -} - -/// # Arguments -impl ArgMatches { - /// Gets the value of a specific option or positional argument. - /// - /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. - /// - /// Returns an error if the wrong type was used. - /// - /// Returns `None` if the option wasn't present. - /// - /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_one`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("port") - /// .value_parser(value_parser!(usize)) - /// .takes_value(true) - /// .required(true)) - /// .get_matches_from(vec!["myapp", "2020"]); - /// - /// let port: usize = *m - /// .get_one("port") - /// .expect("`port`is required"); - /// assert_eq!(port, 2020); - /// ``` - /// [option]: crate::Arg::takes_value() - /// [positional]: crate::Arg::index() - /// [`default_value`]: crate::Arg::default_value() - #[track_caller] - pub fn get_one(&self, id: &str) -> Option<&T> { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_get_one(id)) - } - - /// Iterate over values of a specific option or positional argument. - /// - /// i.e. an argument that takes multiple values at runtime. - /// - /// Returns an error if the wrong type was used. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_many`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("ports") - /// .action(ArgAction::Append) - /// .value_parser(value_parser!(usize)) - /// .short('p') - /// .takes_value(true) - /// .required(true)) - /// .get_matches_from(vec![ - /// "myprog", "-p", "22", "-p", "80", "-p", "2020" - /// ]); - /// let vals: Vec = m.get_many("ports") - /// .expect("`port`is required") - /// .copied() - /// .collect(); - /// assert_eq!(vals, [22, 80, 2020]); - /// ``` - #[track_caller] - pub fn get_many( - &self, - id: &str, - ) -> Option> { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_get_many(id)) - } - - /// Iterate over the original argument values. - /// - /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they - /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid - /// filename on a Unix system as an argument value may contain invalid UTF-8. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_raw`]. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, arg, value_parser}; - /// # use std::ffi::{OsStr,OsString}; - /// # use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// use std::path::PathBuf; - /// - /// let m = Command::new("utf8") - /// .arg(arg!( ... "some arg").value_parser(value_parser!(PathBuf))) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi" - /// OsString::from_vec(vec![b'H', b'i']), - /// // "{0xe9}!" - /// OsString::from_vec(vec![0xe9, b'!'])]); - /// - /// let mut itr = m.get_raw("arg") - /// .expect("`port`is required") - /// .into_iter(); - /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); - /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); - /// assert_eq!(itr.next(), None); - /// ``` - /// [`Iterator`]: std::iter::Iterator - /// [`OsSt`]: std::ffi::OsStr - /// [values]: OsValues - /// [`String`]: std::string::String - #[track_caller] - pub fn get_raw(&self, id: &str) -> Option> { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_get_raw(id)) - } - - /// Returns the value of a specific option or positional argument. - /// - /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. - /// - /// Returns an error if the wrong type was used. No item will have been removed. - /// - /// Returns `None` if the option wasn't present. - /// - /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_remove_one`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser}; - /// let mut m = Command::new("myprog") - /// .arg(Arg::new("file") - /// .required(true) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "myprog", "file.txt", - /// ]); - /// let vals: String = m.remove_one("file") - /// .expect("`file`is required"); - /// assert_eq!(vals, "file.txt"); - /// ``` - /// [option]: crate::Arg::takes_value() - /// [positional]: crate::Arg::index() - /// [`default_value`]: crate::Arg::default_value() - #[track_caller] - pub fn remove_one(&mut self, id: &str) -> Option { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_remove_one(id)) - } - - /// Return values of a specific option or positional argument. - /// - /// i.e. an argument that takes multiple values at runtime. - /// - /// Returns an error if the wrong type was used. No item will have been removed. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_remove_many`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let mut m = Command::new("myprog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Append) - /// .multiple_values(true) - /// .required(true) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt", - /// ]); - /// let vals: Vec = m.remove_many("file") - /// .expect("`file`is required") - /// .collect(); - /// assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]); - /// ``` - #[track_caller] - pub fn remove_many( - &mut self, - id: &str, - ) -> Option> { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_remove_many(id)) - } - - /// Check if values are present for the argument or group id - /// - /// *NOTE:* This will always return `true` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panics - /// - /// If `id` is is not a valid argument or group name. To handle this case programmatically, see - /// [`ArgMatches::try_contains_id`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d')) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert!(m.contains_id("debug")); - /// ``` - /// - /// [`default_value`]: crate::Arg::default_value() - pub fn contains_id(&self, id: &str) -> bool { - let internal_id = Id::from(id); - MatchesError::unwrap(&internal_id, self.try_contains_id(id)) - } - - /// Check if any args were present on the command line - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let mut cmd = Command::new("myapp") - /// .arg(Arg::new("output") - /// .takes_value(true)); - /// - /// let m = cmd - /// .try_get_matches_from_mut(vec!["myapp", "something"]) - /// .unwrap(); - /// assert!(m.args_present()); - /// - /// let m = cmd - /// .try_get_matches_from_mut(vec!["myapp"]) - /// .unwrap(); - /// assert!(! m.args_present()); - pub fn args_present(&self) -> bool { - !self.args.is_empty() - } - - /// Deprecated, replaced with [`ArgMatches::get_one()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_of(&self, id: T) -> Option<&str> { - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = unwrap_string_arg(&id, arg.first()?); - Some(v) - } - - /// Deprecated, replaced with [`ArgMatches::get_one()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_of_lossy(&self, id: T) -> Option> { - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = unwrap_os_string_arg(&id, arg.first()?); - Some(v.to_string_lossy()) - } - - /// Deprecated, replaced with [`ArgMatches::get_one()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_of_os(&self, id: T) -> Option<&OsStr> { - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = unwrap_os_string_arg(&id, arg.first()?); - Some(v) - } - - /// Deprecated, replaced with [`ArgMatches::get_many()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn values_of(&self, id: T) -> Option { - #![allow(deprecated)] - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = Values { - iter: arg.vals_flatten().map(unwrap_string), - len: arg.num_vals(), - }; - Some(v) - } - - /// Get an [`Iterator`] over groups of values of a specific option. - /// - /// specifically grouped by the occurrences of the options. - /// - /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence - /// of the option. - /// - /// If the option doesn't support multiple occurrences, or there was only a single occurrence, - /// the iterator will only contain a single item. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panics - /// - /// If the value is invalid UTF-8. - /// - /// If `id` is not a valid argument or group id. - /// - /// # Examples - /// ```rust - /// # use clap::{Command,Arg, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("exec") - /// .short('x') - /// .min_values(1) - /// .action(ArgAction::Append) - /// .value_terminator(";")) - /// .get_matches_from(vec![ - /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]); - /// let vals: Vec> = m.grouped_values_of("exec").unwrap().collect(); - /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]); - /// ``` - /// [`Iterator`]: std::iter::Iterator - #[cfg(feature = "unstable-grouped")] - #[cfg_attr(debug_assertions, track_caller)] - pub fn grouped_values_of(&self, id: T) -> Option { - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = GroupedValues { - iter: arg.vals().map(|g| g.iter().map(unwrap_string).collect()), - len: arg.vals().len(), - }; - Some(v) - } - - /// Deprecated, replaced with [`ArgMatches::get_many()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn values_of_lossy(&self, id: T) -> Option> { - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = arg - .vals_flatten() - .map(|v| unwrap_os_string_arg(&id, v).to_string_lossy().into_owned()) - .collect(); - Some(v) - } - - /// Deprecated, replaced with [`ArgMatches::get_many()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn values_of_os(&self, id: T) -> Option { - #![allow(deprecated)] - let id = Id::from(id); - let arg = self.get_arg(&id)?; - let v = OsValues { - iter: arg.vals_flatten().map(unwrap_os_string), - len: arg.num_vals(), - }; - Some(v) - } - - /// Deprecated, replaced with [`ArgMatches::get_one()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_of_t(&self, name: &str) -> Result - where - R: FromStr, - ::Err: Display, - { - #![allow(deprecated)] - let v = self - .value_of(name) - .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; - v.parse::().map_err(|e| { - let message = format!( - "The argument '{}' isn't a valid value for '{}': {}", - v, name, e - ); - - Error::value_validation(name.to_string(), v.to_string(), message.into()) - }) - } - - /// Deprecated, replaced with [`ArgMatches::get_one()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_of_t_or_exit(&self, name: &str) -> R - where - R: FromStr, - ::Err: Display, - { - #![allow(deprecated)] - self.value_of_t(name).unwrap_or_else(|e| e.exit()) - } - - /// Deprecated, replaced with [`ArgMatches::get_many()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn values_of_t(&self, name: &str) -> Result, Error> - where - R: FromStr, - ::Err: Display, - { - #![allow(deprecated)] - let v = self - .values_of(name) - .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; - v.map(|v| { - v.parse::().map_err(|e| { - let message = format!("The argument '{}' isn't a valid value: {}", v, e); - - Error::value_validation(name.to_string(), v.to_string(), message.into()) - }) - }) - .collect() - } - - /// Deprecated, replaced with [`ArgMatches::get_many()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn values_of_t_or_exit(&self, name: &str) -> Vec - where - R: FromStr, - ::Err: Display, - { - #![allow(deprecated)] - self.values_of_t(name).unwrap_or_else(|e| e.exit()) - } - - /// Deprecated, replaced with [`ArgAction::SetTrue`][crate::ArgAction] or - /// [`ArgMatches::contains_id`]. - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with either `ArgAction::SetTrue` or `ArgMatches::contains_id(...)`" - ) - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn is_present(&self, id: T) -> bool { - let id = Id::from(id); - - #[cfg(debug_assertions)] - self.get_arg(&id); - - self.args.contains_key(&id) - } - - /// Report where argument value came from - /// - /// # Panics - /// - /// If `id` is is not a valid argument or group id. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ValueSource}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d')) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// [`default_value`]: crate::Arg::default_value() - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_source(&self, id: T) -> Option { - let id = Id::from(id); - - let value = self.get_arg(&id); - - value.and_then(MatchedArg::source) - } - - /// Deprecated, replaced with [`ArgAction::Count`][crate::ArgAction] or - /// [`ArgMatches::get_many`]`.len()`. - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.2.0", - note = "Replaced with either `ArgAction::Count` or `ArgMatches::get_many(...).len()`" - ) - )] - #[cfg_attr(debug_assertions, track_caller)] - pub fn occurrences_of(&self, id: T) -> u64 { - #![allow(deprecated)] - self.get_arg(&Id::from(id)) - .map_or(0, |a| a.get_occurrences()) - } - - /// The first index of that an argument showed up. - /// - /// Indices are similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// Besides the flag/option discrepancy, the primary difference between an argv index and clap - /// index, is that clap continues counting once all arguments have properly separated, whereas - /// an argv index does not. - /// - /// The examples should clear this up. - /// - /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* - /// index. See [`ArgMatches::indices_of`]. - /// - /// # Panics - /// - /// If `id` is is not a valid argument or group id. - /// - /// # Examples - /// - /// The argv indices are listed in the comments below. See how they correspond to the clap - /// indices. Note that if it's not listed in a clap index, this is because it's not saved in - /// in an `ArgMatches` struct for querying. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); - /// // ARGV indices: ^0 ^1 ^2 ^3 - /// // clap indices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Now notice, if we use one of the other styles of options: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); - /// // ARGV indices: ^0 ^1 ^2 - /// // clap indices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Things become much more complicated, or clear if we look at a more complex combination of - /// flags. Let's also throw in the final option style for good measure. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("flag2") - /// .short('F')) - /// .arg(Arg::new("flag3") - /// .short('z')) - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); - /// // ARGV indices: ^0 ^1 ^2 - /// // clap indices: ^1,2,3 ^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// One final combination of flags/options to see how they combine: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f')) - /// .arg(Arg::new("flag2") - /// .short('F')) - /// .arg(Arg::new("flag3") - /// .short('z')) - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-fzFoval"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^1,2,3^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// The last part to mention is when values are sent in multiple groups with a [delimiter]. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .use_value_delimiter(true) - /// .multiple_values(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.index_of("option"), Some(2)); - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); - /// ``` - /// [delimiter]: crate::Arg::value_delimiter() - #[cfg_attr(debug_assertions, track_caller)] - pub fn index_of(&self, id: T) -> Option { - let arg = self.get_arg(&Id::from(id))?; - let i = arg.get_index(0)?; - Some(i) - } - - /// All indices an argument appeared at when parsing. - /// - /// Indices are similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// *NOTE:* For more information about how clap indices compared to argv indices, see - /// [`ArgMatches::index_of`] - /// - /// # Panics - /// - /// If `id` is is not a valid argument or group id. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .use_value_delimiter(true) - /// .multiple_values(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); - /// ``` - /// - /// Another quick example is when flags and options are used together - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true) - /// .action(ArgAction::Append)) - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::Count)) - /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); - /// // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 - /// // clap indices: ^2 ^3 ^5 ^6 - /// - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 5]); - /// assert_eq!(m.indices_of("flag").unwrap().collect::>(), &[6]); - /// ``` - /// - /// One final example, which is an odd case; if we *don't* use value delimiter as we did with - /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they - /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single - /// index. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .takes_value(true) - /// .multiple_values(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 - /// // - /// // clap sees the above as 'myapp -o "val1,val2,val3"' - /// // ^0 ^1 ^2 - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2]); - /// ``` - /// [`ArgMatches::index_of`]: ArgMatches::index_of() - /// [delimiter]: Arg::value_delimiter() - #[cfg_attr(debug_assertions, track_caller)] - pub fn indices_of(&self, id: T) -> Option> { - let arg = self.get_arg(&Id::from(id))?; - let i = Indices { - iter: arg.indices(), - len: arg.num_vals(), - }; - Some(i) - } - - #[inline] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::try_get_one()`") - )] - pub fn is_valid_arg(&self, _id: impl Key) -> bool { - #[cfg(debug_assertions)] - { - let id = Id::from(_id); - self.disable_asserts || id == Id::empty_hash() || self.valid_args.contains(&id) - } - #[cfg(not(debug_assertions))] - { - true - } - } -} - -/// # Subcommands -impl ArgMatches { - /// The name and `ArgMatches` of the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand() { - /// Some(("clone", sub_m)) => {}, // clone was used - /// Some(("push", sub_m)) => {}, // push was used - /// Some(("commit", sub_m)) => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// - /// Another useful scenario is when you want to support third party, or external, subcommands. - /// In these cases you can't know the subcommand name ahead of time, so use a variable instead - /// with pattern matching! - /// - /// ```rust - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let app_m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match app_m.subcommand() { - /// Some((external, sub_m)) => { - /// let ext_args: Vec<&str> = sub_m.get_many::("") - /// .unwrap().map(|s| s.as_str()).collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - #[inline] - pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> { - self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches)) - } - - /// Return the name and `ArgMatches` of the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let mut app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .subcommand_required(true) - /// .get_matches(); - /// - /// let (name, sub_m) = app_m.remove_subcommand().expect("required"); - /// match (name.as_str(), sub_m) { - /// ("clone", sub_m) => {}, // clone was used - /// ("push", sub_m) => {}, // push was used - /// ("commit", sub_m) => {}, // commit was used - /// (name, _) => unimplemented!("{}", name), - /// } - /// ``` - /// - /// Another useful scenario is when you want to support third party, or external, subcommands. - /// In these cases you can't know the subcommand name ahead of time, so use a variable instead - /// with pattern matching! - /// - /// ```rust - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let mut app_m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match app_m.remove_subcommand() { - /// Some((external, mut sub_m)) => { - /// let ext_args: Vec = sub_m.remove_many("") - /// .expect("`file`is required") - /// .collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> { - self.subcommand.take().map(|sc| (sc.name, sc.matches)) - } - - /// The `ArgMatches` for the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Panics - /// - /// If `id` is is not a valid subcommand. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let app_m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue) - /// ) - /// .subcommand(Command::new("test") - /// .arg(Arg::new("opt") - /// .long("option") - /// .takes_value(true))) - /// .get_matches_from(vec![ - /// "myprog", "-d", "test", "--option", "val" - /// ]); - /// - /// // Both parent commands, and child subcommands can have arguments present at the same times - /// assert!(*app_m.get_one::("debug").expect("defaulted by clap")); - /// - /// // Get the subcommand's ArgMatches instance - /// if let Some(sub_m) = app_m.subcommand_matches("test") { - /// // Use the struct like normal - /// assert_eq!(sub_m.get_one::("opt").map(|s| s.as_str()), Some("val")); - /// } - /// ``` - /// - /// [subcommand]: crate::Command::subcommand - /// [`Command`]: crate::Command - pub fn subcommand_matches(&self, id: T) -> Option<&ArgMatches> { - self.get_subcommand(&id.into()).map(|sc| &sc.matches) - } - - /// The name of the current [subcommand]. - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand_name() { - /// Some("clone") => {}, // clone was used - /// Some("push") => {}, // push was used - /// Some("commit") => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - /// [`Command`]: crate::Command - #[inline] - pub fn subcommand_name(&self) -> Option<&str> { - self.subcommand.as_ref().map(|sc| &*sc.name) - } - - /// Check if a subcommand can be queried - /// - /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer - /// mistakes. In some context, this doesn't work, so users can use this function to check - /// before they do a query on `ArgMatches`. - #[inline] - #[doc(hidden)] - pub fn is_valid_subcommand(&self, _id: impl Key) -> bool { - #[cfg(debug_assertions)] - { - let id = Id::from(_id); - self.disable_asserts || id == Id::empty_hash() || self.valid_subcommands.contains(&id) - } - #[cfg(not(debug_assertions))] - { - true - } - } -} - -/// # Advanced -impl ArgMatches { - /// Non-panicking version of [`ArgMatches::get_one`] - pub fn try_get_one( - &self, - id: &str, - ) -> Result, MatchesError> { - let id = Id::from(id); - let arg = self.try_get_arg_t::(&id)?; - let value = match arg.and_then(|a| a.first()) { - Some(value) => value, - None => { - return Ok(None); - } - }; - Ok(value - .downcast_ref::() - .map(Some) - .expect(INTERNAL_ERROR_MSG)) // enforced by `try_get_arg_t` - } - - /// Non-panicking version of [`ArgMatches::get_many`] - pub fn try_get_many( - &self, - id: &str, - ) -> Result>, MatchesError> { - let id = Id::from(id); - let arg = match self.try_get_arg_t::(&id)? { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.vals_flatten(); - let values = ValuesRef { - // enforced by `try_get_arg_t` - iter: values.map(|v| v.downcast_ref::().expect(INTERNAL_ERROR_MSG)), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::get_raw`] - pub fn try_get_raw(&self, id: &str) -> Result>, MatchesError> { - let id = Id::from(id); - let arg = match self.try_get_arg(&id)? { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.raw_vals_flatten(); - let values = RawValues { - iter: values.map(OsString::as_os_str), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::remove_one`] - pub fn try_remove_one( - &mut self, - id: &str, - ) -> Result, MatchesError> { - let id = Id::from(id); - match self.try_remove_arg_t::(&id)? { - Some(values) => Ok(values - .into_vals_flatten() - // enforced by `try_get_arg_t` - .map(|v| v.downcast_into::().expect(INTERNAL_ERROR_MSG)) - .next()), - None => Ok(None), - } - } - - /// Non-panicking version of [`ArgMatches::remove_many`] - pub fn try_remove_many( - &mut self, - id: &str, - ) -> Result>, MatchesError> { - let id = Id::from(id); - let arg = match self.try_remove_arg_t::(&id)? { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.into_vals_flatten(); - let values = Values2 { - // enforced by `try_get_arg_t` - iter: values.map(|v| v.downcast_into::().expect(INTERNAL_ERROR_MSG)), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::contains_id`] - pub fn try_contains_id(&self, id: &str) -> Result { - let id = Id::from(id); - - self.verify_arg(&id)?; - - let presence = self.args.contains_key(&id); - Ok(presence) - } -} - -// Private methods -impl ArgMatches { - #[inline] - fn try_get_arg(&self, arg: &Id) -> Result, MatchesError> { - self.verify_arg(arg)?; - Ok(self.args.get(arg)) - } - - #[inline] - fn try_get_arg_t( - &self, - arg: &Id, - ) -> Result, MatchesError> { - let arg = match self.try_get_arg(arg)? { - Some(arg) => arg, - None => { - return Ok(None); - } - }; - self.verify_arg_t::(arg)?; - Ok(Some(arg)) - } - - #[inline] - fn try_remove_arg_t( - &mut self, - arg: &Id, - ) -> Result, MatchesError> { - self.verify_arg(arg)?; - let matched = match self.args.remove(arg) { - Some(matched) => matched, - None => { - return Ok(None); - } - }; - - let expected = AnyValueId::of::(); - let actual = matched.infer_type_id(expected); - if actual == expected { - Ok(Some(matched)) - } else { - self.args.insert(arg.clone(), matched); - Err(MatchesError::Downcast { actual, expected }) - } - } - - fn verify_arg_t( - &self, - arg: &MatchedArg, - ) -> Result<(), MatchesError> { - let expected = AnyValueId::of::(); - let actual = arg.infer_type_id(expected); - if expected == actual { - Ok(()) - } else { - Err(MatchesError::Downcast { actual, expected }) - } - } - - #[inline] - fn verify_arg(&self, _arg: &Id) -> Result<(), MatchesError> { - #[cfg(debug_assertions)] - { - if self.disable_asserts || *_arg == Id::empty_hash() || self.valid_args.contains(_arg) { - } else if self.valid_subcommands.contains(_arg) { - debug!( - "Subcommand `{:?}` used where an argument or group name was expected.", - _arg - ); - return Err(MatchesError::UnknownArgument {}); - } else { - debug!( - "`{:?}` is not an id of an argument or a group.\n\ - Make sure you're using the name of the argument itself \ - and not the name of short or long flags.", - _arg - ); - return Err(MatchesError::UnknownArgument {}); - } - } - Ok(()) - } - - #[inline] - #[cfg_attr(debug_assertions, track_caller)] - fn get_arg(&self, arg: &Id) -> Option<&MatchedArg> { - #[cfg(debug_assertions)] - { - if self.disable_asserts || *arg == Id::empty_hash() || self.valid_args.contains(arg) { - } else if self.valid_subcommands.contains(arg) { - panic!( - "Subcommand `{:?}` used where an argument or group name was expected.", - arg - ); - } else { - panic!( - "`{:?}` is not an id of an argument or a group.\n\ - Make sure you're using the name of the argument itself \ - and not the name of short or long flags.", - arg - ); - } - } - - self.args.get(arg) - } - - #[inline] - #[cfg_attr(debug_assertions, track_caller)] - fn get_subcommand(&self, id: &Id) -> Option<&SubCommand> { - #[cfg(debug_assertions)] - { - if self.disable_asserts - || *id == Id::empty_hash() - || self.valid_subcommands.contains(id) - { - } else if self.valid_args.contains(id) { - panic!( - "Argument or group `{:?}` used where a subcommand name was expected.", - id - ); - } else { - panic!("`{:?}` is not a name of a subcommand.", id); - } - } - - if let Some(ref sc) = self.subcommand { - if sc.id == *id { - return Some(sc); - } - } - - None - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct SubCommand { - pub(crate) id: Id, - pub(crate) name: String, - pub(crate) matches: ArgMatches, -} - -/// Iterate over multiple values for an argument via [`ArgMatches::remove_many`]. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, ArgAction}; -/// let mut m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .action(ArgAction::Append) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); -/// -/// let mut values = m.remove_many::("output") -/// .unwrap(); -/// -/// assert_eq!(values.next(), Some(String::from("val1"))); -/// assert_eq!(values.next(), Some(String::from("val2"))); -/// assert_eq!(values.next(), None); -/// ``` -#[derive(Clone, Debug)] -pub struct Values2 { - #[allow(clippy::type_complexity)] - iter: Map>>, fn(AnyValue) -> T>, - len: usize, -} - -impl Iterator for Values2 { - type Item = T; - - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -impl DoubleEndedIterator for Values2 { - fn next_back(&mut self) -> Option { - self.iter.next_back() - } -} - -impl ExactSizeIterator for Values2 {} - -/// Creates an empty iterator. -impl Default for Values2 { - fn default() -> Self { - let empty: Vec> = Default::default(); - Values2 { - iter: empty.into_iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Iterate over multiple values for an argument via [`ArgMatches::get_many`]. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, ArgAction}; -/// let m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .action(ArgAction::Append) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); -/// -/// let mut values = m.get_many::("output") -/// .unwrap() -/// .map(|s| s.as_str()); -/// -/// assert_eq!(values.next(), Some("val1")); -/// assert_eq!(values.next(), Some("val2")); -/// assert_eq!(values.next(), None); -/// ``` -#[derive(Clone, Debug)] -pub struct ValuesRef<'a, T> { - #[allow(clippy::type_complexity)] - iter: Map>>, fn(&AnyValue) -> &T>, - len: usize, -} - -impl<'a, T: 'a> Iterator for ValuesRef<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> { - fn next_back(&mut self) -> Option { - self.iter.next_back() - } -} - -impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {} - -/// Creates an empty iterator. -impl<'a, T: 'a> Default for ValuesRef<'a, T> { - fn default() -> Self { - static EMPTY: [Vec; 0] = []; - ValuesRef { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Iterate over raw argument values via [`ArgMatches::get_raw`]. -/// -/// # Examples -/// -#[cfg_attr(not(unix), doc = " ```ignore")] -#[cfg_attr(unix, doc = " ```")] -/// # use clap::{Command, arg, value_parser}; -/// use std::ffi::OsString; -/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; -/// -/// let m = Command::new("utf8") -/// .arg(arg!( "some arg") -/// .value_parser(value_parser!(OsString))) -/// .get_matches_from(vec![OsString::from("myprog"), -/// // "Hi {0xe9}!" -/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); -/// assert_eq!( -/// &*m.get_raw("arg") -/// .unwrap() -/// .next().unwrap() -/// .as_bytes(), -/// [b'H', b'i', b' ', 0xe9, b'!'] -/// ); -/// ``` -#[derive(Clone, Debug)] -pub struct RawValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map>>, fn(&OsString) -> &OsStr>, - len: usize, -} - -impl<'a> Iterator for RawValues<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -impl<'a> DoubleEndedIterator for RawValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for RawValues<'a> {} - -/// Creates an empty iterator. -impl Default for RawValues<'_> { - fn default() -> Self { - static EMPTY: [Vec; 0] = []; - RawValues { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -// The following were taken and adapted from vec_map source -// repo: https://github.com/contain-rs/vec-map -// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 -// license: MIT - Copyright (c) 2015 The Rust Project Developers - -/// Deprecated, replaced with [`ArgMatches::get_many()`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") -)] -#[derive(Clone, Debug)] -pub struct Values<'a> { - #[allow(clippy::type_complexity)] - iter: Map>>, for<'r> fn(&'r AnyValue) -> &'r str>, - len: usize, -} - -#[allow(deprecated)] -impl<'a> Iterator for Values<'a> { - type Item = &'a str; - - fn next(&mut self) -> Option<&'a str> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -#[allow(deprecated)] -impl<'a> DoubleEndedIterator for Values<'a> { - fn next_back(&mut self) -> Option<&'a str> { - self.iter.next_back() - } -} - -#[allow(deprecated)] -impl<'a> ExactSizeIterator for Values<'a> {} - -/// Creates an empty iterator. -#[allow(deprecated)] -impl<'a> Default for Values<'a> { - fn default() -> Self { - static EMPTY: [Vec; 0] = []; - Values { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -#[derive(Clone)] -#[allow(missing_debug_implementations)] -pub struct GroupedValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map>, fn(&Vec) -> Vec<&str>>, - len: usize, -} - -impl<'a> Iterator for GroupedValues<'a> { - type Item = Vec<&'a str>; - - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -impl<'a> DoubleEndedIterator for GroupedValues<'a> { - fn next_back(&mut self) -> Option { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for GroupedValues<'a> {} - -/// Creates an empty iterator. Used for `unwrap_or_default()`. -impl<'a> Default for GroupedValues<'a> { - fn default() -> Self { - #![allow(deprecated)] - static EMPTY: [Vec; 0] = []; - GroupedValues { - iter: EMPTY[..].iter().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Deprecated, replaced with [`ArgMatches::get_many()`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") -)] -#[derive(Clone, Debug)] -pub struct OsValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map>>, fn(&AnyValue) -> &OsStr>, - len: usize, -} - -#[allow(deprecated)] -impl<'a> Iterator for OsValues<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -#[allow(deprecated)] -impl<'a> DoubleEndedIterator for OsValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { - self.iter.next_back() - } -} - -#[allow(deprecated)] -impl<'a> ExactSizeIterator for OsValues<'a> {} - -/// Creates an empty iterator. -#[allow(deprecated)] -impl Default for OsValues<'_> { - fn default() -> Self { - static EMPTY: [Vec; 0] = []; - OsValues { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`] -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg}; -/// let m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .multiple_values(true) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); -/// -/// let mut indices = m.indices_of("output").unwrap(); -/// -/// assert_eq!(indices.next(), Some(2)); -/// assert_eq!(indices.next(), Some(3)); -/// assert_eq!(indices.next(), None); -/// ``` -/// [`ArgMatches::indices_of`]: ArgMatches::indices_of() -#[derive(Clone, Debug)] -pub struct Indices<'a> { - iter: Cloned>, - len: usize, -} - -impl<'a> Iterator for Indices<'a> { - type Item = usize; - - fn next(&mut self) -> Option { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option) { - (self.len, Some(self.len)) - } -} - -impl<'a> DoubleEndedIterator for Indices<'a> { - fn next_back(&mut self) -> Option { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for Indices<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for Indices<'a> { - fn default() -> Self { - static EMPTY: [usize; 0] = []; - // This is never called because the iterator is empty: - Indices { - iter: EMPTY[..].iter().cloned(), - len: 0, - } - } -} - -#[cfg_attr(debug_assertions, track_caller)] -#[inline] -fn unwrap_string(value: &AnyValue) -> &str { - match value.downcast_ref::() { - Some(value) => value, - None => { - panic!("Must use `_os` lookups with `Arg::allow_invalid_utf8`",) - } - } -} - -#[cfg_attr(debug_assertions, track_caller)] -#[inline] -fn unwrap_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v str { - match value.downcast_ref::() { - Some(value) => value, - None => { - panic!( - "Must use `_os` lookups with `Arg::allow_invalid_utf8` at `{:?}`", - id - ) - } - } -} - -#[cfg_attr(debug_assertions, track_caller)] -#[inline] -fn unwrap_os_string(value: &AnyValue) -> &OsStr { - match value.downcast_ref::() { - Some(value) => value, - None => { - panic!("Must use `Arg::allow_invalid_utf8` with `_os` lookups",) - } - } -} - -#[cfg_attr(debug_assertions, track_caller)] -#[inline] -fn unwrap_os_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v OsStr { - match value.downcast_ref::() { - Some(value) => value, - None => { - panic!( - "Must use `Arg::allow_invalid_utf8` with `_os` lookups at `{:?}`", - id - ) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_default_values() { - #![allow(deprecated)] - let mut values: Values = Values::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_osvalues() { - #![allow(deprecated)] - let mut values: OsValues = OsValues::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_raw_values() { - let mut values: RawValues = Default::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_indices() { - let mut indices: Indices = Indices::default(); - assert_eq!(indices.next(), None); - } - - #[test] - fn test_default_indices_with_shorter_lifetime() { - let matches = ArgMatches::default(); - let mut indices = matches.indices_of("").unwrap_or_default(); - assert_eq!(indices.next(), None); - } - - #[test] - fn values_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .takes_value(true) - .multiple_values(true) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .get_many::("POTATO") - .expect("present") - .count(); - assert_eq!(l, 1); - } - - #[test] - fn os_values_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .takes_value(true) - .multiple_values(true) - .value_parser(crate::builder::ValueParser::os_string()) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .get_many::("POTATO") - .expect("present") - .count(); - assert_eq!(l, 1); - } - - #[test] - fn indices_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .takes_value(true) - .multiple_values(true) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .indices_of("POTATO") - .expect("present") - .len(); - assert_eq!(l, 1); - } -} diff --git a/vendor/clap/src/parser/matches/matched_arg.rs b/vendor/clap/src/parser/matches/matched_arg.rs deleted file mode 100644 index fde6d37f3..000000000 --- a/vendor/clap/src/parser/matches/matched_arg.rs +++ /dev/null @@ -1,240 +0,0 @@ -// Std -use std::{ - ffi::{OsStr, OsString}, - iter::{Cloned, Flatten}, - slice::Iter, -}; - -use crate::builder::ArgPredicate; -use crate::parser::AnyValue; -use crate::parser::AnyValueId; -use crate::parser::ValueSource; -use crate::util::eq_ignore_case; -use crate::INTERNAL_ERROR_MSG; - -#[derive(Debug, Clone)] -pub(crate) struct MatchedArg { - occurs: u64, - source: Option, - indices: Vec, - type_id: Option, - vals: Vec>, - raw_vals: Vec>, - ignore_case: bool, -} - -impl MatchedArg { - pub(crate) fn new_arg(arg: &crate::Arg) -> Self { - let ignore_case = arg.is_ignore_case_set(); - Self { - occurs: 0, - source: None, - indices: Vec::new(), - type_id: Some(arg.get_value_parser().type_id()), - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - pub(crate) fn new_group() -> Self { - let ignore_case = false; - Self { - occurs: 0, - source: None, - indices: Vec::new(), - type_id: None, - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - pub(crate) fn new_external(cmd: &crate::Command) -> Self { - let ignore_case = false; - Self { - occurs: 0, - source: None, - indices: Vec::new(), - type_id: Some( - cmd.get_external_subcommand_value_parser() - .expect(INTERNAL_ERROR_MSG) - .type_id(), - ), - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] - pub(crate) fn inc_occurrences(&mut self) { - self.occurs += 1; - } - - #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] - pub(crate) fn set_occurrences(&mut self, occurs: u64) { - self.occurs = occurs - } - - #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] - pub(crate) fn get_occurrences(&self) -> u64 { - self.occurs - } - - pub(crate) fn indices(&self) -> Cloned> { - self.indices.iter().cloned() - } - - pub(crate) fn get_index(&self, index: usize) -> Option { - self.indices.get(index).cloned() - } - - pub(crate) fn push_index(&mut self, index: usize) { - self.indices.push(index) - } - - #[cfg(feature = "unstable-grouped")] - pub(crate) fn vals(&self) -> Iter> { - self.vals.iter() - } - - pub(crate) fn vals_flatten(&self) -> Flatten>> { - self.vals.iter().flatten() - } - - pub(crate) fn into_vals_flatten(self) -> Flatten>> { - self.vals.into_iter().flatten() - } - - pub(crate) fn raw_vals_flatten(&self) -> Flatten>> { - self.raw_vals.iter().flatten() - } - - pub(crate) fn first(&self) -> Option<&AnyValue> { - self.vals_flatten().next() - } - - #[cfg(test)] - pub(crate) fn first_raw(&self) -> Option<&OsString> { - self.raw_vals_flatten().next() - } - - pub(crate) fn new_val_group(&mut self) { - self.vals.push(vec![]); - self.raw_vals.push(vec![]); - } - - pub(crate) fn append_val(&mut self, val: AnyValue, raw_val: OsString) { - // We assume there is always a group created before. - self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val); - self.raw_vals - .last_mut() - .expect(INTERNAL_ERROR_MSG) - .push(raw_val); - } - - pub(crate) fn num_vals(&self) -> usize { - self.vals.iter().map(|v| v.len()).sum() - } - - // Will be used later - #[allow(dead_code)] - pub(crate) fn num_vals_last_group(&self) -> usize { - self.vals.last().map(|x| x.len()).unwrap_or(0) - } - - pub(crate) fn all_val_groups_empty(&self) -> bool { - self.vals.iter().flatten().count() == 0 - } - - pub(crate) fn check_explicit(&self, predicate: ArgPredicate) -> bool { - if self.source == Some(ValueSource::DefaultValue) { - return false; - } - - match predicate { - ArgPredicate::Equals(val) => self.raw_vals_flatten().any(|v| { - if self.ignore_case { - // If `v` isn't utf8, it can't match `val`, so `OsStr::to_str` should be fine - eq_ignore_case(&v.to_string_lossy(), &val.to_string_lossy()) - } else { - OsString::as_os_str(v) == OsStr::new(val) - } - }), - ArgPredicate::IsPresent => true, - } - } - - pub(crate) fn source(&self) -> Option { - self.source - } - - pub(crate) fn set_source(&mut self, source: ValueSource) { - if let Some(existing) = self.source { - self.source = Some(existing.max(source)); - } else { - self.source = Some(source) - } - } - - pub(crate) fn type_id(&self) -> Option { - self.type_id - } - - pub(crate) fn infer_type_id(&self, expected: AnyValueId) -> AnyValueId { - self.type_id() - .or_else(|| { - self.vals_flatten() - .map(|v| v.type_id()) - .find(|actual| *actual != expected) - }) - .unwrap_or(expected) - } -} - -impl PartialEq for MatchedArg { - fn eq(&self, other: &MatchedArg) -> bool { - let MatchedArg { - occurs: self_occurs, - source: self_source, - indices: self_indices, - type_id: self_type_id, - vals: _, - raw_vals: self_raw_vals, - ignore_case: self_ignore_case, - } = self; - let MatchedArg { - occurs: other_occurs, - source: other_source, - indices: other_indices, - type_id: other_type_id, - vals: _, - raw_vals: other_raw_vals, - ignore_case: other_ignore_case, - } = other; - self_occurs == other_occurs - && self_source == other_source - && self_indices == other_indices - && self_type_id == other_type_id - && self_raw_vals == other_raw_vals - && self_ignore_case == other_ignore_case - } -} - -impl Eq for MatchedArg {} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_grouped_vals_first() { - let mut m = MatchedArg::new_group(); - m.new_val_group(); - m.new_val_group(); - m.append_val(AnyValue::new(String::from("bbb")), "bbb".into()); - m.append_val(AnyValue::new(String::from("ccc")), "ccc".into()); - assert_eq!(m.first_raw(), Some(&OsString::from("bbb"))); - } -} diff --git a/vendor/clap/src/parser/matches/mod.rs b/vendor/clap/src/parser/matches/mod.rs deleted file mode 100644 index 7b88eeca7..000000000 --- a/vendor/clap/src/parser/matches/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -mod any_value; -mod arg_matches; -mod matched_arg; -mod value_source; - -pub use any_value::AnyValueId; -pub use arg_matches::RawValues; -pub use arg_matches::ValuesRef; -pub use arg_matches::{ArgMatches, Indices}; -pub use value_source::ValueSource; - -pub(crate) use any_value::AnyValue; -pub(crate) use arg_matches::SubCommand; -pub(crate) use matched_arg::MatchedArg; - -#[allow(deprecated)] -pub use arg_matches::{OsValues, Values}; diff --git a/vendor/clap/src/parser/matches/value_source.rs b/vendor/clap/src/parser/matches/value_source.rs deleted file mode 100644 index fb762d2af..000000000 --- a/vendor/clap/src/parser/matches/value_source.rs +++ /dev/null @@ -1,11 +0,0 @@ -/// Origin of the argument's value -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[non_exhaustive] -pub enum ValueSource { - /// Value came [`Arg::default_value`][crate::Arg::default_value] - DefaultValue, - /// Value came [`Arg::env`][crate::Arg::env] - EnvVariable, - /// Value was passed in on the command-line - CommandLine, -} diff --git a/vendor/clap/src/parser/mod.rs b/vendor/clap/src/parser/mod.rs deleted file mode 100644 index da81648e1..000000000 --- a/vendor/clap/src/parser/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! [`Command`][crate::Command] line argument parser - -mod arg_matcher; -mod error; -mod matches; -#[allow(clippy::module_inception)] -mod parser; -mod validator; - -pub(crate) mod features; - -pub(crate) use self::arg_matcher::ArgMatcher; -pub(crate) use self::matches::AnyValue; -pub(crate) use self::matches::AnyValueId; -pub(crate) use self::matches::{MatchedArg, SubCommand}; -pub(crate) use self::parser::Identifier; -pub(crate) use self::parser::PendingArg; -pub(crate) use self::parser::{ParseState, Parser}; -pub(crate) use self::validator::Validator; - -pub use self::matches::RawValues; -pub use self::matches::ValuesRef; -pub use self::matches::{ArgMatches, Indices, ValueSource}; -pub use error::MatchesError; - -#[allow(deprecated)] -pub use self::matches::{OsValues, Values}; diff --git a/vendor/clap/src/parser/parser.rs b/vendor/clap/src/parser/parser.rs deleted file mode 100644 index fc95dad22..000000000 --- a/vendor/clap/src/parser/parser.rs +++ /dev/null @@ -1,1727 +0,0 @@ -// Std -use std::{ - cell::Cell, - ffi::{OsStr, OsString}, -}; - -// Third Party -use clap_lex::RawOsStr; - -// Internal -use crate::builder::AppSettings as AS; -use crate::builder::{Arg, Command}; -use crate::error::Error as ClapError; -use crate::error::Result as ClapResult; -use crate::mkeymap::KeyType; -use crate::output::fmt::Stream; -use crate::output::{fmt::Colorizer, Usage}; -use crate::parser::features::suggestions; -use crate::parser::{ArgMatcher, SubCommand}; -use crate::parser::{Validator, ValueSource}; -use crate::util::Id; -use crate::ArgAction; -use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; - -pub(crate) struct Parser<'help, 'cmd> { - cmd: &'cmd mut Command<'help>, - cur_idx: Cell, - /// Index of the previous flag subcommand in a group of flags. - flag_subcmd_at: Option, - /// Counter indicating the number of items to skip - /// when revisiting the group of flags which includes the flag subcommand. - flag_subcmd_skip: usize, -} - -// Initializing Methods -impl<'help, 'cmd> Parser<'help, 'cmd> { - pub(crate) fn new(cmd: &'cmd mut Command<'help>) -> Self { - Parser { - cmd, - cur_idx: Cell::new(0), - flag_subcmd_at: None, - flag_subcmd_skip: 0, - } - } -} - -// Parsing Methods -impl<'help, 'cmd> Parser<'help, 'cmd> { - // The actual parsing function - #[allow(clippy::cognitive_complexity)] - pub(crate) fn get_matches_with( - &mut self, - matcher: &mut ArgMatcher, - raw_args: &mut clap_lex::RawArgs, - mut args_cursor: clap_lex::ArgCursor, - ) -> ClapResult<()> { - debug!("Parser::get_matches_with"); - // Verify all positional assertions pass - - let mut subcmd_name: Option = None; - let mut keep_state = false; - let mut parse_state = ParseState::ValuesDone; - let mut pos_counter = 1; - - // Already met any valid arg(then we shouldn't expect subcommands after it). - let mut valid_arg_found = false; - // If the user already passed '--'. Meaning only positional args follow. - let mut trailing_values = false; - - // Count of positional args - let positional_count = self - .cmd - .get_keymap() - .keys() - .filter(|x| x.is_position()) - .count(); - // If any arg sets .last(true) - let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set()); - - while let Some(arg_os) = raw_args.next(&mut args_cursor) { - // Recover the replaced items if any. - if let Some(replaced_items) = arg_os - .to_value() - .ok() - .and_then(|a| self.cmd.get_replacement(a)) - { - debug!( - "Parser::get_matches_with: found replacer: {:?}, target: {:?}", - arg_os, replaced_items - ); - raw_args.insert(&args_cursor, replaced_items); - continue; - } - - debug!( - "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", - arg_os.to_value_os(), - arg_os.to_value_os().as_raw_bytes() - ); - - // Correct pos_counter. - pos_counter = { - let is_second_to_last = pos_counter + 1 == positional_count; - - // The last positional argument, or second to last positional - // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)` - let low_index_mults = is_second_to_last - && self - .cmd - .get_positionals() - .any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0))) - && self - .cmd - .get_positionals() - .last() - .map_or(false, |p_name| !p_name.is_last_set()); - - let missing_pos = self.cmd.is_allow_missing_positional_set() - && is_second_to_last - && !trailing_values; - - debug!( - "Parser::get_matches_with: Positional counter...{}", - pos_counter - ); - debug!( - "Parser::get_matches_with: Low index multiples...{:?}", - low_index_mults - ); - - if low_index_mults || missing_pos { - let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { - if let Some(arg) = self - .cmd - .get_positionals() - .find(|a| a.index == Some(pos_counter)) - { - // If next value looks like a new_arg or it's a - // subcommand, skip positional argument under current - // pos_counter(which means current value cannot be a - // positional argument with a value next to it), assume - // current value matches the next arg. - self.is_new_arg(&n, arg) - || self - .possible_subcommand(n.to_value(), valid_arg_found) - .is_some() - } else { - true - } - } else { - true - }; - - if skip_current { - debug!("Parser::get_matches_with: Bumping the positional counter..."); - pos_counter + 1 - } else { - pos_counter - } - } else if trailing_values - && (self.cmd.is_allow_missing_positional_set() || contains_last) - { - // Came to -- and one positional has .last(true) set, so we go immediately - // to the last (highest index) positional - debug!("Parser::get_matches_with: .last(true) and --, setting last pos"); - positional_count - } else { - pos_counter - } - }; - - // Has the user already passed '--'? Meaning only positional args follow - if !trailing_values { - if self.cmd.is_subcommand_precedence_over_arg_set() - || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_)) - { - // Does the arg match a subcommand name, or any of its aliases (if defined) - let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found); - debug!("Parser::get_matches_with: sc={:?}", sc_name); - if let Some(sc_name) = sc_name { - #[allow(deprecated)] - if sc_name == "help" - && !self.is_set(AS::NoAutoHelp) - && !self.cmd.is_disable_help_subcommand_set() - { - self.parse_help_subcommand(raw_args.remaining(&mut args_cursor))?; - unreachable!("`parse_help_subcommand` always errors"); - } else { - subcmd_name = Some(sc_name.to_owned()); - } - break; - } - } - - if arg_os.is_escape() { - if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if - self.cmd[opt].is_allow_hyphen_values_set()) - { - // ParseResult::MaybeHyphenValue, do nothing - } else { - debug!("Parser::get_matches_with: setting TrailingVals=true"); - trailing_values = true; - continue; - } - } else if let Some((long_arg, long_value)) = arg_os.to_long() { - let parse_result = self.parse_long_arg( - matcher, - long_arg, - long_value, - &parse_state, - &mut valid_arg_found, - trailing_values, - )?; - debug!( - "Parser::get_matches_with: After parse_long_arg {:?}", - parse_result - ); - match parse_result { - ParseResult::NoArg => { - unreachable!("`to_long` always has the flag specified") - } - ParseResult::ValuesDone => { - parse_state = ParseState::ValuesDone; - continue; - } - ParseResult::Opt(id) => { - parse_state = ParseState::Opt(id); - continue; - } - ParseResult::FlagSubCommand(name) => { - debug!( - "Parser::get_matches_with: FlagSubCommand found in long arg {:?}", - &name - ); - subcmd_name = Some(name); - break; - } - ParseResult::EqualsNotProvided { arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::no_equals( - self.cmd, - arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::NoMatchingArg { arg } => { - let _ = self.resolve_pending(matcher); - let remaining_args: Vec<_> = raw_args - .remaining(&mut args_cursor) - .map(|x| x.to_str().expect(INVALID_UTF8)) - .collect(); - return Err(self.did_you_mean_error(&arg, matcher, &remaining_args)); - } - ParseResult::UnneededAttachedValue { rest, used, arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::too_many_values( - self.cmd, - rest, - arg, - Usage::new(self.cmd).create_usage_no_title(&used), - )); - } - ParseResult::MaybeHyphenValue => { - // Maybe a hyphen value, do nothing. - } - ParseResult::AttachedValueNotConsumed => { - unreachable!() - } - } - } else if let Some(short_arg) = arg_os.to_short() { - // Arg looks like a short flag, and not a possible number - - // Try to parse short args like normal, if allow_hyphen_values or - // AllowNegativeNumbers is set, parse_short_arg will *not* throw - // an error, and instead return Ok(None) - let parse_result = self.parse_short_arg( - matcher, - short_arg, - &parse_state, - pos_counter, - &mut valid_arg_found, - trailing_values, - )?; - // If it's None, we then check if one of those two AppSettings was set - debug!( - "Parser::get_matches_with: After parse_short_arg {:?}", - parse_result - ); - match parse_result { - ParseResult::NoArg => { - // Is a single dash `-`, try positional. - } - ParseResult::ValuesDone => { - parse_state = ParseState::ValuesDone; - continue; - } - ParseResult::Opt(id) => { - parse_state = ParseState::Opt(id); - continue; - } - ParseResult::FlagSubCommand(name) => { - // If there are more short flags to be processed, we should keep the state, and later - // revisit the current group of short flags skipping the subcommand. - keep_state = self - .flag_subcmd_at - .map(|at| { - raw_args - .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1)); - // Since we are now saving the current state, the number of flags to skip during state recovery should - // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position. - self.flag_subcmd_skip = self.cur_idx.get() - at + 1; - }) - .is_some(); - - debug!( - "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}", - name, - keep_state, - self.flag_subcmd_skip - ); - - subcmd_name = Some(name); - break; - } - ParseResult::EqualsNotProvided { arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::no_equals( - self.cmd, - arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::NoMatchingArg { arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::unknown_argument( - self.cmd, - arg, - None, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::MaybeHyphenValue => { - // Maybe a hyphen value, do nothing. - } - ParseResult::UnneededAttachedValue { .. } - | ParseResult::AttachedValueNotConsumed => unreachable!(), - } - } - - if let ParseState::Opt(id) = &parse_state { - // Assume this is a value of a previous arg. - - // get the option so we can check the settings - let arg_values = matcher.pending_values_mut(id, None); - let arg = &self.cmd[id]; - let parse_result = self.split_arg_values( - arg, - arg_os.to_value_os(), - trailing_values, - arg_values, - ); - let parse_result = parse_result.unwrap_or_else(|| { - if matcher.needs_more_vals(arg) { - ParseResult::Opt(arg.id.clone()) - } else { - ParseResult::ValuesDone - } - }); - parse_state = match parse_result { - ParseResult::Opt(id) => ParseState::Opt(id), - ParseResult::ValuesDone => ParseState::ValuesDone, - _ => unreachable!(), - }; - // get the next value from the iterator - continue; - } - } - - if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) { - if arg.is_last_set() && !trailing_values { - let _ = self.resolve_pending(matcher); - return Err(ClapError::unknown_argument( - self.cmd, - arg_os.display().to_string(), - None, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - - if self.cmd.is_trailing_var_arg_set() && pos_counter == positional_count { - trailing_values = true; - } - - if matcher.pending_arg_id() != Some(&arg.id) || !arg.is_multiple_values_set() { - self.resolve_pending(matcher)?; - } - let arg_values = matcher.pending_values_mut(&arg.id, Some(Identifier::Index)); - let _parse_result = - self.split_arg_values(arg, arg_os.to_value_os(), trailing_values, arg_values); - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!( - "Parser::get_matches_with: Ignoring state {:?}; positionals do their own thing", - _parse_result - ); - } - } - - // Only increment the positional counter if it doesn't allow multiples - if !arg.is_multiple() { - pos_counter += 1; - parse_state = ParseState::ValuesDone; - } else { - parse_state = ParseState::Pos(arg.id.clone()); - } - valid_arg_found = true; - } else if let Some(external_parser) = - self.cmd.get_external_subcommand_value_parser().cloned() - { - // Get external subcommand name - let sc_name = match arg_os.to_value() { - Ok(s) => s.to_string(), - Err(_) => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::invalid_utf8( - self.cmd, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - }; - - // Collect the external subcommand args - let mut sc_m = ArgMatcher::new(self.cmd); - if cfg!(feature = "unstable-v4") || !raw_args.is_end(&args_cursor) { - sc_m.start_occurrence_of_external(self.cmd); - } - - for raw_val in raw_args.remaining(&mut args_cursor) { - let val = external_parser.parse_ref(self.cmd, None, raw_val)?; - let external_id = &Id::empty_hash(); - sc_m.add_val_to(external_id, val, raw_val.to_os_string()); - } - - matcher.subcommand(SubCommand { - id: Id::from(&*sc_name), - name: sc_name, - matches: sc_m.into_inner(), - }); - - self.resolve_pending(matcher)?; - #[cfg(feature = "env")] - self.add_env(matcher)?; - self.add_defaults(matcher)?; - return Validator::new(self.cmd).validate(parse_state, matcher); - } else { - // Start error processing - let _ = self.resolve_pending(matcher); - return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values)); - } - } - - if let Some(ref pos_sc_name) = subcmd_name { - let sc_name = self - .cmd - .find_subcommand(pos_sc_name) - .expect(INTERNAL_ERROR_MSG) - .get_name() - .to_owned(); - self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state)?; - } - - self.resolve_pending(matcher)?; - #[cfg(feature = "env")] - self.add_env(matcher)?; - self.add_defaults(matcher)?; - Validator::new(self.cmd).validate(parse_state, matcher) - } - - fn match_arg_error( - &self, - arg_os: &clap_lex::ParsedArg<'_>, - valid_arg_found: bool, - trailing_values: bool, - ) -> ClapError { - // If argument follows a `--` - if trailing_values { - // If the arg matches a subcommand name, or any of its aliases (if defined) - if self - .possible_subcommand(arg_os.to_value(), valid_arg_found) - .is_some() - { - return ClapError::unnecessary_double_dash( - self.cmd, - arg_os.display().to_string(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - } - let candidates = suggestions::did_you_mean( - &arg_os.display().to_string(), - self.cmd.all_subcommand_names(), - ); - // If the argument looks like a subcommand. - if !candidates.is_empty() { - let candidates: Vec<_> = candidates - .iter() - .map(|candidate| format!("'{}'", candidate)) - .collect(); - return ClapError::invalid_subcommand( - self.cmd, - arg_os.display().to_string(), - candidates.join(" or "), - self.cmd - .get_bin_name() - .unwrap_or_else(|| self.cmd.get_name()) - .to_owned(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - // If the argument must be a subcommand. - if !self.cmd.has_args() || self.cmd.is_infer_subcommands_set() && self.cmd.has_subcommands() - { - return ClapError::unrecognized_subcommand( - self.cmd, - arg_os.display().to_string(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - ClapError::unknown_argument( - self.cmd, - arg_os.display().to_string(), - None, - Usage::new(self.cmd).create_usage_with_title(&[]), - ) - } - - // Checks if the arg matches a subcommand name, or any of its aliases (if defined) - fn possible_subcommand( - &self, - arg: Result<&str, &RawOsStr>, - valid_arg_found: bool, - ) -> Option<&str> { - debug!("Parser::possible_subcommand: arg={:?}", arg); - let arg = arg.ok()?; - - if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) { - if self.cmd.is_infer_subcommands_set() { - // For subcommand `test`, we accepts it's prefix: `t`, `te`, - // `tes` and `test`. - let v = self - .cmd - .all_subcommand_names() - .filter(|s| s.starts_with(arg)) - .collect::>(); - - if v.len() == 1 { - return Some(v[0]); - } - - // If there is any ambiguity, fallback to non-infer subcommand - // search. - } - if let Some(sc) = self.cmd.find_subcommand(arg) { - return Some(sc.get_name()); - } - } - None - } - - // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined) - fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> { - debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg); - if self.cmd.is_infer_subcommands_set() { - let options = self - .cmd - .get_subcommands() - .fold(Vec::new(), |mut options, sc| { - if let Some(long) = sc.get_long_flag() { - if long.starts_with(arg) { - options.push(long); - } - options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg))) - } - options - }); - if options.len() == 1 { - return Some(options[0]); - } - - for sc in options { - if sc == arg { - return Some(sc); - } - } - } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) { - return Some(sc_name); - } - None - } - - fn parse_help_subcommand( - &self, - cmds: impl Iterator, - ) -> ClapResult { - debug!("Parser::parse_help_subcommand"); - - let mut cmd = self.cmd.clone(); - let sc = { - let mut sc = &mut cmd; - - for cmd in cmds { - sc = if let Some(sc_name) = - sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned()) - { - sc._build_subcommand(&sc_name).unwrap() - } else { - return Err(ClapError::unrecognized_subcommand( - sc, - cmd.to_string_lossy().into_owned(), - Usage::new(sc).create_usage_with_title(&[]), - )); - }; - } - - sc - }; - let parser = Parser::new(sc); - - Err(parser.help_err(true, Stream::Stdout)) - } - - fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool { - #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder - - debug!( - "Parser::is_new_arg: {:?}:{:?}", - next.to_value_os(), - current_positional.name - ); - - if self.cmd.is_allow_hyphen_values_set() - || self.cmd[¤t_positional.id].is_allow_hyphen_values_set() - || (self.cmd.is_allow_negative_numbers_set() && next.is_number()) - { - // If allow hyphen, this isn't a new arg. - debug!("Parser::is_new_arg: Allow hyphen"); - false - } else if next.is_long() { - // If this is a long flag, this is a new arg. - debug!("Parser::is_new_arg: -- found"); - true - } else if next.is_short() { - // If this is a short flag, this is a new arg. But a singe '-' by - // itself is a value and typically means "stdin" on unix systems. - debug!("Parser::is_new_arg: - found"); - true - } else { - // Nothing special, this is a value. - debug!("Parser::is_new_arg: value"); - false - } - } - - fn parse_subcommand( - &mut self, - sc_name: &str, - matcher: &mut ArgMatcher, - raw_args: &mut clap_lex::RawArgs, - args_cursor: clap_lex::ArgCursor, - keep_state: bool, - ) -> ClapResult<()> { - debug!("Parser::parse_subcommand"); - - let partial_parsing_enabled = self.cmd.is_ignore_errors_set(); - - if let Some(sc) = self.cmd._build_subcommand(sc_name) { - let mut sc_matcher = ArgMatcher::new(sc); - - debug!( - "Parser::parse_subcommand: About to parse sc={}", - sc.get_name() - ); - - { - let mut p = Parser::new(sc); - // HACK: maintain indexes between parsers - // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself - if keep_state { - p.cur_idx.set(self.cur_idx.get()); - p.flag_subcmd_at = self.flag_subcmd_at; - p.flag_subcmd_skip = self.flag_subcmd_skip; - } - if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) { - if partial_parsing_enabled { - debug!( - "Parser::parse_subcommand: ignored error in subcommand {}: {:?}", - sc_name, error - ); - } else { - return Err(error); - } - } - } - matcher.subcommand(SubCommand { - id: sc.get_id(), - name: sc.get_name().to_owned(), - matches: sc_matcher.into_inner(), - }); - } - Ok(()) - } - - fn parse_long_arg( - &mut self, - matcher: &mut ArgMatcher, - long_arg: Result<&str, &RawOsStr>, - long_value: Option<&RawOsStr>, - parse_state: &ParseState, - valid_arg_found: &mut bool, - trailing_values: bool, - ) -> ClapResult { - // maybe here lifetime should be 'a - debug!("Parser::parse_long_arg"); - - if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if - self.cmd[opt].is_allow_hyphen_values_set()) - { - return Ok(ParseResult::MaybeHyphenValue); - } - - debug!("Parser::parse_long_arg: Does it contain '='..."); - let long_arg = match long_arg { - Ok(long_arg) => long_arg, - Err(long_arg) => { - return Ok(ParseResult::NoMatchingArg { - arg: long_arg.to_str_lossy().into_owned(), - }); - } - }; - if long_arg.is_empty() { - debug_assert!(long_value.is_none(), "{:?}", long_value); - return Ok(ParseResult::NoArg); - } - - let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) { - debug!( - "Parser::parse_long_arg: Found valid arg or flag '{}'", - arg.to_string() - ); - Some((long_arg, arg)) - } else if self.cmd.is_infer_long_args_set() { - self.cmd.get_arguments().find_map(|a| { - if let Some(long) = a.long { - if long.starts_with(long_arg) { - return Some((long, a)); - } - } - a.aliases - .iter() - .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (*alias, a))) - }) - } else { - None - }; - - if let Some((_long_arg, arg)) = arg { - let ident = Identifier::Long; - *valid_arg_found = true; - if arg.is_takes_value_set() { - debug!( - "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'", - long_arg, &long_value - ); - let has_eq = long_value.is_some(); - self.parse_opt_value(ident, long_value, arg, matcher, trailing_values, has_eq) - } else if let Some(rest) = long_value { - let required = self.cmd.required_graph(); - debug!( - "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`", - long_arg, rest - ); - let used: Vec = matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) - }) - .filter(|&n| { - self.cmd - .find(n) - .map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id))) - }) - .cloned() - .collect(); - - Ok(ParseResult::UnneededAttachedValue { - rest: rest.to_str_lossy().into_owned(), - used, - arg: arg.to_string(), - }) - } else { - debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg); - self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher) - } - } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) { - Ok(ParseResult::FlagSubCommand(sc_name.to_string())) - } else if self.cmd.is_allow_hyphen_values_set() { - Ok(ParseResult::MaybeHyphenValue) - } else { - Ok(ParseResult::NoMatchingArg { - arg: long_arg.to_owned(), - }) - } - } - - fn parse_short_arg( - &mut self, - matcher: &mut ArgMatcher, - mut short_arg: clap_lex::ShortFlags<'_>, - parse_state: &ParseState, - // change this to possible pos_arg when removing the usage of &mut Parser. - pos_counter: usize, - valid_arg_found: &mut bool, - trailing_values: bool, - ) -> ClapResult { - debug!("Parser::parse_short_arg: short_arg={:?}", short_arg); - - #[allow(clippy::blocks_in_if_conditions)] - if self.cmd.is_allow_negative_numbers_set() && short_arg.is_number() { - debug!("Parser::parse_short_arg: negative number"); - return Ok(ParseResult::MaybeHyphenValue); - } else if self.cmd.is_allow_hyphen_values_set() - && short_arg - .clone() - .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default()) - { - debug!("Parser::parse_short_args: contains non-short flag"); - return Ok(ParseResult::MaybeHyphenValue); - } else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) - if self.cmd[opt].is_allow_hyphen_values_set()) - { - debug!("Parser::parse_short_args: prior arg accepts hyphenated values",); - return Ok(ParseResult::MaybeHyphenValue); - } else if self - .cmd - .get_keymap() - .get(&pos_counter) - .map_or(false, |arg| { - arg.is_allow_hyphen_values_set() && !arg.is_last_set() - }) - { - debug!( - "Parser::parse_short_args: positional at {} allows hyphens", - pos_counter - ); - return Ok(ParseResult::MaybeHyphenValue); - } - - let mut ret = ParseResult::NoArg; - - let skip = self.flag_subcmd_skip; - self.flag_subcmd_skip = 0; - let res = short_arg.advance_by(skip); - debug_assert_eq!( - res, - Ok(()), - "tracking of `flag_subcmd_skip` is off for `{:?}`", - short_arg - ); - while let Some(c) = short_arg.next_flag() { - let c = match c { - Ok(c) => c, - Err(rest) => { - return Ok(ParseResult::NoMatchingArg { - arg: format!("-{}", rest.to_str_lossy()), - }); - } - }; - debug!("Parser::parse_short_arg:iter:{}", c); - - // Check for matching short options, and return the name if there is no trailing - // concatenated value: -oval - // Option: -o - // Value: val - if let Some(arg) = self.cmd.get_keymap().get(&c) { - let ident = Identifier::Short; - debug!( - "Parser::parse_short_arg:iter:{}: Found valid opt or flag", - c - ); - *valid_arg_found = true; - if !arg.is_takes_value_set() { - ret = - self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher)?; - continue; - } - - // Check for trailing concatenated value - // - // Cloning the iterator, so we rollback if it isn't there. - let val = short_arg.clone().next_value_os().unwrap_or_default(); - debug!( - "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}", - c, val, val.as_raw_bytes(), short_arg - ); - let val = Some(val).filter(|v| !v.is_empty()); - - // Default to "we're expecting a value later". - // - // If attached value is not consumed, we may have more short - // flags to parse, continue. - // - // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't - // consume the `vf`, even if it's provided as value. - let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) { - (Some(val), true) - } else { - (val, false) - }; - match self.parse_opt_value(ident, val, arg, matcher, trailing_values, has_eq)? { - ParseResult::AttachedValueNotConsumed => continue, - x => return Ok(x), - } - } - - return if let Some(sc_name) = self.cmd.find_short_subcmd(c) { - debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name); - // Make sure indices get updated before reading `self.cur_idx` - self.resolve_pending(matcher)?; - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get()); - - let name = sc_name.to_string(); - // Get the index of the previously saved flag subcommand in the group of flags (if exists). - // If it is a new flag subcommand, then the formentioned index should be the current one - // (ie. `cur_idx`), and should be registered. - let cur_idx = self.cur_idx.get(); - self.flag_subcmd_at.get_or_insert(cur_idx); - let done_short_args = short_arg.is_empty(); - if done_short_args { - self.flag_subcmd_at = None; - } - Ok(ParseResult::FlagSubCommand(name)) - } else { - Ok(ParseResult::NoMatchingArg { - arg: format!("-{}", c), - }) - }; - } - Ok(ret) - } - - fn parse_opt_value( - &self, - ident: Identifier, - attached_value: Option<&RawOsStr>, - arg: &Arg<'help>, - matcher: &mut ArgMatcher, - trailing_values: bool, - has_eq: bool, - ) -> ClapResult { - debug!( - "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}", - arg.name, attached_value, has_eq - ); - debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings); - - debug!("Parser::parse_opt_value; Checking for val..."); - // require_equals is set, but no '=' is provided, try throwing error. - if arg.is_require_equals_set() && !has_eq { - if arg.min_vals == Some(0) { - debug!("Requires equals, but min_vals == 0"); - let mut arg_values = Vec::new(); - // We assume this case is valid: require equals, but min_vals == 0. - if !arg.default_missing_vals.is_empty() { - debug!("Parser::parse_opt_value: has default_missing_vals"); - for v in arg.default_missing_vals.iter() { - let trailing_values = false; // CLI should not be affecting default_missing_values - let _parse_result = self.split_arg_values( - arg, - &RawOsStr::new(v), - trailing_values, - &mut arg_values, - ); - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::parse_opt_value: Ignoring state {:?}; no values accepted after default_missing_values", _parse_result); - } - } - } - }; - let react_result = self.react( - Some(ident), - ValueSource::CommandLine, - arg, - arg_values, - matcher, - )?; - debug_assert_eq!(react_result, ParseResult::ValuesDone); - if attached_value.is_some() { - Ok(ParseResult::AttachedValueNotConsumed) - } else { - Ok(ParseResult::ValuesDone) - } - } else { - debug!("Requires equals but not provided. Error."); - Ok(ParseResult::EqualsNotProvided { - arg: arg.to_string(), - }) - } - } else if let Some(v) = attached_value { - let mut arg_values = Vec::new(); - let parse_result = self.split_arg_values(arg, v, trailing_values, &mut arg_values); - let react_result = self.react( - Some(ident), - ValueSource::CommandLine, - arg, - arg_values, - matcher, - )?; - debug_assert_eq!(react_result, ParseResult::ValuesDone); - let mut parse_result = parse_result.unwrap_or_else(|| { - if matcher.needs_more_vals(arg) { - ParseResult::Opt(arg.id.clone()) - } else { - ParseResult::ValuesDone - } - }); - if parse_result != ParseResult::ValuesDone { - debug!("Parser::parse_opt_value: Overriding state {:?}; no values accepted after attached", parse_result); - parse_result = ParseResult::ValuesDone; - } - Ok(parse_result) - } else { - debug!("Parser::parse_opt_value: More arg vals required..."); - self.resolve_pending(matcher)?; - matcher.pending_values_mut(&arg.id, Some(ident)); - Ok(ParseResult::Opt(arg.id.clone())) - } - } - - fn split_arg_values( - &self, - arg: &Arg<'help>, - val: &RawOsStr, - trailing_values: bool, - output: &mut Vec, - ) -> Option { - debug!("Parser::split_arg_values; arg={}, val={:?}", arg.name, val); - debug!( - "Parser::split_arg_values; trailing_values={:?}, DontDelimTrailingVals={:?}", - trailing_values, - self.cmd.is_dont_delimit_trailing_values_set() - ); - - let mut delim = arg.val_delim; - if trailing_values && self.cmd.is_dont_delimit_trailing_values_set() { - delim = None; - } - match delim { - Some(delim) if val.contains(delim) => { - let vals = val.split(delim).map(|x| x.to_os_str().into_owned()); - for raw_val in vals { - if Some(raw_val.as_os_str()) == arg.terminator.map(OsStr::new) { - return Some(ParseResult::ValuesDone); - } - output.push(raw_val); - } - // Delimited values are always considered the final value - Some(ParseResult::ValuesDone) - } - _ if Some(val) == arg.terminator.map(RawOsStr::from_str) => { - Some(ParseResult::ValuesDone) - } - _ => { - output.push(val.to_os_str().into_owned()); - if arg.is_require_value_delimiter_set() { - Some(ParseResult::ValuesDone) - } else { - None - } - } - } - } - - fn push_arg_values( - &self, - arg: &Arg<'help>, - raw_vals: Vec, - matcher: &mut ArgMatcher, - ) -> ClapResult<()> { - debug!("Parser::push_arg_values: {:?}", raw_vals); - - for raw_val in raw_vals { - // update the current index because each value is a distinct index to clap - self.cur_idx.set(self.cur_idx.get() + 1); - debug!( - "Parser::add_single_val_to_arg: cur_idx:={}", - self.cur_idx.get() - ); - let value_parser = arg.get_value_parser(); - let val = value_parser.parse_ref(self.cmd, Some(arg), &raw_val)?; - - // Increment or create the group "args" - for group in self.cmd.groups_for_arg(&arg.id) { - matcher.add_val_to(&group, val.clone(), raw_val.clone()); - } - - matcher.add_val_to(&arg.id, val, raw_val); - matcher.add_index_to(&arg.id, self.cur_idx.get()); - } - - Ok(()) - } - - fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { - let pending = match matcher.take_pending() { - Some(pending) => pending, - None => { - return Ok(()); - } - }; - - debug!("Parser::resolve_pending: id={:?}", pending.id); - let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG); - let _ = self.react( - pending.ident, - ValueSource::CommandLine, - arg, - pending.raw_vals, - matcher, - )?; - - Ok(()) - } - - fn react( - &self, - ident: Option, - source: ValueSource, - arg: &Arg<'help>, - raw_vals: Vec, - matcher: &mut ArgMatcher, - ) -> ClapResult { - self.resolve_pending(matcher)?; - - debug!( - "Parser::react action={:?}, identifier={:?}, source={:?}", - arg.get_action(), - ident, - source - ); - match arg.get_action() { - ArgAction::Set => { - if source == ValueSource::CommandLine - && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) - { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - matcher.remove(&arg.id); - self.start_custom_arg(matcher, arg, source); - self.push_arg_values(arg, raw_vals, matcher)?; - if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { - debug!( - "Parser::react not enough values passed in, leaving it to the validator to complain", - ); - } - Ok(ParseResult::ValuesDone) - } - ArgAction::Append => { - if source == ValueSource::CommandLine - && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) - { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - self.start_custom_arg(matcher, arg, source); - self.push_arg_values(arg, raw_vals, matcher)?; - if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { - debug!( - "Parser::react not enough values passed in, leaving it to the validator to complain", - ); - } - Ok(ParseResult::ValuesDone) - } - #[allow(deprecated)] - ArgAction::StoreValue => { - if ident == Some(Identifier::Index) - && arg.is_multiple_values_set() - && matcher.contains(&arg.id) - { - // HACK: Reuse existing occurrence - } else if source == ValueSource::CommandLine { - if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - self.start_occurrence_of_arg(matcher, arg); - } else { - self.start_custom_arg(matcher, arg, source); - } - self.push_arg_values(arg, raw_vals, matcher)?; - if ident == Some(Identifier::Index) && arg.is_multiple_values_set() { - // HACK: Maintain existing occurrence behavior - let matched = matcher.get_mut(&arg.id).unwrap(); - #[allow(deprecated)] - matched.set_occurrences(matched.num_vals() as u64); - } - if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { - debug!( - "Parser::react not enough values passed in, leaving it to the validator to complain", - ); - } - Ok(ParseResult::ValuesDone) - } - #[allow(deprecated)] - ArgAction::IncOccurrence => { - debug_assert_eq!(raw_vals, Vec::::new()); - if source == ValueSource::CommandLine { - if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - self.start_occurrence_of_arg(matcher, arg); - } else { - self.start_custom_arg(matcher, arg, source); - } - matcher.add_index_to(&arg.id, self.cur_idx.get()); - Ok(ParseResult::ValuesDone) - } - ArgAction::SetTrue => { - let raw_vals = match raw_vals.len() { - 0 => { - vec![OsString::from("true")] - } - 1 => raw_vals, - _ => { - debug!("Parser::react ignoring trailing values: {:?}", raw_vals); - let mut raw_vals = raw_vals; - raw_vals.resize(1, Default::default()); - raw_vals - } - }; - - matcher.remove(&arg.id); - self.start_custom_arg(matcher, arg, source); - self.push_arg_values(arg, raw_vals, matcher)?; - Ok(ParseResult::ValuesDone) - } - ArgAction::SetFalse => { - let raw_vals = match raw_vals.len() { - 0 => { - vec![OsString::from("false")] - } - 1 => raw_vals, - _ => { - debug!("Parser::react ignoring trailing values: {:?}", raw_vals); - let mut raw_vals = raw_vals; - raw_vals.resize(1, Default::default()); - raw_vals - } - }; - - matcher.remove(&arg.id); - self.start_custom_arg(matcher, arg, source); - self.push_arg_values(arg, raw_vals, matcher)?; - Ok(ParseResult::ValuesDone) - } - ArgAction::Count => { - let raw_vals = match raw_vals.len() { - 0 => { - let existing_value = *matcher - .get_one::(arg.get_id()) - .unwrap_or(&0); - let next_value = existing_value.saturating_add(1); - vec![OsString::from(next_value.to_string())] - } - 1 => raw_vals, - _ => { - debug!("Parser::react ignoring trailing values: {:?}", raw_vals); - let mut raw_vals = raw_vals; - raw_vals.resize(1, Default::default()); - raw_vals - } - }; - - matcher.remove(&arg.id); - self.start_custom_arg(matcher, arg, source); - self.push_arg_values(arg, raw_vals, matcher)?; - Ok(ParseResult::ValuesDone) - } - ArgAction::Help => { - debug_assert_eq!(raw_vals, Vec::::new()); - let use_long = match ident { - Some(Identifier::Long) => true, - Some(Identifier::Short) => false, - Some(Identifier::Index) => true, - None => true, - }; - debug!("Help: use_long={}", use_long); - Err(self.help_err(use_long, Stream::Stdout)) - } - ArgAction::Version => { - debug_assert_eq!(raw_vals, Vec::::new()); - let use_long = match ident { - Some(Identifier::Long) => true, - Some(Identifier::Short) => false, - Some(Identifier::Index) => true, - None => true, - }; - debug!("Version: use_long={}", use_long); - Err(self.version_err(use_long)) - } - } - } - - fn remove_overrides(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) { - debug!("Parser::remove_overrides: id={:?}", arg.id); - for override_id in &arg.overrides { - debug!("Parser::remove_overrides:iter:{:?}: removing", override_id); - matcher.remove(override_id); - } - - // Override anything that can override us - let mut transitive = Vec::new(); - for arg_id in matcher.arg_ids() { - if let Some(overrider) = self.cmd.find(arg_id) { - if overrider.overrides.contains(&arg.id) { - transitive.push(&overrider.id); - } - } - } - for overrider_id in transitive { - debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id); - matcher.remove(overrider_id); - } - } - - #[cfg(feature = "env")] - fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> { - debug!("Parser::add_env"); - use crate::util::str_to_bool; - - let trailing_values = false; // defaults are independent of the commandline - for arg in self.cmd.get_arguments() { - // Use env only if the arg was absent among command line args, - // early return if this is not the case. - if matcher.contains(&arg.id) { - debug!("Parser::add_env: Skipping existing arg `{}`", arg); - continue; - } - - debug!("Parser::add_env: Checking arg `{}`", arg); - if let Some((_, Some(ref val))) = arg.env { - let val = RawOsStr::new(val); - - if arg.is_takes_value_set() { - debug!( - "Parser::add_env: Found an opt with value={:?}, trailing={:?}", - val, trailing_values - ); - let mut arg_values = Vec::new(); - let _parse_result = - self.split_arg_values(arg, &val, trailing_values, &mut arg_values); - let _ = self.react(None, ValueSource::EnvVariable, arg, arg_values, matcher)?; - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result); - } - } - } else { - match arg.get_action() { - #[allow(deprecated)] - ArgAction::StoreValue => unreachable!("{:?} is not a flag", arg.get_id()), - #[allow(deprecated)] - ArgAction::IncOccurrence => { - debug!("Parser::add_env: Found a flag with value `{:?}`", val); - let predicate = str_to_bool(val.to_str_lossy()); - debug!("Parser::add_env: Found boolean literal `{:?}`", predicate); - if predicate.unwrap_or(true) { - let _ = self.react( - None, - ValueSource::EnvVariable, - arg, - vec![], - matcher, - )?; - } - } - ArgAction::Set - | ArgAction::Append - | ArgAction::SetTrue - | ArgAction::SetFalse - | ArgAction::Count => { - let mut arg_values = Vec::new(); - let _parse_result = - self.split_arg_values(arg, &val, trailing_values, &mut arg_values); - let _ = self.react( - None, - ValueSource::EnvVariable, - arg, - arg_values, - matcher, - )?; - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result); - } - } - } - // Early return on `Help` or `Version`. - ArgAction::Help | ArgAction::Version => { - let _ = - self.react(None, ValueSource::EnvVariable, arg, vec![], matcher)?; - } - } - } - } - } - - Ok(()) - } - - fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { - debug!("Parser::add_defaults"); - - for arg in self.cmd.get_arguments() { - debug!("Parser::add_defaults:iter:{}:", arg.name); - self.add_default_value(arg, matcher)?; - } - - Ok(()) - } - - fn add_default_value(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) -> ClapResult<()> { - let trailing_values = false; // defaults are independent of the commandline - - if !arg.default_missing_vals.is_empty() { - debug!( - "Parser::add_default_value:iter:{}: has default missing vals", - arg.name - ); - match matcher.get(&arg.id) { - Some(ma) if ma.all_val_groups_empty() => { - debug!( - "Parser::add_default_value:iter:{}: has no user defined vals", - arg.name - ); - // The flag occurred, we just want to add the val groups - let mut arg_values = Vec::new(); - for v in arg.default_missing_vals.iter() { - let _parse_result = self.split_arg_values( - arg, - &RawOsStr::new(v), - trailing_values, - &mut arg_values, - ); - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); - } - } - } - self.start_custom_arg(matcher, arg, ValueSource::CommandLine); - self.push_arg_values(arg, arg_values, matcher)?; - } - None => { - debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name); - // do nothing - } - _ => { - debug!( - "Parser::add_default_value:iter:{}: has user defined vals", - arg.name - ); - // do nothing - } - } - } else { - debug!( - "Parser::add_default_value:iter:{}: doesn't have default missing vals", - arg.name - ); - // do nothing - } - - if !arg.default_vals_ifs.is_empty() { - debug!("Parser::add_default_value: has conditional defaults"); - if !matcher.contains(&arg.id) { - for (id, val, default) in arg.default_vals_ifs.iter() { - let add = if let Some(a) = matcher.get(id) { - match val { - crate::builder::ArgPredicate::Equals(v) => { - a.raw_vals_flatten().any(|value| v == value) - } - crate::builder::ArgPredicate::IsPresent => true, - } - } else { - false - }; - - if add { - if let Some(default) = default { - let mut arg_values = Vec::new(); - let _parse_result = self.split_arg_values( - arg, - &RawOsStr::new(default), - trailing_values, - &mut arg_values, - ); - let _ = self.react( - None, - ValueSource::DefaultValue, - arg, - arg_values, - matcher, - )?; - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); - } - } - } - return Ok(()); - } - } - } - } else { - debug!("Parser::add_default_value: doesn't have conditional defaults"); - } - - if !arg.default_vals.is_empty() { - debug!( - "Parser::add_default_value:iter:{}: has default vals", - arg.name - ); - if matcher.contains(&arg.id) { - debug!("Parser::add_default_value:iter:{}: was used", arg.name); - // do nothing - } else { - debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name); - let mut arg_values = Vec::new(); - for v in arg.default_vals.iter() { - let _parse_result = self.split_arg_values( - arg, - &RawOsStr::new(v), - trailing_values, - &mut arg_values, - ); - if let Some(_parse_result) = _parse_result { - if _parse_result != ParseResult::ValuesDone { - debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); - } - } - } - let _ = self.react(None, ValueSource::DefaultValue, arg, arg_values, matcher)?; - } - } else { - debug!( - "Parser::add_default_value:iter:{}: doesn't have default vals", - arg.name - ); - - // do nothing - } - - Ok(()) - } - - fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>, source: ValueSource) { - if source == ValueSource::CommandLine { - // With each new occurrence, remove overrides from prior occurrences - self.remove_overrides(arg, matcher); - } - matcher.start_custom_arg(arg, source); - for group in self.cmd.groups_for_arg(&arg.id) { - matcher.start_custom_group(&group, source); - } - } - - /// Increase occurrence of specific argument and the grouped arg it's in. - fn start_occurrence_of_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) { - // With each new occurrence, remove overrides from prior occurrences - self.remove_overrides(arg, matcher); - - matcher.start_occurrence_of_arg(arg); - // Increment or create the group "args" - for group in self.cmd.groups_for_arg(&arg.id) { - matcher.start_occurrence_of_group(&group); - } - } -} - -// Error, Help, and Version Methods -impl<'help, 'cmd> Parser<'help, 'cmd> { - /// Is only used for the long flag(which is the only one needs fuzzy searching) - fn did_you_mean_error( - &mut self, - arg: &str, - matcher: &mut ArgMatcher, - remaining_args: &[&str], - ) -> ClapError { - debug!("Parser::did_you_mean_error: arg={}", arg); - // Didn't match a flag or option - let longs = self - .cmd - .get_keymap() - .keys() - .filter_map(|x| match x { - KeyType::Long(l) => Some(l.to_string_lossy().into_owned()), - _ => None, - }) - .collect::>(); - debug!("Parser::did_you_mean_error: longs={:?}", longs); - - let did_you_mean = suggestions::did_you_mean_flag( - arg, - remaining_args, - longs.iter().map(|x| &x[..]), - self.cmd.get_subcommands_mut(), - ); - - // Add the arg to the matches to build a proper usage string - if let Some((name, _)) = did_you_mean.as_ref() { - if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) { - self.start_occurrence_of_arg(matcher, arg); - } - } - - let required = self.cmd.required_graph(); - let used: Vec = matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) - }) - .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set())) - .cloned() - .collect(); - - ClapError::unknown_argument( - self.cmd, - format!("--{}", arg), - did_you_mean, - Usage::new(self.cmd) - .required(&required) - .create_usage_with_title(&*used), - ) - } - - fn help_err(&self, use_long: bool, stream: Stream) -> ClapError { - match self.cmd.write_help_err(use_long, stream) { - Ok(c) => ClapError::display_help(self.cmd, c), - Err(e) => e, - } - } - - fn version_err(&self, use_long: bool) -> ClapError { - debug!("Parser::version_err"); - - let msg = self.cmd._render_version(use_long); - let mut c = Colorizer::new(Stream::Stdout, self.cmd.color_help()); - c.none(msg); - ClapError::display_version(self.cmd, c) - } -} - -// Query Methods -impl<'help, 'cmd> Parser<'help, 'cmd> { - pub(crate) fn is_set(&self, s: AS) -> bool { - self.cmd.is_set(s) - } -} - -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum ParseState { - ValuesDone, - Opt(Id), - Pos(Id), -} - -/// Recoverable Parsing results. -#[derive(Debug, PartialEq, Clone)] -#[must_use] -enum ParseResult { - FlagSubCommand(String), - Opt(Id), - ValuesDone, - /// Value attached to the short flag is not consumed(e.g. 'u' for `-cu` is - /// not consumed). - AttachedValueNotConsumed, - /// This long flag doesn't need a value but is provided one. - UnneededAttachedValue { - rest: String, - used: Vec, - arg: String, - }, - /// This flag might be an hyphen Value. - MaybeHyphenValue, - /// Equals required but not provided. - EqualsNotProvided { - arg: String, - }, - /// Failed to match a Arg. - NoMatchingArg { - arg: String, - }, - /// No argument found e.g. parser is given `-` when parsing a flag. - NoArg, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct PendingArg { - pub(crate) id: Id, - pub(crate) ident: Option, - pub(crate) raw_vals: Vec, -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum Identifier { - Short, - Long, - Index, -} diff --git a/vendor/clap/src/parser/validator.rs b/vendor/clap/src/parser/validator.rs deleted file mode 100644 index ebf2b234d..000000000 --- a/vendor/clap/src/parser/validator.rs +++ /dev/null @@ -1,692 +0,0 @@ -// Internal -use crate::builder::{AppSettings, Arg, ArgPredicate, Command, PossibleValue}; -use crate::error::{Error, Result as ClapResult}; -use crate::output::fmt::Stream; -use crate::output::Usage; -use crate::parser::{ArgMatcher, MatchedArg, ParseState}; -use crate::util::ChildGraph; -use crate::util::Id; -use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; - -pub(crate) struct Validator<'help, 'cmd> { - cmd: &'cmd Command<'help>, - required: ChildGraph, -} - -impl<'help, 'cmd> Validator<'help, 'cmd> { - pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { - let required = cmd.required_graph(); - Validator { cmd, required } - } - - pub(crate) fn validate( - &mut self, - parse_state: ParseState, - matcher: &mut ArgMatcher, - ) -> ClapResult<()> { - debug!("Validator::validate"); - let mut conflicts = Conflicts::new(); - let has_subcmd = matcher.subcommand_name().is_some(); - - if let ParseState::Opt(a) = parse_state { - debug!("Validator::validate: needs_val_of={:?}", a); - - let o = &self.cmd[&a]; - let should_err = if let Some(v) = matcher.args.get(&o.id) { - v.all_val_groups_empty() && !(o.min_vals.is_some() && o.min_vals.unwrap() == 0) - } else { - true - }; - if should_err { - return Err(Error::empty_value( - self.cmd, - &get_possible_values(o) - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(PossibleValue::get_name) - .collect::>(), - o.to_string(), - )); - } - } - - if !has_subcmd && self.cmd.is_arg_required_else_help_set() { - let num_user_values = matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - .count(); - if num_user_values == 0 { - let message = self.cmd.write_help_err(false, Stream::Stderr)?; - return Err(Error::display_help_error(self.cmd, message)); - } - } - #[allow(deprecated)] - if !has_subcmd && self.cmd.is_subcommand_required_set() { - let bn = self - .cmd - .get_bin_name() - .unwrap_or_else(|| self.cmd.get_name()); - return Err(Error::missing_subcommand( - self.cmd, - bn.to_string(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } else if !has_subcmd && self.cmd.is_set(AppSettings::SubcommandRequiredElseHelp) { - debug!("Validator::new::get_matches_with: SubcommandRequiredElseHelp=true"); - let message = self.cmd.write_help_err(false, Stream::Stderr)?; - return Err(Error::display_help_error(self.cmd, message)); - } - - self.validate_conflicts(matcher, &mut conflicts)?; - if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) { - self.validate_required(matcher, &mut conflicts)?; - } - self.validate_matched_args(matcher)?; - - Ok(()) - } - - fn validate_arg_values(&self, arg: &Arg, ma: &MatchedArg) -> ClapResult<()> { - debug!("Validator::validate_arg_values: arg={:?}", arg.name); - for val in ma.raw_vals_flatten() { - if !arg.possible_vals.is_empty() { - debug!( - "Validator::validate_arg_values: possible_vals={:?}", - arg.possible_vals - ); - let val_str = val.to_string_lossy(); - let ok = arg - .possible_vals - .iter() - .any(|pv| pv.matches(&val_str, arg.is_ignore_case_set())); - if !ok { - return Err(Error::invalid_value( - self.cmd, - val_str.into_owned(), - &arg.possible_vals - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(PossibleValue::get_name) - .collect::>(), - arg.to_string(), - )); - } - } - { - #![allow(deprecated)] - if arg.is_forbid_empty_values_set() && val.is_empty() { - debug!("Validator::validate_arg_values: illegal empty val found"); - return Err(Error::empty_value( - self.cmd, - &get_possible_values(arg) - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(PossibleValue::get_name) - .collect::>(), - arg.to_string(), - )); - } - } - - if let Some(ref vtor) = arg.validator { - debug!("Validator::validate_arg_values: checking validator..."); - let mut vtor = vtor.lock().unwrap(); - if let Err(e) = vtor(&*val.to_string_lossy()) { - debug!("error"); - return Err(Error::value_validation( - arg.to_string(), - val.to_string_lossy().into_owned(), - e, - ) - .with_cmd(self.cmd)); - } else { - debug!("good"); - } - } - if let Some(ref vtor) = arg.validator_os { - debug!("Validator::validate_arg_values: checking validator_os..."); - let mut vtor = vtor.lock().unwrap(); - if let Err(e) = vtor(val) { - debug!("error"); - return Err(Error::value_validation( - arg.to_string(), - val.to_string_lossy().into(), - e, - ) - .with_cmd(self.cmd)); - } else { - debug!("good"); - } - } - } - Ok(()) - } - - fn validate_conflicts( - &mut self, - matcher: &ArgMatcher, - conflicts: &mut Conflicts, - ) -> ClapResult<()> { - debug!("Validator::validate_conflicts"); - - self.validate_exclusive(matcher)?; - - for arg_id in matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - .filter(|arg_id| self.cmd.find(arg_id).is_some()) - { - debug!("Validator::validate_conflicts::iter: id={:?}", arg_id); - let conflicts = conflicts.gather_conflicts(self.cmd, matcher, arg_id); - self.build_conflict_err(arg_id, &conflicts, matcher)?; - } - - Ok(()) - } - - fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> { - debug!("Validator::validate_exclusive"); - let args_count = matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) - }) - .count(); - if args_count <= 1 { - // Nothing present to conflict with - return Ok(()); - } - - matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) - }) - .filter_map(|name| { - debug!("Validator::validate_exclusive:iter:{:?}", name); - self.cmd - .find(name) - // Find `arg`s which are exclusive but also appear with other args. - .filter(|&arg| arg.is_exclusive_set() && args_count > 1) - }) - // Throw an error for the first conflict found. - .try_for_each(|arg| { - Err(Error::argument_conflict( - self.cmd, - arg.to_string(), - Vec::new(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )) - }) - } - - fn build_conflict_err( - &self, - name: &Id, - conflict_ids: &[Id], - matcher: &ArgMatcher, - ) -> ClapResult<()> { - if conflict_ids.is_empty() { - return Ok(()); - } - - debug!("Validator::build_conflict_err: name={:?}", name); - let mut seen = std::collections::HashSet::new(); - let conflicts = conflict_ids - .iter() - .flat_map(|c_id| { - if self.cmd.find_group(c_id).is_some() { - self.cmd.unroll_args_in_group(c_id) - } else { - vec![c_id.clone()] - } - }) - .filter_map(|c_id| { - seen.insert(c_id.clone()).then(|| { - let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG); - c_arg.to_string() - }) - }) - .collect(); - - let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG); - let usg = self.build_conflict_err_usage(matcher, conflict_ids); - Err(Error::argument_conflict( - self.cmd, - former_arg.to_string(), - conflicts, - usg, - )) - } - - fn build_conflict_err_usage(&self, matcher: &ArgMatcher, conflicting_keys: &[Id]) -> String { - let used_filtered: Vec = matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - .filter(|n| { - // Filter out the args we don't want to specify. - self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) - }) - .filter(|key| !conflicting_keys.contains(key)) - .cloned() - .collect(); - let required: Vec = used_filtered - .iter() - .filter_map(|key| self.cmd.find(key)) - .flat_map(|arg| arg.requires.iter().map(|item| &item.1)) - .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key)) - .chain(used_filtered.iter()) - .cloned() - .collect(); - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&required) - } - - fn gather_requires(&mut self, matcher: &ArgMatcher) { - debug!("Validator::gather_requires"); - for name in matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - { - debug!("Validator::gather_requires:iter:{:?}", name); - if let Some(arg) = self.cmd.find(name) { - let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option { - let required = matcher.check_explicit(&arg.id, *val); - required.then(|| req_arg.clone()) - }; - - for req in self.cmd.unroll_arg_requires(is_relevant, &arg.id) { - self.required.insert(req); - } - } else if let Some(g) = self.cmd.find_group(name) { - debug!("Validator::gather_requires:iter:{:?}:group", name); - for r in &g.requires { - self.required.insert(r.clone()); - } - } - } - } - - fn validate_matched_args(&self, matcher: &ArgMatcher) -> ClapResult<()> { - debug!("Validator::validate_matched_args"); - matcher.iter().try_for_each(|(name, ma)| { - debug!( - "Validator::validate_matched_args:iter:{:?}: vals={:#?}", - name, - ma.vals_flatten() - ); - if let Some(arg) = self.cmd.find(name) { - self.validate_arg_num_vals(arg, ma)?; - self.validate_arg_values(arg, ma)?; - self.validate_arg_num_occurs(arg, ma)?; - } - Ok(()) - }) - } - - fn validate_arg_num_occurs(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { - #![allow(deprecated)] - debug!( - "Validator::validate_arg_num_occurs: {:?}={}", - a.name, - ma.get_occurrences() - ); - // Occurrence of positional argument equals to number of values rather - // than number of grouped values. - if ma.get_occurrences() > 1 && !a.is_multiple_occurrences_set() && !a.is_positional() { - // Not the first time, and we don't allow multiples - return Err(Error::unexpected_multiple_usage( - self.cmd, - a.to_string(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - if let Some(max_occurs) = a.max_occurs { - debug!( - "Validator::validate_arg_num_occurs: max_occurs set...{}", - max_occurs - ); - let occurs = ma.get_occurrences() as usize; - if occurs > max_occurs { - return Err(Error::too_many_occurrences( - self.cmd, - a.to_string(), - max_occurs, - occurs, - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - } - - Ok(()) - } - - fn validate_arg_num_vals(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { - debug!("Validator::validate_arg_num_vals"); - if let Some(num) = a.num_vals { - let total_num = ma.num_vals(); - debug!("Validator::validate_arg_num_vals: num_vals set...{}", num); - #[allow(deprecated)] - let should_err = if a.is_multiple_occurrences_set() { - total_num % num != 0 - } else { - num != total_num - }; - if should_err { - debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); - return Err(Error::wrong_number_of_values( - self.cmd, - a.to_string(), - num, - #[allow(deprecated)] - if a.is_multiple_occurrences_set() { - total_num % num - } else { - total_num - }, - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - } - if let Some(num) = a.max_vals { - debug!("Validator::validate_arg_num_vals: max_vals set...{}", num); - if ma.num_vals() > num { - debug!("Validator::validate_arg_num_vals: Sending error TooManyValues"); - return Err(Error::too_many_values( - self.cmd, - ma.raw_vals_flatten() - .last() - .expect(INTERNAL_ERROR_MSG) - .to_str() - .expect(INVALID_UTF8) - .to_string(), - a.to_string(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - } - let min_vals_zero = if let Some(num) = a.min_vals { - debug!("Validator::validate_arg_num_vals: min_vals set: {}", num); - if ma.num_vals() < num && num != 0 { - debug!("Validator::validate_arg_num_vals: Sending error TooFewValues"); - return Err(Error::too_few_values( - self.cmd, - a.to_string(), - num, - ma.num_vals(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - num == 0 - } else { - false - }; - // Issue 665 (https://github.com/clap-rs/clap/issues/665) - // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) - if a.is_takes_value_set() && !min_vals_zero && ma.all_val_groups_empty() { - return Err(Error::empty_value( - self.cmd, - &get_possible_values(a) - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(PossibleValue::get_name) - .collect::>(), - a.to_string(), - )); - } - Ok(()) - } - - fn validate_required( - &mut self, - matcher: &ArgMatcher, - conflicts: &mut Conflicts, - ) -> ClapResult<()> { - debug!("Validator::validate_required: required={:?}", self.required); - self.gather_requires(matcher); - - let is_exclusive_present = matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - .any(|id| { - self.cmd - .find(id) - .map(|arg| arg.is_exclusive_set()) - .unwrap_or_default() - }); - debug!( - "Validator::validate_required: is_exclusive_present={}", - is_exclusive_present - ); - - for arg_or_group in self - .required - .iter() - .filter(|r| !matcher.check_explicit(r, ArgPredicate::IsPresent)) - { - debug!("Validator::validate_required:iter:aog={:?}", arg_or_group); - if let Some(arg) = self.cmd.find(arg_or_group) { - debug!("Validator::validate_required:iter: This is an arg"); - if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) { - return self.missing_required_error(matcher, vec![]); - } - } else if let Some(group) = self.cmd.find_group(arg_or_group) { - debug!("Validator::validate_required:iter: This is a group"); - if !self - .cmd - .unroll_args_in_group(&group.id) - .iter() - .any(|a| matcher.check_explicit(a, ArgPredicate::IsPresent)) - { - return self.missing_required_error(matcher, vec![]); - } - } - } - - // Validate the conditionally required args - for a in self.cmd.get_arguments() { - for (other, val) in &a.r_ifs { - if matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) - && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) - { - return self.missing_required_error(matcher, vec![a.id.clone()]); - } - } - - let match_all = a.r_ifs_all.iter().all(|(other, val)| { - matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) - }); - if match_all - && !a.r_ifs_all.is_empty() - && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) - { - return self.missing_required_error(matcher, vec![a.id.clone()]); - } - } - - self.validate_required_unless(matcher)?; - - Ok(()) - } - - fn is_missing_required_ok( - &self, - a: &Arg<'help>, - matcher: &ArgMatcher, - conflicts: &mut Conflicts, - ) -> bool { - debug!("Validator::is_missing_required_ok: {}", a.name); - let conflicts = conflicts.gather_conflicts(self.cmd, matcher, &a.id); - !conflicts.is_empty() - } - - fn validate_required_unless(&self, matcher: &ArgMatcher) -> ClapResult<()> { - debug!("Validator::validate_required_unless"); - let failed_args: Vec<_> = self - .cmd - .get_arguments() - .filter(|&a| { - (!a.r_unless.is_empty() || !a.r_unless_all.is_empty()) - && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) - && self.fails_arg_required_unless(a, matcher) - }) - .map(|a| a.id.clone()) - .collect(); - if failed_args.is_empty() { - Ok(()) - } else { - self.missing_required_error(matcher, failed_args) - } - } - - // Failing a required unless means, the arg's "unless" wasn't present, and neither were they - fn fails_arg_required_unless(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool { - debug!("Validator::fails_arg_required_unless: a={:?}", a.name); - let exists = |id| matcher.check_explicit(id, ArgPredicate::IsPresent); - - (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists)) - && !a.r_unless.iter().any(exists) - } - - // `incl`: an arg to include in the error even if not used - fn missing_required_error(&self, matcher: &ArgMatcher, incl: Vec) -> ClapResult<()> { - debug!("Validator::missing_required_error; incl={:?}", incl); - debug!( - "Validator::missing_required_error: reqs={:?}", - self.required - ); - - let usg = Usage::new(self.cmd).required(&self.required); - - let req_args = usg - .get_required_usage_from(&incl, Some(matcher), true) - .into_iter() - .collect::>(); - - debug!( - "Validator::missing_required_error: req_args={:#?}", - req_args - ); - - let used: Vec = matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - .filter(|n| { - // Filter out the args we don't want to specify. - self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) - }) - .cloned() - .chain(incl) - .collect(); - - Err(Error::missing_required_argument( - self.cmd, - req_args, - usg.create_usage_with_title(&used), - )) - } -} - -#[derive(Default, Clone, Debug)] -struct Conflicts { - potential: std::collections::HashMap>, -} - -impl Conflicts { - fn new() -> Self { - Self::default() - } - - fn gather_conflicts(&mut self, cmd: &Command, matcher: &ArgMatcher, arg_id: &Id) -> Vec { - debug!("Conflicts::gather_conflicts: arg={:?}", arg_id); - let mut conflicts = Vec::new(); - for other_arg_id in matcher - .arg_ids() - .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) - { - if arg_id == other_arg_id { - continue; - } - - if self - .gather_direct_conflicts(cmd, arg_id) - .contains(other_arg_id) - { - conflicts.push(other_arg_id.clone()); - } - if self - .gather_direct_conflicts(cmd, other_arg_id) - .contains(arg_id) - { - conflicts.push(other_arg_id.clone()); - } - } - debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts); - conflicts - } - - fn gather_direct_conflicts(&mut self, cmd: &Command, arg_id: &Id) -> &[Id] { - self.potential.entry(arg_id.clone()).or_insert_with(|| { - let conf = if let Some(arg) = cmd.find(arg_id) { - let mut conf = arg.blacklist.clone(); - for group_id in cmd.groups_for_arg(arg_id) { - let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG); - conf.extend(group.conflicts.iter().cloned()); - if !group.multiple { - for member_id in &group.args { - if member_id != arg_id { - conf.push(member_id.clone()); - } - } - } - } - - // Overrides are implicitly conflicts - conf.extend(arg.overrides.iter().cloned()); - - conf - } else if let Some(group) = cmd.find_group(arg_id) { - group.conflicts.clone() - } else { - debug_assert!(false, "id={:?} is unknown", arg_id); - Vec::new() - }; - debug!( - "Conflicts::gather_direct_conflicts id={:?}, conflicts={:?}", - arg_id, conf - ); - conf - }) - } -} - -fn get_possible_values<'help>(a: &Arg<'help>) -> Vec> { - #![allow(deprecated)] - if !a.is_takes_value_set() { - vec![] - } else if let Some(pvs) = a.get_possible_values() { - // Check old first in case the user explicitly set possible values and the derive inferred - // a `ValueParser` with some. - pvs.to_vec() - } else { - a.get_value_parser() - .possible_values() - .map(|pvs| pvs.collect()) - .unwrap_or_default() - } -} diff --git a/vendor/clap/src/util/color.rs b/vendor/clap/src/util/color.rs deleted file mode 100644 index 15c9901a0..000000000 --- a/vendor/clap/src/util/color.rs +++ /dev/null @@ -1,62 +0,0 @@ -/// Represents the color preferences for program output -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum ColorChoice { - /// Enables colored output only when the output is going to a terminal or TTY. - /// - /// **NOTE:** This is the default behavior of `clap`. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Auto) - /// .get_matches(); - /// ``` - Auto, - - /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Always) - /// .get_matches(); - /// ``` - Always, - - /// Disables colored output no matter if the output is going to a terminal/TTY, or not. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Never) - /// .get_matches(); - /// ``` - Never, -} - -impl Default for ColorChoice { - fn default() -> Self { - Self::Auto - } -} diff --git a/vendor/clap/src/util/fnv.rs b/vendor/clap/src/util/fnv.rs deleted file mode 100644 index 4602300a4..000000000 --- a/vendor/clap/src/util/fnv.rs +++ /dev/null @@ -1,46 +0,0 @@ -use std::{ - fmt::Display, - hash::{Hash, Hasher}, -}; - -const MAGIC_INIT: u64 = 0x811C_9DC5; - -// TODO: Docs -pub trait Key: Hash + Display { - fn key(&self) -> u64; -} - -impl Key for T -where - T: Hash + Display, -{ - fn key(&self) -> u64 { - let mut hasher = FnvHasher::new(); - self.hash(&mut hasher); - hasher.finish() - } -} - -pub(crate) struct FnvHasher(u64); - -impl FnvHasher { - pub(crate) fn new() -> Self { - FnvHasher(MAGIC_INIT) - } -} - -impl Hasher for FnvHasher { - fn finish(&self) -> u64 { - self.0 - } - fn write(&mut self, bytes: &[u8]) { - let FnvHasher(mut hash) = *self; - - for byte in bytes.iter() { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x0100_0000_01b3); - } - - *self = FnvHasher(hash); - } -} diff --git a/vendor/clap/src/util/graph.rs b/vendor/clap/src/util/graph.rs deleted file mode 100644 index d646400b0..000000000 --- a/vendor/clap/src/util/graph.rs +++ /dev/null @@ -1,49 +0,0 @@ -#[derive(Debug)] -struct Child { - id: T, - children: Vec, -} - -impl Child { - fn new(id: T) -> Self { - Child { - id, - children: vec![], - } - } -} - -#[derive(Debug)] -pub(crate) struct ChildGraph(Vec>); - -impl ChildGraph -where - T: Sized + PartialEq + Clone, -{ - pub(crate) fn with_capacity(s: usize) -> Self { - ChildGraph(Vec::with_capacity(s)) - } - - pub(crate) fn insert(&mut self, req: T) -> usize { - self.0.iter().position(|e| e.id == req).unwrap_or_else(|| { - let idx = self.0.len(); - self.0.push(Child::new(req)); - idx - }) - } - - pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize { - let c_idx = self.0.len(); - self.0.push(Child::new(child)); - self.0[parent].children.push(c_idx); - c_idx - } - - pub(crate) fn iter(&self) -> impl Iterator { - self.0.iter().map(|r| &r.id) - } - - pub(crate) fn contains(&self, req: &T) -> bool { - self.0.iter().any(|r| r.id == *req) - } -} diff --git a/vendor/clap/src/util/id.rs b/vendor/clap/src/util/id.rs deleted file mode 100644 index 63a7e003e..000000000 --- a/vendor/clap/src/util/id.rs +++ /dev/null @@ -1,92 +0,0 @@ -use crate::util::fnv::Key; - -use std::{ - fmt::{Debug, Formatter, Result}, - hash::{Hash, Hasher}, - ops::Deref, -}; - -#[derive(Clone, Eq, Default)] -#[cfg_attr(not(debug_assertions), repr(transparent))] -pub(crate) struct Id { - #[cfg(debug_assertions)] - name: String, - id: u64, -} - -macro_rules! precomputed_hashes { - ($($fn_name:ident, $const:expr, $name:expr;)*) => { - impl Id { - $( - pub(crate) fn $fn_name() -> Self { - Id { - #[cfg(debug_assertions)] - name: $name.into(), - id: $const, - } - } - )* - } - }; -} - -// precompute some common values -precomputed_hashes! { - empty_hash, 0x1C9D_3ADB_639F_298E, ""; - help_hash, 0x5963_6393_CFFB_FE5F, "help"; - version_hash, 0x30FF_0B7C_4D07_9478, "version"; -} - -impl Id { - pub(crate) fn from_ref(val: T) -> Self { - Id { - #[cfg(debug_assertions)] - name: val.to_string(), - id: val.key(), - } - } -} - -impl Debug for Id { - fn fmt(&self, f: &mut Formatter) -> Result { - #[cfg(debug_assertions)] - write!(f, "{}", self.name)?; - #[cfg(not(debug_assertions))] - write!(f, "[hash: {:X}]", self.id)?; - - Ok(()) - } -} - -impl Deref for Id { - type Target = u64; - - fn deref(&self) -> &Self::Target { - &self.id - } -} - -impl From for Id { - fn from(val: T) -> Self { - Id { - #[cfg(debug_assertions)] - name: val.to_string(), - id: val.key(), - } - } -} - -impl Hash for Id { - fn hash(&self, state: &mut H) - where - H: Hasher, - { - self.id.hash(state) - } -} - -impl PartialEq for Id { - fn eq(&self, other: &Id) -> bool { - self.id == other.id - } -} diff --git a/vendor/clap/src/util/mod.rs b/vendor/clap/src/util/mod.rs deleted file mode 100644 index 8adc8db17..000000000 --- a/vendor/clap/src/util/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -#![allow(clippy::single_component_path_imports)] - -mod fnv; -mod graph; -mod id; -mod str_to_bool; - -pub use self::fnv::Key; - -pub(crate) use self::str_to_bool::str_to_bool; -pub(crate) use self::str_to_bool::FALSE_LITERALS; -pub(crate) use self::str_to_bool::TRUE_LITERALS; -pub(crate) use self::{graph::ChildGraph, id::Id}; - -pub(crate) mod color; - -pub(crate) const SUCCESS_CODE: i32 = 0; -// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but -// instead 2 seems to be frequently used. -// Examples -// - GNU `ls` returns 2 -// - Python's `argparse` returns 2 -pub(crate) const USAGE_CODE: i32 = 2; - -pub(crate) fn safe_exit(code: i32) -> ! { - use std::io::Write; - - let _ = std::io::stdout().lock().flush(); - let _ = std::io::stderr().lock().flush(); - - std::process::exit(code) -} - -#[cfg(not(feature = "unicode"))] -pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool { - left.eq_ignore_ascii_case(right) -} - -#[cfg(feature = "unicode")] -pub(crate) use unicase::eq as eq_ignore_case; diff --git a/vendor/clap/src/util/str_to_bool.rs b/vendor/clap/src/util/str_to_bool.rs deleted file mode 100644 index 1fbdc7531..000000000 --- a/vendor/clap/src/util/str_to_bool.rs +++ /dev/null @@ -1,21 +0,0 @@ -/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`. -pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"]; - -/// False values are `n`, `no`, `f`, `false`, `off`, and `0`. -pub(crate) const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"]; - -/// Converts a string literal representation of truth to true or false. -/// -/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive). -/// -/// Any other value will be considered as `true`. -pub(crate) fn str_to_bool(val: impl AsRef) -> Option { - let pat: &str = &val.as_ref().to_lowercase(); - if TRUE_LITERALS.contains(&pat) { - Some(true) - } else if FALSE_LITERALS.contains(&pat) { - Some(false) - } else { - None - } -} diff --git a/vendor/clap_derive/.cargo-checksum.json b/vendor/clap_derive/.cargo-checksum.json index 8d3303f99..1dfa35a62 100644 --- a/vendor/clap_derive/.cargo-checksum.json +++ b/vendor/clap_derive/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"29d214d0c807739f6d147a1a472dfab5d929b4dd31623f670df28a713be107e8","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"d99fca4ba5976a41b150cd7f5c17100e0d275b9bf48b51a0d964115dc81e20b9","src/attrs.rs":"dd4288ac38aeb184bbffade71af48706034f10d311068af2917c0f96d813698a","src/derives/args.rs":"27a13d33f24f7f7668c82fa653978e909514bd39e808c7996fddb0d3a3c0e570","src/derives/into_app.rs":"02c36d403ad35e3d49de6042cacecf2a724561b5e3948b5aec4b45646e031877","src/derives/mod.rs":"ff7947fddee4b3d8365e29459a02458382e13df022aee822e09bce1ac255d3bb","src/derives/parser.rs":"9ca609e6e5bfb303e22b4ecb8aca9035571179920b0df91031e9f987559252e0","src/derives/subcommand.rs":"0513c48013c2bd9f450ffc7bfcbf84b3a3290e37ff571dd070798356c2b291ac","src/derives/value_enum.rs":"27b87ccb6829925f6ffa631109217bffd81b74f61519841678bd6d8c5cfcbe40","src/dummies.rs":"02f111bbd84b8f0525faeb9189c59cb2fd2df05ae6c7b014735c82feac5ff23f","src/lib.rs":"e4be47e8db06a6555a2a4cd1802d17c16a3b51ae0ec291b3ec75ef2b6517eb0e","src/parse.rs":"f0d720da5477755bdce02fcd248a57efe74b2fbbc5e07c5dc17d9bf78b017958","src/utils/doc_comments.rs":"386859b274fd1e298aeaeafd2b20764db0957cbb4e6c9e8bab52a506a0b8ecda","src/utils/mod.rs":"ee28526587d2d80d5dba162f28191f44f6a0c296d0e52225eb74b90534d49b25","src/utils/spanned.rs":"e93600124c54985533f74fe23f096f4ada94b310eff97a16f0ce40fb0f690a3b","src/utils/ty.rs":"0a9b8c5dabfa28388b60423f4b6075a275b347258ac35301997cb0d7f763607f"},"package":"c11d40217d16aee8508cc8e5fde8b4ff24639758608e5374e731b53f85749fb9"} \ No newline at end of file +{"files":{"Cargo.toml":"eaf10a4c685b527f604ea9f84fbe7095e15fe4424225c57481d0555a89dfb054","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"0d687e1f07b58fe68bda74668ff6326125e5e5efa184cce755cd84ac535b7058","README.md":"4ec07b9c59a2ddcedcdc9d21d51c147b18157794b03ff2ea5ae57f2b5236943d","src/attrs.rs":"1c95a75fd377d19587f429d3f51544ac0ca96f868cce4ffe12d1163f7465fa73","src/derives/args.rs":"27a13d33f24f7f7668c82fa653978e909514bd39e808c7996fddb0d3a3c0e570","src/derives/into_app.rs":"02c36d403ad35e3d49de6042cacecf2a724561b5e3948b5aec4b45646e031877","src/derives/mod.rs":"ff7947fddee4b3d8365e29459a02458382e13df022aee822e09bce1ac255d3bb","src/derives/parser.rs":"9ca609e6e5bfb303e22b4ecb8aca9035571179920b0df91031e9f987559252e0","src/derives/subcommand.rs":"0513c48013c2bd9f450ffc7bfcbf84b3a3290e37ff571dd070798356c2b291ac","src/derives/value_enum.rs":"4d0958d3a767c82f2366d8fda20367c5aa033af616d09ef581e8abdb2e029a70","src/dummies.rs":"02f111bbd84b8f0525faeb9189c59cb2fd2df05ae6c7b014735c82feac5ff23f","src/lib.rs":"e4be47e8db06a6555a2a4cd1802d17c16a3b51ae0ec291b3ec75ef2b6517eb0e","src/parse.rs":"ceaac282cabccfac5bcf56ce02095c9acbf00dbfdd3c3009fa58e87bdde46218","src/utils/doc_comments.rs":"386859b274fd1e298aeaeafd2b20764db0957cbb4e6c9e8bab52a506a0b8ecda","src/utils/mod.rs":"ee28526587d2d80d5dba162f28191f44f6a0c296d0e52225eb74b90534d49b25","src/utils/spanned.rs":"e93600124c54985533f74fe23f096f4ada94b310eff97a16f0ce40fb0f690a3b","src/utils/ty.rs":"0a9b8c5dabfa28388b60423f4b6075a275b347258ac35301997cb0d7f763607f"},"package":"ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65"} \ No newline at end of file diff --git a/vendor/clap_derive/Cargo.toml b/vendor/clap_derive/Cargo.toml index 49e3fd963..f74476e68 100644 --- a/vendor/clap_derive/Cargo.toml +++ b/vendor/clap_derive/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2021" -rust-version = "1.56.0" +rust-version = "1.56.1" name = "clap_derive" -version = "3.2.5" +version = "3.2.18" include = [ "build.rs", "src/**/*", @@ -24,7 +24,6 @@ include = [ "examples/**/*", ] description = "Parse command line argument by defining a struct, derive crate." -documentation = "https://docs.rs/clap_derive" readme = "README.md" keywords = [ "clap", diff --git a/vendor/clap_derive/LICENSE-MIT b/vendor/clap_derive/LICENSE-MIT index 5acedf041..7b05b8453 100644 --- a/vendor/clap_derive/LICENSE-MIT +++ b/vendor/clap_derive/LICENSE-MIT @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015-2016 Kevin B. Knapp +Copyright (c) 2015-2022 Kevin B. Knapp and Clap Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/clap_derive/README.md b/vendor/clap_derive/README.md index 1acadb355..17f649eda 100644 --- a/vendor/clap_derive/README.md +++ b/vendor/clap_derive/README.md @@ -3,8 +3,8 @@ Macro implementation for clap's derives. [docs.rs](https://docs.rs/clap) -- [Derive Tutorial](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_derive/README.md) -- [Derive Reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) +- [Derive Tutorial](https://github.com/clap-rs/clap/blob/v3.2.18/examples/tutorial_derive/README.md) +- [Derive Reference](https://github.com/clap-rs/clap/blob/v3.2.18/examples/derive_ref/README.md) ## License diff --git a/vendor/clap_derive/src/attrs.rs b/vendor/clap_derive/src/attrs.rs index 3c685fbe8..2c5b47d95 100644 --- a/vendor/clap_derive/src/attrs.rs +++ b/vendor/clap_derive/src/attrs.rs @@ -450,7 +450,7 @@ impl Attrs { } fn push_method(&mut self, name: Ident, arg: impl ToTokens) { - if name == "name" { + if name == "name" || name == "id" { self.name = Name::Assigned(quote!(#arg)); } else if name == "value_parser" { self.value_parser = Some(ValueParser::Explicit(Method::new(name, quote!(#arg)))); @@ -552,7 +552,7 @@ impl Attrs { }) } else { quote_spanned!(ident.span()=> { - static DEFAULT_VALUE: clap::once_cell::sync::Lazy = clap::once_cell::sync::Lazy::new(|| { + static DEFAULT_VALUE: clap::__macro_refs::once_cell::sync::Lazy = clap::__macro_refs::once_cell::sync::Lazy::new(|| { let val: #ty = #val; ::std::string::ToString::to_string(&val) }); @@ -564,6 +564,81 @@ impl Attrs { self.methods.push(Method::new(raw_ident, val)); } + DefaultValuesT(ident, expr) => { + let ty = if let Some(ty) = self.ty.as_ref() { + ty + } else { + abort!( + ident, + "#[clap(default_values_t)] (without an argument) can be used \ + only on field level"; + + note = "see \ + https://github.com/clap-rs/clap/blob/master/examples/derive_ref/README.md#magic-attributes") + }; + + let container_type = Ty::from_syn_ty(ty); + if *container_type != Ty::Vec { + abort!( + ident, + "#[clap(default_values_t)] can be used only on Vec types"; + + note = "see \ + https://github.com/clap-rs/clap/blob/master/examples/derive_ref/README.md#magic-attributes") + } + let inner_type = inner_type(ty); + + // Use `Borrow<#inner_type>` so we accept `&Vec<#inner_type>` and + // `Vec<#inner_type>`. + let val = if parsed.iter().any(|a| matches!(a, ValueEnum(_))) { + quote_spanned!(ident.span()=> { + { + fn iter_to_vals(iterable: impl IntoIterator) -> Vec<&'static str> + where + T: ::std::borrow::Borrow<#inner_type> + { + iterable + .into_iter() + .map(|val| { + clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name() + }) + .collect() + + } + + static DEFAULT_VALUES: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + iter_to_vals(#expr) + }); + &*DEFAULT_VALUES.as_slice() + } + }) + } else { + quote_spanned!(ident.span()=> { + { + fn iter_to_vals(iterable: impl IntoIterator) -> Vec + where + T: ::std::borrow::Borrow<#inner_type> + { + iterable.into_iter().map(|val| val.borrow().to_string()).collect() + + } + + static DEFAULT_STRINGS: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + iter_to_vals(#expr) + }); + + static DEFAULT_VALUES: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + DEFAULT_STRINGS.iter().map(::std::string::String::as_str).collect() + }); + &*DEFAULT_VALUES.as_slice() + } + }) + }; + + self.methods + .push(Method::new(Ident::new("default_values", ident.span()), val)); + } + DefaultValueOsT(ident, expr) => { let ty = if let Some(ty) = self.ty.as_ref() { ty @@ -592,7 +667,7 @@ impl Attrs { }) } else { quote_spanned!(ident.span()=> { - static DEFAULT_VALUE: clap::once_cell::sync::Lazy<::std::ffi::OsString> = clap::once_cell::sync::Lazy::new(|| { + static DEFAULT_VALUE: clap::__macro_refs::once_cell::sync::Lazy<::std::ffi::OsString> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { let val: #ty = #val; ::std::ffi::OsString::from(val) }); @@ -604,6 +679,84 @@ impl Attrs { self.methods.push(Method::new(raw_ident, val)); } + DefaultValuesOsT(ident, expr) => { + let ty = if let Some(ty) = self.ty.as_ref() { + ty + } else { + abort!( + ident, + "#[clap(default_values_os_t)] (without an argument) can be used \ + only on field level"; + + note = "see \ + https://github.com/clap-rs/clap/blob/master/examples/derive_ref/README.md#magic-attributes") + }; + + let container_type = Ty::from_syn_ty(ty); + if *container_type != Ty::Vec { + abort!( + ident, + "#[clap(default_values_os_t)] can be used only on Vec types"; + + note = "see \ + https://github.com/clap-rs/clap/blob/master/examples/derive_ref/README.md#magic-attributes") + } + let inner_type = inner_type(ty); + + // Use `Borrow<#inner_type>` so we accept `&Vec<#inner_type>` and + // `Vec<#inner_type>`. + let val = if parsed.iter().any(|a| matches!(a, ValueEnum(_))) { + quote_spanned!(ident.span()=> { + { + fn iter_to_vals(iterable: impl IntoIterator) -> Vec<&'static ::std::ffi::OsStr> + where + T: ::std::borrow::Borrow<#inner_type> + { + iterable + .into_iter() + .map(|val| { + clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name() + }) + .map(::std::ffi::OsStr::new) + .collect() + + } + + static DEFAULT_VALUES: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + iter_to_vals(#expr) + }); + &*DEFAULT_VALUES.as_slice() + } + }) + } else { + quote_spanned!(ident.span()=> { + { + fn iter_to_vals(iterable: impl IntoIterator) -> Vec<::std::ffi::OsString> + where + T: ::std::borrow::Borrow<#inner_type> + { + iterable.into_iter().map(|val| val.borrow().into()).collect() + + } + + static DEFAULT_OS_STRINGS: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + iter_to_vals(#expr) + }); + + static DEFAULT_VALUES: clap::__macro_refs::once_cell::sync::Lazy> = clap::__macro_refs::once_cell::sync::Lazy::new(|| { + DEFAULT_OS_STRINGS.iter().map(::std::ffi::OsString::as_os_str).collect() + }); + &*DEFAULT_VALUES.as_slice() + } + }) + }; + + self.methods.push(Method::new( + Ident::new("default_values_os", ident.span()), + val, + )); + } + NextDisplayOrder(ident, expr) => { self.next_display_order = Some(Method::new(ident, quote!(#expr))); } diff --git a/vendor/clap_derive/src/derives/value_enum.rs b/vendor/clap_derive/src/derives/value_enum.rs index b18b665c4..06d514f0e 100644 --- a/vendor/clap_derive/src/derives/value_enum.rs +++ b/vendor/clap_derive/src/derives/value_enum.rs @@ -84,7 +84,7 @@ fn lits( None } else { if !matches!(variant.fields, Fields::Unit) { - abort!(variant.span(), "`#[derive(ValueEnum)]` only supports non-unit variants, unless they are skipped"); + abort!(variant.span(), "`#[derive(ValueEnum)]` only supports unit variants. Non-unit variants must be skipped"); } let fields = attrs.field_methods(false); let name = attrs.cased_name(); diff --git a/vendor/clap_derive/src/parse.rs b/vendor/clap_derive/src/parse.rs index 253736cfd..7d7e19cdc 100644 --- a/vendor/clap_derive/src/parse.rs +++ b/vendor/clap_derive/src/parse.rs @@ -53,7 +53,9 @@ pub enum ClapAttr { // ident = arbitrary_expr NameExpr(Ident, Expr), DefaultValueT(Ident, Option), + DefaultValuesT(Ident, Expr), DefaultValueOsT(Ident, Option), + DefaultValuesOsT(Ident, Expr), NextDisplayOrder(Ident, Expr), NextHelpHeading(Ident, Expr), HelpHeading(Ident, Expr), @@ -122,7 +124,9 @@ impl Parse for ClapAttr { Ok(expr) => match &*name_str { "skip" => Ok(Skip(name, Some(expr))), "default_value_t" => Ok(DefaultValueT(name, Some(expr))), + "default_values_t" => Ok(DefaultValuesT(name, expr)), "default_value_os_t" => Ok(DefaultValueOsT(name, Some(expr))), + "default_values_os_t" => Ok(DefaultValuesOsT(name, expr)), "next_display_order" => Ok(NextDisplayOrder(name, expr)), "next_help_heading" => Ok(NextHelpHeading(name, expr)), "help_heading" => Ok(HelpHeading(name, expr)), diff --git a/vendor/clap_lex-0.2.2/.cargo-checksum.json b/vendor/clap_lex-0.2.2/.cargo-checksum.json new file mode 100644 index 000000000..d1fc5c2fe --- /dev/null +++ b/vendor/clap_lex-0.2.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"8141410d44a74e1783beeec03f35ac2b89ead0f2d0e0fb6ddc71dcc064749a89","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"b68af9a7bf1ad292ee5cfccb123dc639c5c1ad9b57645e533209965c394bf05d","src/lib.rs":"d78b54dc0fe6bd1a3a0ae764d31616a83b1a3b596ec75ad8f182c119c8c30b74"},"package":"5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613"} \ No newline at end of file diff --git a/vendor/clap_lex-0.2.2/Cargo.toml b/vendor/clap_lex-0.2.2/Cargo.toml new file mode 100644 index 000000000..b089dcde8 --- /dev/null +++ b/vendor/clap_lex-0.2.2/Cargo.toml @@ -0,0 +1,89 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.56.0" +name = "clap_lex" +version = "0.2.2" +include = [ + "build.rs", + "src/**/*", + "Cargo.toml", + "LICENSE*", + "README.md", + "benches/**/*", + "examples/**/*", +] +description = "Minimal, flexible command line parser" +documentation = "https://docs.rs/clap_lex" +readme = "README.md" +keywords = [ + "argument", + "cli", + "arg", + "parser", + "parse", +] +categories = ["command-line-interface"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/clap-rs/clap/tree/master/clap_lex" +resolver = "2" + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "Unreleased" +replace = "{{version}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = '\.\.\.HEAD' +replace = "...{{tag_name}}" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "ReleaseDate" +replace = "{{date}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "" +replace = """ + +## [Unreleased] - ReleaseDate +""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "" +replace = """ + +[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "README.md" +search = "github.com/clap-rs/clap/blob/[^/]+/" +replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" +exactly = 4 +prerelease = true + +[lib] +bench = false + +[dependencies.os_str_bytes] +version = "6.0" +features = ["raw_os_str"] +default-features = false diff --git a/vendor/clap_lex-0.2.2/LICENSE-APACHE b/vendor/clap_lex-0.2.2/LICENSE-APACHE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/clap_lex-0.2.2/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/clap_lex-0.2.2/LICENSE-MIT b/vendor/clap_lex-0.2.2/LICENSE-MIT new file mode 100644 index 000000000..5acedf041 --- /dev/null +++ b/vendor/clap_lex-0.2.2/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Kevin B. Knapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/clap_lex-0.2.2/README.md b/vendor/clap_lex-0.2.2/README.md new file mode 100644 index 000000000..0c21bc819 --- /dev/null +++ b/vendor/clap_lex-0.2.2/README.md @@ -0,0 +1,19 @@ + +# clap_lex + +> **Minimal, flexible command line parser** + +[![Crates.io](https://img.shields.io/crates/v/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) +[![Crates.io](https://img.shields.io/crates/d/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-MIT) + +Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). + +1. [About](#about) +2. [API Reference](https://docs.rs/clap_lex) +3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) +4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/clap_lex/CONTRIBUTING.md) +5. [Sponsors](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/README.md#sponsors) + +## About diff --git a/vendor/clap_lex-0.2.2/src/lib.rs b/vendor/clap_lex-0.2.2/src/lib.rs new file mode 100644 index 000000000..f205c3de0 --- /dev/null +++ b/vendor/clap_lex-0.2.2/src/lib.rs @@ -0,0 +1,484 @@ +//! Minimal, flexible command-line parser +//! +//! As opposed to a declarative parser, this processes arguments as a stream of tokens. As lexing +//! a command-line is not context-free, we rely on the caller to decide how to interpret the +//! arguments. +//! +//! # Examples +//! +//! ```rust +//! # use std::path::PathBuf; +//! # type BoxedError = Box; +//! #[derive(Debug)] +//! struct Args { +//! paths: Vec, +//! color: Color, +//! verbosity: usize, +//! } +//! +//! #[derive(Debug)] +//! enum Color { +//! Always, +//! Auto, +//! Never, +//! } +//! +//! impl Color { +//! fn parse(s: Option<&clap_lex::RawOsStr>) -> Result { +//! let s = s.map(|s| s.to_str().ok_or(s)); +//! match s { +//! Some(Ok("always")) | Some(Ok("")) | None => { +//! Ok(Color::Always) +//! } +//! Some(Ok("auto")) => { +//! Ok(Color::Auto) +//! } +//! Some(Ok("never")) => { +//! Ok(Color::Never) +//! } +//! Some(invalid) => { +//! Err(format!("Invalid value for `--color`, {:?}", invalid).into()) +//! } +//! } +//! } +//! } +//! +//! fn parse_args( +//! raw: impl IntoIterator> +//! ) -> Result { +//! let mut args = Args { +//! paths: Vec::new(), +//! color: Color::Auto, +//! verbosity: 0, +//! }; +//! +//! let raw = clap_lex::RawArgs::new(raw); +//! let mut cursor = raw.cursor(); +//! raw.next(&mut cursor); // Skip the bin +//! while let Some(arg) = raw.next(&mut cursor) { +//! if arg.is_escape() { +//! args.paths.extend(raw.remaining(&mut cursor).map(PathBuf::from)); +//! } else if arg.is_stdio() { +//! args.paths.push(PathBuf::from("-")); +//! } else if let Some((long, value)) = arg.to_long() { +//! match long { +//! Ok("verbose") => { +//! if let Some(value) = value { +//! return Err(format!("`--verbose` does not take a value, got `{:?}`", value).into()); +//! } +//! args.verbosity += 1; +//! } +//! Ok("color") => { +//! args.color = Color::parse(value)?; +//! } +//! _ => { +//! return Err( +//! format!("Unexpected flag: --{}", arg.display()).into() +//! ); +//! } +//! } +//! } else if let Some(mut shorts) = arg.to_short() { +//! while let Some(short) = shorts.next_flag() { +//! match short { +//! Ok('v') => { +//! args.verbosity += 1; +//! } +//! Ok('c') => { +//! let value = shorts.next_value_os(); +//! args.color = Color::parse(value)?; +//! } +//! Ok(c) => { +//! return Err(format!("Unexpected flag: -{}", c).into()); +//! } +//! Err(e) => { +//! return Err(format!("Unexpected flag: -{}", e.to_str_lossy()).into()); +//! } +//! } +//! } +//! } else { +//! args.paths.push(PathBuf::from(arg.to_value_os().to_os_str().into_owned())); +//! } +//! } +//! +//! Ok(args) +//! } +//! +//! let args = parse_args(["bin", "--hello", "world"]); +//! println!("{:?}", args); +//! ``` + +use std::ffi::OsStr; +use std::ffi::OsString; + +pub use std::io::SeekFrom; + +pub use os_str_bytes::RawOsStr; +pub use os_str_bytes::RawOsString; + +/// Command-line arguments +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct RawArgs { + items: Vec, +} + +impl RawArgs { + //// Create an argument list to parse + /// + /// **NOTE:** The argument returned will be the current binary. + /// + /// # Example + /// + /// ```rust,no_run + /// # use std::path::PathBuf; + /// let raw = clap_lex::RawArgs::from_args(); + /// let mut cursor = raw.cursor(); + /// let _bin = raw.next_os(&mut cursor); + /// + /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); + /// println!("{:?}", paths); + /// ``` + pub fn from_args() -> Self { + Self::new(std::env::args_os()) + } + + //// Create an argument list to parse + /// + /// # Example + /// + /// ```rust,no_run + /// # use std::path::PathBuf; + /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); + /// let mut cursor = raw.cursor(); + /// let _bin = raw.next_os(&mut cursor); + /// + /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); + /// println!("{:?}", paths); + /// ``` + pub fn new(iter: impl IntoIterator>) -> Self { + let iter = iter.into_iter(); + Self::from(iter) + } + + /// Create a cursor for walking the arguments + /// + /// # Example + /// + /// ```rust,no_run + /// # use std::path::PathBuf; + /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); + /// let mut cursor = raw.cursor(); + /// let _bin = raw.next_os(&mut cursor); + /// + /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); + /// println!("{:?}", paths); + /// ``` + pub fn cursor(&self) -> ArgCursor { + ArgCursor::new() + } + + /// Advance the cursor, returning the next [`ParsedArg`] + pub fn next(&self, cursor: &mut ArgCursor) -> Option> { + self.next_os(cursor).map(ParsedArg::new) + } + + /// Advance the cursor, returning a raw argument value. + pub fn next_os(&self, cursor: &mut ArgCursor) -> Option<&OsStr> { + let next = self.items.get(cursor.cursor).map(|s| s.as_os_str()); + cursor.cursor = cursor.cursor.saturating_add(1); + next + } + + /// Return the next [`ParsedArg`] + pub fn peek(&self, cursor: &ArgCursor) -> Option> { + self.peek_os(cursor).map(ParsedArg::new) + } + + /// Return a raw argument value. + pub fn peek_os(&self, cursor: &ArgCursor) -> Option<&OsStr> { + self.items.get(cursor.cursor).map(|s| s.as_os_str()) + } + + /// Return all remaining raw arguments, advancing the cursor to the end + /// + /// # Example + /// + /// ```rust,no_run + /// # use std::path::PathBuf; + /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); + /// let mut cursor = raw.cursor(); + /// let _bin = raw.next_os(&mut cursor); + /// + /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); + /// println!("{:?}", paths); + /// ``` + pub fn remaining(&self, cursor: &mut ArgCursor) -> impl Iterator { + let remaining = self.items[cursor.cursor..].iter().map(|s| s.as_os_str()); + cursor.cursor = self.items.len(); + remaining + } + + /// Adjust the cursor's position + pub fn seek(&self, cursor: &mut ArgCursor, pos: SeekFrom) { + let pos = match pos { + SeekFrom::Start(pos) => pos, + SeekFrom::End(pos) => (self.items.len() as i64).saturating_add(pos).max(0) as u64, + SeekFrom::Current(pos) => (cursor.cursor as i64).saturating_add(pos).max(0) as u64, + }; + let pos = (pos as usize).min(self.items.len()); + cursor.cursor = pos; + } + + /// Inject arguments before the [`RawArgs::next`] + pub fn insert(&mut self, cursor: &ArgCursor, insert_items: &[&str]) { + self.items.splice( + cursor.cursor..cursor.cursor, + insert_items.iter().map(OsString::from), + ); + } + + /// Any remaining args? + pub fn is_end(&self, cursor: &ArgCursor) -> bool { + self.peek_os(cursor).is_none() + } +} + +impl From for RawArgs +where + I: Iterator, + T: Into, +{ + fn from(val: I) -> Self { + Self { + items: val.map(|x| x.into()).collect(), + } + } +} + +/// Position within [`RawArgs`] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct ArgCursor { + cursor: usize, +} + +impl ArgCursor { + fn new() -> Self { + Self { cursor: 0 } + } +} + +/// Command-line Argument +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ParsedArg<'s> { + inner: std::borrow::Cow<'s, RawOsStr>, + utf8: Option<&'s str>, +} + +impl<'s> ParsedArg<'s> { + fn new(inner: &'s OsStr) -> Self { + let utf8 = inner.to_str(); + let inner = RawOsStr::new(inner); + Self { inner, utf8 } + } + + /// Argument is length of 0 + pub fn is_empty(&self) -> bool { + self.inner.as_ref().is_empty() + } + + /// Does the argument look like a stdio argument (`-`) + pub fn is_stdio(&self) -> bool { + self.inner.as_ref() == "-" + } + + /// Does the argument look like an argument escape (`--`) + pub fn is_escape(&self) -> bool { + self.inner.as_ref() == "--" + } + + /// Does the argument look like a number + pub fn is_number(&self) -> bool { + self.to_value() + .map(|s| s.parse::().is_ok()) + .unwrap_or_default() + } + + /// Treat as a long-flag + pub fn to_long(&self) -> Option<(Result<&str, &RawOsStr>, Option<&RawOsStr>)> { + if let Some(raw) = self.utf8 { + let remainder = raw.strip_prefix("--")?; + if remainder.is_empty() { + debug_assert!(self.is_escape()); + return None; + } + + let (flag, value) = if let Some((p0, p1)) = remainder.split_once('=') { + (p0, Some(p1)) + } else { + (remainder, None) + }; + let flag = Ok(flag); + let value = value.map(RawOsStr::from_str); + Some((flag, value)) + } else { + let raw = self.inner.as_ref(); + let remainder = raw.strip_prefix("--")?; + if remainder.is_empty() { + debug_assert!(self.is_escape()); + return None; + } + + let (flag, value) = if let Some((p0, p1)) = remainder.split_once('=') { + (p0, Some(p1)) + } else { + (remainder, None) + }; + let flag = flag.to_str().ok_or(flag); + Some((flag, value)) + } + } + + /// Can treat as a long-flag + pub fn is_long(&self) -> bool { + self.inner.as_ref().starts_with("--") && !self.is_escape() + } + + /// Treat as a short-flag + pub fn to_short(&self) -> Option> { + if let Some(remainder_os) = self.inner.as_ref().strip_prefix('-') { + if remainder_os.starts_with('-') { + None + } else if remainder_os.is_empty() { + debug_assert!(self.is_stdio()); + None + } else { + let remainder = self.utf8.map(|s| &s[1..]); + Some(ShortFlags::new(remainder_os, remainder)) + } + } else { + None + } + } + + /// Can treat as a short-flag + pub fn is_short(&self) -> bool { + self.inner.as_ref().starts_with('-') + && !self.is_stdio() + && !self.inner.as_ref().starts_with("--") + } + + /// Treat as a value + /// + /// **NOTE:** May return a flag or an escape. + pub fn to_value_os(&self) -> &RawOsStr { + self.inner.as_ref() + } + + /// Treat as a value + /// + /// **NOTE:** May return a flag or an escape. + pub fn to_value(&self) -> Result<&str, &RawOsStr> { + self.utf8.ok_or_else(|| self.inner.as_ref()) + } + + /// Safely print an argument that may contain non-UTF8 content + /// + /// This may perform lossy conversion, depending on the platform. If you would like an implementation which escapes the path please use Debug instead. + pub fn display(&self) -> impl std::fmt::Display + '_ { + self.inner.to_str_lossy() + } +} + +/// Walk through short flags within a [`ParsedArg`] +#[derive(Clone, Debug)] +pub struct ShortFlags<'s> { + inner: &'s RawOsStr, + utf8_prefix: std::str::CharIndices<'s>, + invalid_suffix: Option<&'s RawOsStr>, +} + +impl<'s> ShortFlags<'s> { + fn new(inner: &'s RawOsStr, utf8: Option<&'s str>) -> Self { + let (utf8_prefix, invalid_suffix) = if let Some(utf8) = utf8 { + (utf8, None) + } else { + split_nonutf8_once(inner) + }; + let utf8_prefix = utf8_prefix.char_indices(); + Self { + inner, + utf8_prefix, + invalid_suffix, + } + } + + /// Move the iterator forward by `n` short flags + pub fn advance_by(&mut self, n: usize) -> Result<(), usize> { + for i in 0..n { + self.next().ok_or(i)?.map_err(|_| i)?; + } + Ok(()) + } + + /// No short flags left + pub fn is_empty(&self) -> bool { + self.invalid_suffix.is_none() && self.utf8_prefix.as_str().is_empty() + } + + /// Does the short flag look like a number + /// + /// Ideally call this before doing any iterator + pub fn is_number(&self) -> bool { + self.invalid_suffix.is_none() && self.utf8_prefix.as_str().parse::().is_ok() + } + + /// Advance the iterator, returning the next short flag on success + /// + /// On error, returns the invalid-UTF8 value + pub fn next_flag(&mut self) -> Option> { + if let Some((_, flag)) = self.utf8_prefix.next() { + return Some(Ok(flag)); + } + + if let Some(suffix) = self.invalid_suffix { + self.invalid_suffix = None; + return Some(Err(suffix)); + } + + None + } + + /// Advance the iterator, returning everything left as a value + pub fn next_value_os(&mut self) -> Option<&'s RawOsStr> { + if let Some((index, _)) = self.utf8_prefix.next() { + self.utf8_prefix = "".char_indices(); + self.invalid_suffix = None; + return Some(&self.inner[index..]); + } + + if let Some(suffix) = self.invalid_suffix { + self.invalid_suffix = None; + return Some(suffix); + } + + None + } +} + +impl<'s> Iterator for ShortFlags<'s> { + type Item = Result; + + fn next(&mut self) -> Option { + self.next_flag() + } +} + +fn split_nonutf8_once(b: &RawOsStr) -> (&str, Option<&RawOsStr>) { + match std::str::from_utf8(b.as_raw_bytes()) { + Ok(s) => (s, None), + Err(err) => { + let (valid, after_valid) = b.split_at(err.valid_up_to()); + let valid = std::str::from_utf8(valid.as_raw_bytes()).unwrap(); + (valid, Some(after_valid)) + } + } +} diff --git a/vendor/clap_lex/.cargo-checksum.json b/vendor/clap_lex/.cargo-checksum.json deleted file mode 100644 index d1fc5c2fe..000000000 --- a/vendor/clap_lex/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"8141410d44a74e1783beeec03f35ac2b89ead0f2d0e0fb6ddc71dcc064749a89","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"b68af9a7bf1ad292ee5cfccb123dc639c5c1ad9b57645e533209965c394bf05d","src/lib.rs":"d78b54dc0fe6bd1a3a0ae764d31616a83b1a3b596ec75ad8f182c119c8c30b74"},"package":"5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613"} \ No newline at end of file diff --git a/vendor/clap_lex/Cargo.toml b/vendor/clap_lex/Cargo.toml deleted file mode 100644 index b089dcde8..000000000 --- a/vendor/clap_lex/Cargo.toml +++ /dev/null @@ -1,89 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2021" -rust-version = "1.56.0" -name = "clap_lex" -version = "0.2.2" -include = [ - "build.rs", - "src/**/*", - "Cargo.toml", - "LICENSE*", - "README.md", - "benches/**/*", - "examples/**/*", -] -description = "Minimal, flexible command line parser" -documentation = "https://docs.rs/clap_lex" -readme = "README.md" -keywords = [ - "argument", - "cli", - "arg", - "parser", - "parse", -] -categories = ["command-line-interface"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/clap-rs/clap/tree/master/clap_lex" -resolver = "2" - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "Unreleased" -replace = "{{version}}" -min = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = '\.\.\.HEAD' -replace = "...{{tag_name}}" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "ReleaseDate" -replace = "{{date}}" -min = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "" -replace = """ - -## [Unreleased] - ReleaseDate -""" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "" -replace = """ - -[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "README.md" -search = "github.com/clap-rs/clap/blob/[^/]+/" -replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" -exactly = 4 -prerelease = true - -[lib] -bench = false - -[dependencies.os_str_bytes] -version = "6.0" -features = ["raw_os_str"] -default-features = false diff --git a/vendor/clap_lex/LICENSE-APACHE b/vendor/clap_lex/LICENSE-APACHE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/clap_lex/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/clap_lex/LICENSE-MIT b/vendor/clap_lex/LICENSE-MIT deleted file mode 100644 index 5acedf041..000000000 --- a/vendor/clap_lex/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2016 Kevin B. Knapp - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/clap_lex/README.md b/vendor/clap_lex/README.md deleted file mode 100644 index 0c21bc819..000000000 --- a/vendor/clap_lex/README.md +++ /dev/null @@ -1,19 +0,0 @@ - -# clap_lex - -> **Minimal, flexible command line parser** - -[![Crates.io](https://img.shields.io/crates/v/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) -[![Crates.io](https://img.shields.io/crates/d/clap_lex?style=flat-square)](https://crates.io/crates/clap_lex) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-APACHE) -[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/LICENSE-MIT) - -Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). - -1. [About](#about) -2. [API Reference](https://docs.rs/clap_lex) -3. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) -4. [CONTRIBUTING](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/clap_lex/CONTRIBUTING.md) -5. [Sponsors](https://github.com/clap-rs/clap/blob/clap_lex-v0.2.2/README.md#sponsors) - -## About diff --git a/vendor/clap_lex/src/lib.rs b/vendor/clap_lex/src/lib.rs deleted file mode 100644 index f205c3de0..000000000 --- a/vendor/clap_lex/src/lib.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! Minimal, flexible command-line parser -//! -//! As opposed to a declarative parser, this processes arguments as a stream of tokens. As lexing -//! a command-line is not context-free, we rely on the caller to decide how to interpret the -//! arguments. -//! -//! # Examples -//! -//! ```rust -//! # use std::path::PathBuf; -//! # type BoxedError = Box; -//! #[derive(Debug)] -//! struct Args { -//! paths: Vec, -//! color: Color, -//! verbosity: usize, -//! } -//! -//! #[derive(Debug)] -//! enum Color { -//! Always, -//! Auto, -//! Never, -//! } -//! -//! impl Color { -//! fn parse(s: Option<&clap_lex::RawOsStr>) -> Result { -//! let s = s.map(|s| s.to_str().ok_or(s)); -//! match s { -//! Some(Ok("always")) | Some(Ok("")) | None => { -//! Ok(Color::Always) -//! } -//! Some(Ok("auto")) => { -//! Ok(Color::Auto) -//! } -//! Some(Ok("never")) => { -//! Ok(Color::Never) -//! } -//! Some(invalid) => { -//! Err(format!("Invalid value for `--color`, {:?}", invalid).into()) -//! } -//! } -//! } -//! } -//! -//! fn parse_args( -//! raw: impl IntoIterator> -//! ) -> Result { -//! let mut args = Args { -//! paths: Vec::new(), -//! color: Color::Auto, -//! verbosity: 0, -//! }; -//! -//! let raw = clap_lex::RawArgs::new(raw); -//! let mut cursor = raw.cursor(); -//! raw.next(&mut cursor); // Skip the bin -//! while let Some(arg) = raw.next(&mut cursor) { -//! if arg.is_escape() { -//! args.paths.extend(raw.remaining(&mut cursor).map(PathBuf::from)); -//! } else if arg.is_stdio() { -//! args.paths.push(PathBuf::from("-")); -//! } else if let Some((long, value)) = arg.to_long() { -//! match long { -//! Ok("verbose") => { -//! if let Some(value) = value { -//! return Err(format!("`--verbose` does not take a value, got `{:?}`", value).into()); -//! } -//! args.verbosity += 1; -//! } -//! Ok("color") => { -//! args.color = Color::parse(value)?; -//! } -//! _ => { -//! return Err( -//! format!("Unexpected flag: --{}", arg.display()).into() -//! ); -//! } -//! } -//! } else if let Some(mut shorts) = arg.to_short() { -//! while let Some(short) = shorts.next_flag() { -//! match short { -//! Ok('v') => { -//! args.verbosity += 1; -//! } -//! Ok('c') => { -//! let value = shorts.next_value_os(); -//! args.color = Color::parse(value)?; -//! } -//! Ok(c) => { -//! return Err(format!("Unexpected flag: -{}", c).into()); -//! } -//! Err(e) => { -//! return Err(format!("Unexpected flag: -{}", e.to_str_lossy()).into()); -//! } -//! } -//! } -//! } else { -//! args.paths.push(PathBuf::from(arg.to_value_os().to_os_str().into_owned())); -//! } -//! } -//! -//! Ok(args) -//! } -//! -//! let args = parse_args(["bin", "--hello", "world"]); -//! println!("{:?}", args); -//! ``` - -use std::ffi::OsStr; -use std::ffi::OsString; - -pub use std::io::SeekFrom; - -pub use os_str_bytes::RawOsStr; -pub use os_str_bytes::RawOsString; - -/// Command-line arguments -#[derive(Default, Clone, Debug, PartialEq, Eq)] -pub struct RawArgs { - items: Vec, -} - -impl RawArgs { - //// Create an argument list to parse - /// - /// **NOTE:** The argument returned will be the current binary. - /// - /// # Example - /// - /// ```rust,no_run - /// # use std::path::PathBuf; - /// let raw = clap_lex::RawArgs::from_args(); - /// let mut cursor = raw.cursor(); - /// let _bin = raw.next_os(&mut cursor); - /// - /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); - /// println!("{:?}", paths); - /// ``` - pub fn from_args() -> Self { - Self::new(std::env::args_os()) - } - - //// Create an argument list to parse - /// - /// # Example - /// - /// ```rust,no_run - /// # use std::path::PathBuf; - /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); - /// let mut cursor = raw.cursor(); - /// let _bin = raw.next_os(&mut cursor); - /// - /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); - /// println!("{:?}", paths); - /// ``` - pub fn new(iter: impl IntoIterator>) -> Self { - let iter = iter.into_iter(); - Self::from(iter) - } - - /// Create a cursor for walking the arguments - /// - /// # Example - /// - /// ```rust,no_run - /// # use std::path::PathBuf; - /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); - /// let mut cursor = raw.cursor(); - /// let _bin = raw.next_os(&mut cursor); - /// - /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); - /// println!("{:?}", paths); - /// ``` - pub fn cursor(&self) -> ArgCursor { - ArgCursor::new() - } - - /// Advance the cursor, returning the next [`ParsedArg`] - pub fn next(&self, cursor: &mut ArgCursor) -> Option> { - self.next_os(cursor).map(ParsedArg::new) - } - - /// Advance the cursor, returning a raw argument value. - pub fn next_os(&self, cursor: &mut ArgCursor) -> Option<&OsStr> { - let next = self.items.get(cursor.cursor).map(|s| s.as_os_str()); - cursor.cursor = cursor.cursor.saturating_add(1); - next - } - - /// Return the next [`ParsedArg`] - pub fn peek(&self, cursor: &ArgCursor) -> Option> { - self.peek_os(cursor).map(ParsedArg::new) - } - - /// Return a raw argument value. - pub fn peek_os(&self, cursor: &ArgCursor) -> Option<&OsStr> { - self.items.get(cursor.cursor).map(|s| s.as_os_str()) - } - - /// Return all remaining raw arguments, advancing the cursor to the end - /// - /// # Example - /// - /// ```rust,no_run - /// # use std::path::PathBuf; - /// let raw = clap_lex::RawArgs::new(["bin", "foo.txt"]); - /// let mut cursor = raw.cursor(); - /// let _bin = raw.next_os(&mut cursor); - /// - /// let mut paths = raw.remaining(&mut cursor).map(PathBuf::from).collect::>(); - /// println!("{:?}", paths); - /// ``` - pub fn remaining(&self, cursor: &mut ArgCursor) -> impl Iterator { - let remaining = self.items[cursor.cursor..].iter().map(|s| s.as_os_str()); - cursor.cursor = self.items.len(); - remaining - } - - /// Adjust the cursor's position - pub fn seek(&self, cursor: &mut ArgCursor, pos: SeekFrom) { - let pos = match pos { - SeekFrom::Start(pos) => pos, - SeekFrom::End(pos) => (self.items.len() as i64).saturating_add(pos).max(0) as u64, - SeekFrom::Current(pos) => (cursor.cursor as i64).saturating_add(pos).max(0) as u64, - }; - let pos = (pos as usize).min(self.items.len()); - cursor.cursor = pos; - } - - /// Inject arguments before the [`RawArgs::next`] - pub fn insert(&mut self, cursor: &ArgCursor, insert_items: &[&str]) { - self.items.splice( - cursor.cursor..cursor.cursor, - insert_items.iter().map(OsString::from), - ); - } - - /// Any remaining args? - pub fn is_end(&self, cursor: &ArgCursor) -> bool { - self.peek_os(cursor).is_none() - } -} - -impl From for RawArgs -where - I: Iterator, - T: Into, -{ - fn from(val: I) -> Self { - Self { - items: val.map(|x| x.into()).collect(), - } - } -} - -/// Position within [`RawArgs`] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct ArgCursor { - cursor: usize, -} - -impl ArgCursor { - fn new() -> Self { - Self { cursor: 0 } - } -} - -/// Command-line Argument -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ParsedArg<'s> { - inner: std::borrow::Cow<'s, RawOsStr>, - utf8: Option<&'s str>, -} - -impl<'s> ParsedArg<'s> { - fn new(inner: &'s OsStr) -> Self { - let utf8 = inner.to_str(); - let inner = RawOsStr::new(inner); - Self { inner, utf8 } - } - - /// Argument is length of 0 - pub fn is_empty(&self) -> bool { - self.inner.as_ref().is_empty() - } - - /// Does the argument look like a stdio argument (`-`) - pub fn is_stdio(&self) -> bool { - self.inner.as_ref() == "-" - } - - /// Does the argument look like an argument escape (`--`) - pub fn is_escape(&self) -> bool { - self.inner.as_ref() == "--" - } - - /// Does the argument look like a number - pub fn is_number(&self) -> bool { - self.to_value() - .map(|s| s.parse::().is_ok()) - .unwrap_or_default() - } - - /// Treat as a long-flag - pub fn to_long(&self) -> Option<(Result<&str, &RawOsStr>, Option<&RawOsStr>)> { - if let Some(raw) = self.utf8 { - let remainder = raw.strip_prefix("--")?; - if remainder.is_empty() { - debug_assert!(self.is_escape()); - return None; - } - - let (flag, value) = if let Some((p0, p1)) = remainder.split_once('=') { - (p0, Some(p1)) - } else { - (remainder, None) - }; - let flag = Ok(flag); - let value = value.map(RawOsStr::from_str); - Some((flag, value)) - } else { - let raw = self.inner.as_ref(); - let remainder = raw.strip_prefix("--")?; - if remainder.is_empty() { - debug_assert!(self.is_escape()); - return None; - } - - let (flag, value) = if let Some((p0, p1)) = remainder.split_once('=') { - (p0, Some(p1)) - } else { - (remainder, None) - }; - let flag = flag.to_str().ok_or(flag); - Some((flag, value)) - } - } - - /// Can treat as a long-flag - pub fn is_long(&self) -> bool { - self.inner.as_ref().starts_with("--") && !self.is_escape() - } - - /// Treat as a short-flag - pub fn to_short(&self) -> Option> { - if let Some(remainder_os) = self.inner.as_ref().strip_prefix('-') { - if remainder_os.starts_with('-') { - None - } else if remainder_os.is_empty() { - debug_assert!(self.is_stdio()); - None - } else { - let remainder = self.utf8.map(|s| &s[1..]); - Some(ShortFlags::new(remainder_os, remainder)) - } - } else { - None - } - } - - /// Can treat as a short-flag - pub fn is_short(&self) -> bool { - self.inner.as_ref().starts_with('-') - && !self.is_stdio() - && !self.inner.as_ref().starts_with("--") - } - - /// Treat as a value - /// - /// **NOTE:** May return a flag or an escape. - pub fn to_value_os(&self) -> &RawOsStr { - self.inner.as_ref() - } - - /// Treat as a value - /// - /// **NOTE:** May return a flag or an escape. - pub fn to_value(&self) -> Result<&str, &RawOsStr> { - self.utf8.ok_or_else(|| self.inner.as_ref()) - } - - /// Safely print an argument that may contain non-UTF8 content - /// - /// This may perform lossy conversion, depending on the platform. If you would like an implementation which escapes the path please use Debug instead. - pub fn display(&self) -> impl std::fmt::Display + '_ { - self.inner.to_str_lossy() - } -} - -/// Walk through short flags within a [`ParsedArg`] -#[derive(Clone, Debug)] -pub struct ShortFlags<'s> { - inner: &'s RawOsStr, - utf8_prefix: std::str::CharIndices<'s>, - invalid_suffix: Option<&'s RawOsStr>, -} - -impl<'s> ShortFlags<'s> { - fn new(inner: &'s RawOsStr, utf8: Option<&'s str>) -> Self { - let (utf8_prefix, invalid_suffix) = if let Some(utf8) = utf8 { - (utf8, None) - } else { - split_nonutf8_once(inner) - }; - let utf8_prefix = utf8_prefix.char_indices(); - Self { - inner, - utf8_prefix, - invalid_suffix, - } - } - - /// Move the iterator forward by `n` short flags - pub fn advance_by(&mut self, n: usize) -> Result<(), usize> { - for i in 0..n { - self.next().ok_or(i)?.map_err(|_| i)?; - } - Ok(()) - } - - /// No short flags left - pub fn is_empty(&self) -> bool { - self.invalid_suffix.is_none() && self.utf8_prefix.as_str().is_empty() - } - - /// Does the short flag look like a number - /// - /// Ideally call this before doing any iterator - pub fn is_number(&self) -> bool { - self.invalid_suffix.is_none() && self.utf8_prefix.as_str().parse::().is_ok() - } - - /// Advance the iterator, returning the next short flag on success - /// - /// On error, returns the invalid-UTF8 value - pub fn next_flag(&mut self) -> Option> { - if let Some((_, flag)) = self.utf8_prefix.next() { - return Some(Ok(flag)); - } - - if let Some(suffix) = self.invalid_suffix { - self.invalid_suffix = None; - return Some(Err(suffix)); - } - - None - } - - /// Advance the iterator, returning everything left as a value - pub fn next_value_os(&mut self) -> Option<&'s RawOsStr> { - if let Some((index, _)) = self.utf8_prefix.next() { - self.utf8_prefix = "".char_indices(); - self.invalid_suffix = None; - return Some(&self.inner[index..]); - } - - if let Some(suffix) = self.invalid_suffix { - self.invalid_suffix = None; - return Some(suffix); - } - - None - } -} - -impl<'s> Iterator for ShortFlags<'s> { - type Item = Result; - - fn next(&mut self) -> Option { - self.next_flag() - } -} - -fn split_nonutf8_once(b: &RawOsStr) -> (&str, Option<&RawOsStr>) { - match std::str::from_utf8(b.as_raw_bytes()) { - Ok(s) => (s, None), - Err(err) => { - let (valid, after_valid) = b.split_at(err.valid_up_to()); - let valid = std::str::from_utf8(valid.as_raw_bytes()).unwrap(); - (valid, Some(after_valid)) - } - } -} diff --git a/vendor/compiler_builtins/.cargo-checksum.json b/vendor/compiler_builtins/.cargo-checksum.json index 9324f092f..90052bb9e 100644 --- a/vendor/compiler_builtins/.cargo-checksum.json +++ b/vendor/compiler_builtins/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.lock":"b369bba03aca1dd529671fb54000fd8dfc0d4d5b5cfe1afe71294155c974bc34","Cargo.toml":"1f727cb37da8b846367a12e034c01aca729f745a695383dd596b05b7f86ba970","README.md":"5eb36fbab30693dbbe9f0de54749c95bd06fd6e42013b5b9eff3c062b9fdd34f","build.rs":"991919d9ab1eca85e87a85acafcb86d4880f1afe9fe35d6bd87039dcb1fa9aa7","examples/intrinsics.rs":"a7aa69c17af3aa8f6edff32c214e80827d3cbe3aea386a2be42244444752d253","libm/src/math/acos.rs":"fb066ba84aba1372d706425ec14f35ff8d971756d15eeebd22ecf42a716493bb","libm/src/math/acosf.rs":"a112b82309bba1d35c4e3d6ad4d6c21ef305343d9ab601ddf4bc61d43bc9f1af","libm/src/math/acosh.rs":"56dac8538e4350cd7cf001327c89f087b68abb2e6aaad58edba8a094b09f6b0f","libm/src/math/acoshf.rs":"df5b0c4d8e37e64cf5ff2d8328b28bc35c78e84060ff769e64523ea9ff9065c1","libm/src/math/asin.rs":"095a1e98996daff45df0b154ca0ec35bbf31db964ee9fdda0207308cb20df441","libm/src/math/asinf.rs":"49cccb4db2881982643a4a7d5453f4f8daf527711bbb67313607a3c178856d61","libm/src/math/asinh.rs":"e8fc94031015fddf35e9c26b94da9f6431ee17c81cd7bd37da8ffc98f7e0b32c","libm/src/math/asinhf.rs":"8a0b8933a98a17617a66fef4c7b89eba645fdf05302000babf4a5a5f45328430","libm/src/math/atan.rs":"d4fe46e1c5739dd09997869dcfbc3c85f03c534af52e700d6c6bcf9c3fedda07","libm/src/math/atan2.rs":"2623bc8ca707d13a7092ce49adf68e9cbf4452ad1bf4a861dc40ca858606a747","libm/src/math/atan2f.rs":"dd01943e0e1f1955912e5c3ffc9467529cf64bd02ac0a6ad5ab31dbe6657f05d","libm/src/math/atanf.rs":"e41b41569474a59c970ede3538e00bda4072cf4d90040017101cc79d7dc28caa","libm/src/math/atanh.rs":"5934dbd6b7395ca4f103ace7598da723a9270e1cf6b47e7f786debe4bb3651ff","libm/src/math/atanhf.rs":"8ba4711dda19ef2dc33622be65c1483902868083543198c6bbd040d4026293de","libm/src/math/cbrt.rs":"f2c45612d2eecd93cfcdd9ebf824c754fc8f8dfd6d16862c0b9c4ccea78c2a0f","libm/src/math/cbrtf.rs":"ad0b483854aa9f17a44d36c049bf0e8ebab34c27e90b787c05f45cc230ec7d19","libm/src/math/ceil.rs":"57ba5b6e207a0ccbd34190d1aa544389ca12126be23821dfb5746497f620ce03","libm/src/math/ceilf.rs":"c922a0475a599b9ea5473e615f74700b99707cebd6927f24ea59cb2a3cb3bbc3","libm/src/math/copysign.rs":"d80c880efaf0cdf2ce0a4d4f5a68dd6c36c88d46fa997ec8ac8604bfdb26fa33","libm/src/math/copysignf.rs":"1547116071e68a42b1605eb2fc722db6466a34517dc96b92de1f29a274c3d8e3","libm/src/math/cos.rs":"74babdc13ede78e400c5ca1854c3e22d2e08cbdc5618aefa5bba6f9303ef65b6","libm/src/math/cosf.rs":"09c40f93c445b741e22477ceedf163ca33b6a47f973f7c9876cfba2692edb29c","libm/src/math/cosh.rs":"0d0a7cef18577f321996b8b87561963139f754ad7f2ea0a3b3883811f3f0693a","libm/src/math/coshf.rs":"be8ca8739e4cf1978425b349f941cb4838bba8c10cb559c7940b9fd4fdde21ad","libm/src/math/erf.rs":"9c55fc6756ba816996f0b585e07ccfa4cd87575ad525cd30c4a968b30acffda3","libm/src/math/erff.rs":"cb020e8bada9a54573a11fe3271750d73f14fed3092a881a9ceaf98fe32fd5a6","libm/src/math/exp.rs":"ca7405ad0d1993fffcf9aae96f9256307bed3c4916545aaebd1cf1d2df1807fa","libm/src/math/exp10.rs":"2deb037f88feac87a0e924b69dd496f0dd3b5d35f2a58e09d4c5166b207e517b","libm/src/math/exp10f.rs":"6979464dfe3f4f2da1f9afc909646499c4bfaef15e10a039384750e2f1586fea","libm/src/math/exp2.rs":"94a9304a2ce3bc81f6d2aefd3cde6faa30f13260d46cb13692863cdea1c9a3a1","libm/src/math/exp2f.rs":"785f2630accd35118ec07bf60273e219ed91a215b956b1552eeea5bc2a708cc8","libm/src/math/expf.rs":"ec14c18f891a9e37735ec39e6fc2e9bf674a2c2e083f22e2533b481177359c98","libm/src/math/expm1.rs":"124069f456c8ad331f265c7509d9e223b2a300e461bbfd3d6adfdcdd2ee5b8ac","libm/src/math/expm1f.rs":"18e2116d31ea8410051cc709b9d04b754b0e3ba6758ee1bf0b48749f4999b840","libm/src/math/expo2.rs":"4f4f9fecfccb43f30c2784aa7c0bb656754a52b8ab431f7d1b551c673ab133f1","libm/src/math/fabs.rs":"e6c7db39f98508098cdf64ac0c2f53866c466149a7490afb9fe22b44c4dd81b3","libm/src/math/fabsf.rs":"83a1f5f4d9ca899ba2b701d7332e18b40258b83e111db4c5d8fab2cc1be58aa3","libm/src/math/fdim.rs":"8ec091996005207297c2389ae563e1b18dbc6a9eac951de29a976c5cd7bc32a7","libm/src/math/fdimf.rs":"c7f3f2269834d55be26b6580ddc07c42531577955fa4de35bad1e2a361085614","libm/src/math/fenv.rs":"8730d45aa4c591f91dccdcc1ce533fa23e9c6df0c38defb9c57f749cb25e1cd0","libm/src/math/floor.rs":"5050804cae173af6775c0678d6c1aafb5ca2b744bc8a2f50d9d03b95dcee1fb0","libm/src/math/floorf.rs":"c903e0c57bc60a888c513eb7a873a87a4759ba68fc791b6b931652f8ee74cc03","libm/src/math/fma.rs":"d88e01c2c2d11333dd49b61166caa036ff5f08f3a8c5973b9e3c9574bf2eb675","libm/src/math/fmaf.rs":"3e0f5727e56f31218f674b9b8975d7e67b3a24a097f06a2a3eca9723cd786213","libm/src/math/fmax.rs":"f6c8e96a8b1a170648d2fa3513e7b6b459085d708c839869f82e305fe58fac37","libm/src/math/fmaxf.rs":"dff0025433232e8a5ec7bd54d847ccf596d762ea4e35f5c54fbaac9404d732fd","libm/src/math/fmin.rs":"95b6cb66ca0e0e22276f0bf88dbe8fb69796a69a196a7491bd4802efbcf2e298","libm/src/math/fminf.rs":"304bc839b15ea3d84e68d2af9f40524ec120d30a36a667b22fcb98a6c258f4c7","libm/src/math/fmod.rs":"a1c0550fc7df8164733d914e222ff0966a2ab886d6e75a1098f24fe0283ae227","libm/src/math/fmodf.rs":"ee51ed092c0eeb8195f35735ff725cfd46612e0d689a7c483538bd92fbe61828","libm/src/math/frexp.rs":"28af70026922a8ab979744c7ad4d8faba6079c4743b7eeb6d14c983a982fbbcc","libm/src/math/frexpf.rs":"2e2593ae8002ba420809ebfaf737ef001cdc912354be3d978a8c0cb930350d4d","libm/src/math/hypot.rs":"841131c4a0cea75bc8a86e29f3f6d0815a61fc99731c9984651ce83d3050d218","libm/src/math/hypotf.rs":"5f317323edc2eb699580fe54b074b7e570a7734d51a0a149c0b49b54470a836c","libm/src/math/ilogb.rs":"813413bf6266d4fc40db9c5921af3cef4f892ba93e8f6d9efe62a449d1234532","libm/src/math/ilogbf.rs":"dec462780f46682e16cfaa733238bed3b692729e951f53a44726100b6c73a716","libm/src/math/j0.rs":"9572b6396c489927d332d0e717920e61ec0618e5e9c31f7eeeec70f5e4abab06","libm/src/math/j0f.rs":"802c8254bded9b3afb6eea8b9af240038a5a4a5d811396729f69ca509e3e7d87","libm/src/math/j1.rs":"97b1af1611fa3d110c2b349ee8e4176100132ea1391b619086b47ac063b81803","libm/src/math/j1f.rs":"9c9b128752e8ea2e7d81b637ba84907ab54a545e7602c49167b313743927930b","libm/src/math/jn.rs":"847d122334e5707ad9627146cddccc082a1f2f5bcd3e5ef54399013a7007ce88","libm/src/math/jnf.rs":"4045076f7d1a1b89882ed60d4dd60a4cbbc66b85cfb90491378c8015effcc476","libm/src/math/k_cos.rs":"f34a69e44d6b8901b03b578a75972f438ab20a7b98a0903fc1903d6fde3899be","libm/src/math/k_cosf.rs":"8f7117ff21cebf8e890a5bcfd7ea858a94172f4172b79a66d53824c2cb0888b1","libm/src/math/k_expo2.rs":"eb4ca9e6a525b7ea6da868c3cb136896682cc46f8396ba2a2ebc3ae9e9ba54b0","libm/src/math/k_expo2f.rs":"d51ad5df61cb5d1258bdb90c52bfed4572bb446a9337de9c04411ed9454ae0cb","libm/src/math/k_sin.rs":"14b2aba6ca07150c92768b5a72acaf5cde6a11d6619e14896512a7ba242e289a","libm/src/math/k_sinf.rs":"2775fcc710807164e6f37a4f8da3c8143cd5f16e19ce7c31c5591522151d7a96","libm/src/math/k_tan.rs":"a72beae4ccd9631eeeb61d6365bbeecae81c8411f3120a999c515cca0d5ea5c5","libm/src/math/k_tanf.rs":"6a794be56fa4b2f60452b9bab19af01c388f174560acbf829a351378ea39495d","libm/src/math/ldexp.rs":"b647f0096e80e4d926d8dd18d294c892ee2cb1778effe2c5e1b2664ae5cb1a4e","libm/src/math/ldexpf.rs":"98743fad2cd97a7be496f40ba3157ac1438fce0d0c25d5ab90c3b8c71c3fd0ed","libm/src/math/lgamma.rs":"498552658cc8106d7754f85ae8dbc3306ac2f0a9f7eb5a796be70c5beac92c41","libm/src/math/lgamma_r.rs":"77fb6442aeb5343926d8965e1549dde3e2cc4fd09555de6b56506001d956c344","libm/src/math/lgammaf.rs":"457105f53a4c8717e8f5a117d261dcf94e222e83981337fe23602abe883fe3f7","libm/src/math/lgammaf_r.rs":"44de75babbdd53c4a5879cd6f426e7311db82669def39df5f63914d67d6cc1b1","libm/src/math/log.rs":"b5e0c5f30d9e94351488732801be3107c12b854c3f95ad37e256dd88eeca408f","libm/src/math/log10.rs":"3425ff8be001fd1646ba15e254eb6ef4bdc6ccaf0cbee27ddf1fa84e04178b90","libm/src/math/log10f.rs":"fee4f71879bc4c99259e68c0c641364901629fb29a8ebddfcc0d090102cceddd","libm/src/math/log1p.rs":"9cf400852f165e6be19b97036ae9521fb9ca857d0a9a91c117d9123221622185","libm/src/math/log1pf.rs":"2716e6d2afa271996b7c8f47fd9e4952c88f4c1fd8c07c3e8ce8c62794bf71d8","libm/src/math/log2.rs":"dbbbfbaaa8aa6a4dbefea554ea3983090a9691228b011910c751f6adca912c40","libm/src/math/log2f.rs":"92a90350d8edce21c31c285c3e620fca7c62a2366008921715945c2c73b5b79f","libm/src/math/logf.rs":"845342cffc34d3db1f5ec12d8e5b773cd5a79056e28662fcb9bcd80207596f50","libm/src/math/mod.rs":"9de65aedb36910356bc47d25b1468b40ab63faf7e319e599e478a239681bdf9c","libm/src/math/modf.rs":"d012ed5a708ef52b6d1313c22a46cadaf5764dde1220816e3df2f03a0fcc60ae","libm/src/math/modff.rs":"f8f1e4c27a85d2cdb3c8e74439d59ef64aa543b948f22c23227d02d8388d61c2","libm/src/math/nextafter.rs":"3282e7eef214a32736fb6928d490198ad394b26b402b45495115b104839eebfe","libm/src/math/nextafterf.rs":"0937dc8a8155c19842c12181e741cec1f7df1f7a00cee81fcb2475e2842761b7","libm/src/math/pow.rs":"17c38297c5bf99accd915f292b777f8716ecf328916297c8bb9dfde6fd8ce522","libm/src/math/powf.rs":"2c423a0ea57fdc4e20f3533f744c6e6288c998b4de8f2914fafaa0e78be81b04","libm/src/math/rem_pio2.rs":"3e53234977daf61c89c29c940791714aad2f676a6f38188c7d17543a2aa8806f","libm/src/math/rem_pio2_large.rs":"21762d08d72dc6f2e313123a7311683000974a09b8fcae50994d9c39239721b1","libm/src/math/rem_pio2f.rs":"07fb48f6d5cbadfd32ce4124b2b74af98b8391a2a6f36ce2a7d32e4500cb65ac","libm/src/math/remainder.rs":"63865f4370853c476b45bb27a5c54a4072146aa4a626835ae5263871a4e7e5dc","libm/src/math/remainderf.rs":"dd3fa432dbda8f2135428198be7bd69c57f8d13df3f365b12f52bf6a82352ac4","libm/src/math/remquo.rs":"3cc0bf55069f165c4843f2c358b3a27279c01e8cdd99f9057a3f7f31f45408f2","libm/src/math/remquof.rs":"cc749e18ecb7e766b8b8eeabdbf89ac99087d3d587e71e30f690676a3d2c1f9b","libm/src/math/round.rs":"f10797ef15dd34a74e912ba8621d60bc0200c87b94308c9de3cc88d7aec4feb4","libm/src/math/roundf.rs":"27e37cfcf82373709e7debf9c0c18f7ed00ae0f5d97a214c388041f7a6996d35","libm/src/math/scalbn.rs":"b5c9d6d4177fe393cbfe1c634d75ce14b754f6cbce87c5bf979a9661491748a2","libm/src/math/scalbnf.rs":"4f198d06db1896386256fb9a5ac5b805b16b836226c18780a475cf18d7c1449c","libm/src/math/sin.rs":"bb483a2138ca779e03a191222636f0c60fd75a77a2a12f263bda4b6aa9136317","libm/src/math/sincos.rs":"55b7446984db26bc118eb3d9b01f4fd2594de06558e0f9b6dc936a57888ca9be","libm/src/math/sincosf.rs":"f7b18383b242dad59e6033240d0e4a0fd08a2633e5048eff27532085f1c67f87","libm/src/math/sinf.rs":"dcddac1d56b084cbb8d0e019433c9c5fe2201d9b257a7dcf2f85c9a8f14b79cf","libm/src/math/sinh.rs":"d8ee4c7af883a526f36c1a6da13bb81fba9181b477e2f2538161a2bee97edc35","libm/src/math/sinhf.rs":"d06eb030ba9dbf7094df127262bfe99f149b4db49fa8ab8c15499660f1e46b26","libm/src/math/sqrt.rs":"824570a631c2542ccee68b65e3eb08fe79c037a29bbaaf54da5367e7b236124a","libm/src/math/sqrtf.rs":"4cf418d74f7751d522a642a9a8d6b86ee3472c6aaef44f0eb1bc26f4d8a90985","libm/src/math/tan.rs":"930ecedaadc60f704c2dfa4e15186f59713c1ba7d948529d215223b424827db5","libm/src/math/tanf.rs":"894156a3b107aee08461eb4e7e412fc049aa237d176ae705c6e3e2d7060d94e3","libm/src/math/tanh.rs":"f1f08eb98ed959a17370a7aaf0177be36e3764543424e78feb033ed3f5e8ec98","libm/src/math/tanhf.rs":"74027b0c672a4e64bdef6d7a3069b90caec50e1e7dbb2c12d2828f310502f41e","libm/src/math/tgamma.rs":"a6aabb8365410af6611f19f58694ccb74e82bb9ba9e1cdec7e1af787cfa44815","libm/src/math/tgammaf.rs":"c95bd69957387533853532164f7e2251d2b04f5e775406b9e647226ae2bdd5ad","libm/src/math/trunc.rs":"642264897cc1505e720c8cf313be81aa9fd53aae866644a2e988d01dbc77fd8a","libm/src/math/truncf.rs":"dee3607baf1af0f01deae46e429e097234c50b268eaefebbe716f19f38597900","src/arm.rs":"8ccf47608cc7862d8d834ca292d0d3d97faaab6cc6f20ba59ccf2987ff0f3f77","src/arm_linux.rs":"87136556091817b2bded52c3ece101123aae84ff13ccaf13a196826b2e3fc297","src/float/add.rs":"3ec32ceaf470a89777b54f9cde61832fdadeade0f4894f268a949e968520bc57","src/float/cmp.rs":"79b1fdc8d5f943c4ad5ea4ad32623b18f63e17ac3852fbc64a4942228007e1fc","src/float/conv.rs":"55138604371e00ef14167894159156b68f939039b0e5b2b1f3db61456e3d3870","src/float/div.rs":"bc808a5372d041b96aa603ac814165e1e7dbd690e4ab9b026d9465c1cbc2c583","src/float/extend.rs":"180b2e791c58e0526de0a798845c580ce3222c8a15c8665e6e6a4bf5cf1a34aa","src/float/mod.rs":"48d76632575789a6ecf99213b1ed38c21c86ad5a5c3fa33ccb31f77829271b79","src/float/mul.rs":"0d0c1f0c28c149ecadeafd459d3c4c9327e4cfcae2cba479957bb8010ef51a01","src/float/pow.rs":"2ada190738731eb6f24104f8fb8c4d6f03cfb16451536dbee32f2b33db0c4b19","src/float/sub.rs":"c2a87f4628f51d5d908d0f25b5d51ce0599dc559d5a72b20e131261f484d5848","src/float/trunc.rs":"d21d2a2f9a1918b4bbb594691e397972a7c04b74b2acf04016c55693abf6d24b","src/int/addsub.rs":"7ec45ce1ba15b56a5b7129d3e5722c4db764c6545306d3fa9090983bcabd6f17","src/int/leading_zeros.rs":"ccf5e9d098c80034dcf6e38437c9a2eb670fa8043558bbfb574f2293164729a6","src/int/mod.rs":"bab1b77535ceebdebb89fd4e59e7105f8c45347bb638351a626615b24544a0b1","src/int/mul.rs":"bb48d8fd42d8f9f5fe9271d8d0f7a92dbae320bf4346e19d1071eb2093cb8ed9","src/int/sdiv.rs":"ace4cb0ec388a38834e01cab2c5bc87182d31588dfc0b1ae117c11ed0c4781cf","src/int/shift.rs":"3967c28a8d61279546e91958d64745fec63f15aee9175eb0602cc6353830da6c","src/int/specialized_div_rem/asymmetric.rs":"27f5bf70a35109f9d4e4e1ad1e8003aa17da5a1e436bf3e63a493d7528a3a566","src/int/specialized_div_rem/binary_long.rs":"9f1ced81a394f000a21a329683144d68ee431a954136a3634eb55b1ee2cf6d51","src/int/specialized_div_rem/delegate.rs":"9df141af98e391361e25d71ae38d5e845a91d896edd2c041132fd46af8268e85","src/int/specialized_div_rem/mod.rs":"c32a7c416f2c81d6368720053864c3e7082417bca983c329520a8e7dc8c34736","src/int/specialized_div_rem/norm_shift.rs":"3be7ee0dea545c1f702d9daf67dad2b624bf7b17b075c8b90d3d3f7b53df4c21","src/int/specialized_div_rem/trifecta.rs":"87eef69da255b809fd710b14f2eb3f9f59e3dac625f8564ebc8ba78f9763523b","src/int/udiv.rs":"3732b490a472505411577f008b92f489287745968ce6791665201201377d3475","src/lib.rs":"557cd24974b4be235d3cdc4846eeacd8e536330ff54d037b8d56b21d99f64b3c","src/macros.rs":"4e6c006a47d7437f91a92802ecdceea63c60f3924ec98a429a14506c41c5f5dc","src/math.rs":"48bb0d97a1b56d960c6b5130b9a62a1cb1e8e5d62a522163022b8ea24c6cfcca","src/mem/impls.rs":"4517ae10a8adc2b0527529a872d8a7f98627f166d9a18a7aed6fc774b18dd843","src/mem/mod.rs":"791fa5fab759060e966de994b637e88c3c329cf2c0343efccca1da9dc80fcb66","src/mem/x86_64.rs":"912d4e955440113b97bd7dc836697df01a692524edd48cafaf599783ae277b85","src/probestack.rs":"ef5c07e9b95de7b2b77a937789fcfefd9846274317489ad6d623e377c9888601","src/riscv.rs":"8aa8cde1106a179e9a37724193bc5cea5defe212eb38e3049c23b254578f78d4","src/x86.rs":"117b50d6725ee0af0a7b3d197ea580655561f66a870ebc450d96af22bf7f39f6","src/x86_64.rs":"4f16bc9fad7757d48a6da3a078c715dd3a22154aadb4f1998d4c1b5d91396f9e"},"package":"71b72fde1d7792ca3bd654f7c3ea4508f9e4d0c826e24179eabb7fcc97a90bc3"} \ No newline at end of file +{"files":{"Cargo.lock":"d76ea6435a58ea3155de70652b8c03e08e0c96645dcf7e2f8f3650c06cb699e2","Cargo.toml":"97342c77c2e481ff977fafc2a84d7c729f26e08dee2cf1d00b6be8ddad303797","LICENSE.txt":"0e13fed90654e0bc677d624a2d770833a09541fe0c0bdb3d051b3d081207393a","README.md":"5eb36fbab30693dbbe9f0de54749c95bd06fd6e42013b5b9eff3c062b9fdd34f","build.rs":"0c006642fbbe9fa5372a88cbbbb0bb4b391f635b2bde0c497de10740c1458c5e","examples/intrinsics.rs":"a7aa69c17af3aa8f6edff32c214e80827d3cbe3aea386a2be42244444752d253","libm/src/math/acos.rs":"fb066ba84aba1372d706425ec14f35ff8d971756d15eeebd22ecf42a716493bb","libm/src/math/acosf.rs":"a112b82309bba1d35c4e3d6ad4d6c21ef305343d9ab601ddf4bc61d43bc9f1af","libm/src/math/acosh.rs":"99de01ded7922bb93a882ad5ad8b472b5cae0059dea0bdca2077f65e94483150","libm/src/math/acoshf.rs":"10750c4d39ef6717b20a15ef1ce43e15eb851682d2f820f7e94501adec98b9a5","libm/src/math/asin.rs":"095a1e98996daff45df0b154ca0ec35bbf31db964ee9fdda0207308cb20df441","libm/src/math/asinf.rs":"49cccb4db2881982643a4a7d5453f4f8daf527711bbb67313607a3c178856d61","libm/src/math/asinh.rs":"4dd51affa71cce34a192ad66154e248f8d1c4b40fb497f29052333e425bb740f","libm/src/math/asinhf.rs":"914bfecf449f5e2bce786aa12c056d419073c6011d41c1bab7c39ba765fa4c53","libm/src/math/atan.rs":"d4fe46e1c5739dd09997869dcfbc3c85f03c534af52e700d6c6bcf9c3fedda07","libm/src/math/atan2.rs":"2623bc8ca707d13a7092ce49adf68e9cbf4452ad1bf4a861dc40ca858606a747","libm/src/math/atan2f.rs":"dd01943e0e1f1955912e5c3ffc9467529cf64bd02ac0a6ad5ab31dbe6657f05d","libm/src/math/atanf.rs":"e41b41569474a59c970ede3538e00bda4072cf4d90040017101cc79d7dc28caa","libm/src/math/atanh.rs":"57a8fb3f0f116fa4a966ac6bc2abd5f80236ead8e79013f468bd3786921f7110","libm/src/math/atanhf.rs":"6f2e57aaec1b5fc7609cb3938b3d155f51b4237dbda530739c34a0448cd9beb9","libm/src/math/cbrt.rs":"f2c45612d2eecd93cfcdd9ebf824c754fc8f8dfd6d16862c0b9c4ccea78c2a0f","libm/src/math/cbrtf.rs":"ad0b483854aa9f17a44d36c049bf0e8ebab34c27e90b787c05f45cc230ec7d19","libm/src/math/ceil.rs":"57ba5b6e207a0ccbd34190d1aa544389ca12126be23821dfb5746497f620ce03","libm/src/math/ceilf.rs":"c922a0475a599b9ea5473e615f74700b99707cebd6927f24ea59cb2a3cb3bbc3","libm/src/math/copysign.rs":"8b6440a251f0f1509d87f18122f74d0d5c03d0b60517e89e441434a3c5d84591","libm/src/math/copysignf.rs":"87d35436d224852ada93a2e93f6730cf1a727b808dd10e7d49ab4585866e336b","libm/src/math/cos.rs":"74babdc13ede78e400c5ca1854c3e22d2e08cbdc5618aefa5bba6f9303ef65b6","libm/src/math/cosf.rs":"09c40f93c445b741e22477ceedf163ca33b6a47f973f7c9876cfba2692edb29c","libm/src/math/cosh.rs":"0d0a7cef18577f321996b8b87561963139f754ad7f2ea0a3b3883811f3f0693a","libm/src/math/coshf.rs":"be8ca8739e4cf1978425b349f941cb4838bba8c10cb559c7940b9fd4fdde21ad","libm/src/math/erf.rs":"52cc9d9d54074a692001fb2d8215cd6903b645d4291ea20482455bc7f6947726","libm/src/math/erff.rs":"d37af67007fe4e9bce994c8c9805dd8af1b0ada68a10db8d8db13424dce65d09","libm/src/math/exp.rs":"ca7405ad0d1993fffcf9aae96f9256307bed3c4916545aaebd1cf1d2df1807fa","libm/src/math/exp10.rs":"2e136c6ecedd8e57a6c31796f57fae4546fcfd8bc6be66c836f553df9c74b907","libm/src/math/exp10f.rs":"9a3ce506ec587066a355ab74e0eb69a03a214ac405718087ae9772365050b20b","libm/src/math/exp2.rs":"94a9304a2ce3bc81f6d2aefd3cde6faa30f13260d46cb13692863cdea1c9a3a1","libm/src/math/exp2f.rs":"785f2630accd35118ec07bf60273e219ed91a215b956b1552eeea5bc2a708cc8","libm/src/math/expf.rs":"ec14c18f891a9e37735ec39e6fc2e9bf674a2c2e083f22e2533b481177359c98","libm/src/math/expm1.rs":"124069f456c8ad331f265c7509d9e223b2a300e461bbfd3d6adfdcdd2ee5b8ac","libm/src/math/expm1f.rs":"18e2116d31ea8410051cc709b9d04b754b0e3ba6758ee1bf0b48749f4999b840","libm/src/math/expo2.rs":"4f4f9fecfccb43f30c2784aa7c0bb656754a52b8ab431f7d1b551c673ab133f1","libm/src/math/fabs.rs":"e6c7db39f98508098cdf64ac0c2f53866c466149a7490afb9fe22b44c4dd81b3","libm/src/math/fabsf.rs":"83a1f5f4d9ca899ba2b701d7332e18b40258b83e111db4c5d8fab2cc1be58aa3","libm/src/math/fdim.rs":"8ec091996005207297c2389ae563e1b18dbc6a9eac951de29a976c5cd7bc32a7","libm/src/math/fdimf.rs":"c7f3f2269834d55be26b6580ddc07c42531577955fa4de35bad1e2a361085614","libm/src/math/fenv.rs":"916ae11e4763588518d64dee82afb41be9d1ee38ecc0679c821d4e7e22cd3dc5","libm/src/math/floor.rs":"5050804cae173af6775c0678d6c1aafb5ca2b744bc8a2f50d9d03b95dcee1fb0","libm/src/math/floorf.rs":"c903e0c57bc60a888c513eb7a873a87a4759ba68fc791b6b931652f8ee74cc03","libm/src/math/fma.rs":"d88e01c2c2d11333dd49b61166caa036ff5f08f3a8c5973b9e3c9574bf2eb675","libm/src/math/fmaf.rs":"1db6ee0d47ddbdb441cfe167edf89b431239f5805708fd0376cf5c01349a4bd6","libm/src/math/fmax.rs":"f6c8e96a8b1a170648d2fa3513e7b6b459085d708c839869f82e305fe58fac37","libm/src/math/fmaxf.rs":"dff0025433232e8a5ec7bd54d847ccf596d762ea4e35f5c54fbaac9404d732fd","libm/src/math/fmin.rs":"95b6cb66ca0e0e22276f0bf88dbe8fb69796a69a196a7491bd4802efbcf2e298","libm/src/math/fminf.rs":"304bc839b15ea3d84e68d2af9f40524ec120d30a36a667b22fcb98a6c258f4c7","libm/src/math/fmod.rs":"a1c0550fc7df8164733d914e222ff0966a2ab886d6e75a1098f24fe0283ae227","libm/src/math/fmodf.rs":"ee51ed092c0eeb8195f35735ff725cfd46612e0d689a7c483538bd92fbe61828","libm/src/math/frexp.rs":"28af70026922a8ab979744c7ad4d8faba6079c4743b7eeb6d14c983a982fbbcc","libm/src/math/frexpf.rs":"2e2593ae8002ba420809ebfaf737ef001cdc912354be3d978a8c0cb930350d4d","libm/src/math/hypot.rs":"841131c4a0cea75bc8a86e29f3f6d0815a61fc99731c9984651ce83d3050d218","libm/src/math/hypotf.rs":"5f317323edc2eb699580fe54b074b7e570a7734d51a0a149c0b49b54470a836c","libm/src/math/ilogb.rs":"d178ad7ca3439f82d565962b143f20448e45b2e2c51357b127abaec683297e32","libm/src/math/ilogbf.rs":"00f2b1b0496e21c6a42d68aea74d7156fa2ff0a735741b9051f3ca1cf0f57586","libm/src/math/j0.rs":"9572b6396c489927d332d0e717920e61ec0618e5e9c31f7eeeec70f5e4abab06","libm/src/math/j0f.rs":"802c8254bded9b3afb6eea8b9af240038a5a4a5d811396729f69ca509e3e7d87","libm/src/math/j1.rs":"97b1af1611fa3d110c2b349ee8e4176100132ea1391b619086b47ac063b81803","libm/src/math/j1f.rs":"9c9b128752e8ea2e7d81b637ba84907ab54a545e7602c49167b313743927930b","libm/src/math/jn.rs":"847d122334e5707ad9627146cddccc082a1f2f5bcd3e5ef54399013a7007ce88","libm/src/math/jnf.rs":"4045076f7d1a1b89882ed60d4dd60a4cbbc66b85cfb90491378c8015effcc476","libm/src/math/k_cos.rs":"f34a69e44d6b8901b03b578a75972f438ab20a7b98a0903fc1903d6fde3899be","libm/src/math/k_cosf.rs":"8f7117ff21cebf8e890a5bcfd7ea858a94172f4172b79a66d53824c2cb0888b1","libm/src/math/k_expo2.rs":"eb4ca9e6a525b7ea6da868c3cb136896682cc46f8396ba2a2ebc3ae9e9ba54b0","libm/src/math/k_expo2f.rs":"d51ad5df61cb5d1258bdb90c52bfed4572bb446a9337de9c04411ed9454ae0cb","libm/src/math/k_sin.rs":"14b2aba6ca07150c92768b5a72acaf5cde6a11d6619e14896512a7ba242e289a","libm/src/math/k_sinf.rs":"2775fcc710807164e6f37a4f8da3c8143cd5f16e19ce7c31c5591522151d7a96","libm/src/math/k_tan.rs":"a72beae4ccd9631eeeb61d6365bbeecae81c8411f3120a999c515cca0d5ea5c5","libm/src/math/k_tanf.rs":"6a794be56fa4b2f60452b9bab19af01c388f174560acbf829a351378ea39495d","libm/src/math/ldexp.rs":"b647f0096e80e4d926d8dd18d294c892ee2cb1778effe2c5e1b2664ae5cb1a4e","libm/src/math/ldexpf.rs":"98743fad2cd97a7be496f40ba3157ac1438fce0d0c25d5ab90c3b8c71c3fd0ed","libm/src/math/lgamma.rs":"0edd18e4f96bfcbe8b1b5af3eeca5208cd6d2d479dfa5ad117c9dfeccecf614f","libm/src/math/lgamma_r.rs":"f44a37aeccd56559ef784ae8edf217d14ad5cc2d910f0a65e70ffc86d7dc23dd","libm/src/math/lgammaf.rs":"967845357758b868a571857ec001f9f9154001110b8e97c08b6d10586bed9c49","libm/src/math/lgammaf_r.rs":"7143016d60e11fa235d53968125e57231b1104ce52149b5e1eed39629e0d1ff0","libm/src/math/log.rs":"b5e0c5f30d9e94351488732801be3107c12b854c3f95ad37e256dd88eeca408f","libm/src/math/log10.rs":"3425ff8be001fd1646ba15e254eb6ef4bdc6ccaf0cbee27ddf1fa84e04178b90","libm/src/math/log10f.rs":"fee4f71879bc4c99259e68c0c641364901629fb29a8ebddfcc0d090102cceddd","libm/src/math/log1p.rs":"9cf400852f165e6be19b97036ae9521fb9ca857d0a9a91c117d9123221622185","libm/src/math/log1pf.rs":"2716e6d2afa271996b7c8f47fd9e4952c88f4c1fd8c07c3e8ce8c62794bf71d8","libm/src/math/log2.rs":"dbbbfbaaa8aa6a4dbefea554ea3983090a9691228b011910c751f6adca912c40","libm/src/math/log2f.rs":"92a90350d8edce21c31c285c3e620fca7c62a2366008921715945c2c73b5b79f","libm/src/math/logf.rs":"845342cffc34d3db1f5ec12d8e5b773cd5a79056e28662fcb9bcd80207596f50","libm/src/math/mod.rs":"9de65aedb36910356bc47d25b1468b40ab63faf7e319e599e478a239681bdf9c","libm/src/math/modf.rs":"d012ed5a708ef52b6d1313c22a46cadaf5764dde1220816e3df2f03a0fcc60ae","libm/src/math/modff.rs":"f8f1e4c27a85d2cdb3c8e74439d59ef64aa543b948f22c23227d02d8388d61c2","libm/src/math/nextafter.rs":"3282e7eef214a32736fb6928d490198ad394b26b402b45495115b104839eebfe","libm/src/math/nextafterf.rs":"0937dc8a8155c19842c12181e741cec1f7df1f7a00cee81fcb2475e2842761b7","libm/src/math/pow.rs":"17c38297c5bf99accd915f292b777f8716ecf328916297c8bb9dfde6fd8ce522","libm/src/math/powf.rs":"2c423a0ea57fdc4e20f3533f744c6e6288c998b4de8f2914fafaa0e78be81b04","libm/src/math/rem_pio2.rs":"3e53234977daf61c89c29c940791714aad2f676a6f38188c7d17543a2aa8806f","libm/src/math/rem_pio2_large.rs":"482f31ff4e4eacf885f6130ae26a1d59f76b382059d6c742f30e5036811d3ca8","libm/src/math/rem_pio2f.rs":"07fb48f6d5cbadfd32ce4124b2b74af98b8391a2a6f36ce2a7d32e4500cb65ac","libm/src/math/remainder.rs":"63865f4370853c476b45bb27a5c54a4072146aa4a626835ae5263871a4e7e5dc","libm/src/math/remainderf.rs":"dd3fa432dbda8f2135428198be7bd69c57f8d13df3f365b12f52bf6a82352ac4","libm/src/math/remquo.rs":"3cc0bf55069f165c4843f2c358b3a27279c01e8cdd99f9057a3f7f31f45408f2","libm/src/math/remquof.rs":"cc749e18ecb7e766b8b8eeabdbf89ac99087d3d587e71e30f690676a3d2c1f9b","libm/src/math/round.rs":"f10797ef15dd34a74e912ba8621d60bc0200c87b94308c9de3cc88d7aec4feb4","libm/src/math/roundf.rs":"27e37cfcf82373709e7debf9c0c18f7ed00ae0f5d97a214c388041f7a6996d35","libm/src/math/scalbn.rs":"b5c9d6d4177fe393cbfe1c634d75ce14b754f6cbce87c5bf979a9661491748a2","libm/src/math/scalbnf.rs":"4f198d06db1896386256fb9a5ac5b805b16b836226c18780a475cf18d7c1449c","libm/src/math/sin.rs":"bb483a2138ca779e03a191222636f0c60fd75a77a2a12f263bda4b6aa9136317","libm/src/math/sincos.rs":"1cf62a16c215e367f51078a3ba23a3f257682032a8f3c657293029a886b18d82","libm/src/math/sincosf.rs":"b0f589e6ada8215944d7784f420c6721c90387d799e349ce7676674f3c475e75","libm/src/math/sinf.rs":"dcddac1d56b084cbb8d0e019433c9c5fe2201d9b257a7dcf2f85c9a8f14b79cf","libm/src/math/sinh.rs":"d8ee4c7af883a526f36c1a6da13bb81fba9181b477e2f2538161a2bee97edc35","libm/src/math/sinhf.rs":"d06eb030ba9dbf7094df127262bfe99f149b4db49fa8ab8c15499660f1e46b26","libm/src/math/sqrt.rs":"824570a631c2542ccee68b65e3eb08fe79c037a29bbaaf54da5367e7b236124a","libm/src/math/sqrtf.rs":"4cf418d74f7751d522a642a9a8d6b86ee3472c6aaef44f0eb1bc26f4d8a90985","libm/src/math/tan.rs":"930ecedaadc60f704c2dfa4e15186f59713c1ba7d948529d215223b424827db5","libm/src/math/tanf.rs":"894156a3b107aee08461eb4e7e412fc049aa237d176ae705c6e3e2d7060d94e3","libm/src/math/tanh.rs":"f1f08eb98ed959a17370a7aaf0177be36e3764543424e78feb033ed3f5e8ec98","libm/src/math/tanhf.rs":"74027b0c672a4e64bdef6d7a3069b90caec50e1e7dbb2c12d2828f310502f41e","libm/src/math/tgamma.rs":"c889cfa49bbeb4dbb0941fe9fac3b4da7d5879dcf04a3b9bb6e56de529baf374","libm/src/math/tgammaf.rs":"0737b34777095d0e4d07fe533e8f105082dd4e8ece411bba6ae5993b45b9388c","libm/src/math/trunc.rs":"642264897cc1505e720c8cf313be81aa9fd53aae866644a2e988d01dbc77fd8a","libm/src/math/truncf.rs":"dee3607baf1af0f01deae46e429e097234c50b268eaefebbe716f19f38597900","src/arm.rs":"acf149932aa46a2755cf8cd2eb7d6ae249e46b1e10ad45ce5f924561945d1273","src/arm_linux.rs":"35a4cb7b75015543feb15b0c692da0faf0e6037d3b97a4a18067ba416eae1a70","src/float/add.rs":"3ec32ceaf470a89777b54f9cde61832fdadeade0f4894f268a949e968520bc57","src/float/cmp.rs":"79b1fdc8d5f943c4ad5ea4ad32623b18f63e17ac3852fbc64a4942228007e1fc","src/float/conv.rs":"e2b5e6fe398f35c7db4af62ba1fd79b39591fe1bfaf304ae825ed3c8cf902d9c","src/float/div.rs":"fe21115ecb1b3330569fd85cb51c650bf80683f152333db988d8e0d564a9ae11","src/float/extend.rs":"180b2e791c58e0526de0a798845c580ce3222c8a15c8665e6e6a4bf5cf1a34aa","src/float/mod.rs":"48d76632575789a6ecf99213b1ed38c21c86ad5a5c3fa33ccb31f77829271b79","src/float/mul.rs":"0d0c1f0c28c149ecadeafd459d3c4c9327e4cfcae2cba479957bb8010ef51a01","src/float/pow.rs":"2ada190738731eb6f24104f8fb8c4d6f03cfb16451536dbee32f2b33db0c4b19","src/float/sub.rs":"c2a87f4628f51d5d908d0f25b5d51ce0599dc559d5a72b20e131261f484d5848","src/float/trunc.rs":"d21d2a2f9a1918b4bbb594691e397972a7c04b74b2acf04016c55693abf6d24b","src/int/addsub.rs":"7ec45ce1ba15b56a5b7129d3e5722c4db764c6545306d3fa9090983bcabd6f17","src/int/leading_zeros.rs":"ccf5e9d098c80034dcf6e38437c9a2eb670fa8043558bbfb574f2293164729a6","src/int/mod.rs":"bab1b77535ceebdebb89fd4e59e7105f8c45347bb638351a626615b24544a0b1","src/int/mul.rs":"bb48d8fd42d8f9f5fe9271d8d0f7a92dbae320bf4346e19d1071eb2093cb8ed9","src/int/sdiv.rs":"ace4cb0ec388a38834e01cab2c5bc87182d31588dfc0b1ae117c11ed0c4781cf","src/int/shift.rs":"3967c28a8d61279546e91958d64745fec63f15aee9175eb0602cc6353830da6c","src/int/specialized_div_rem/asymmetric.rs":"27f5bf70a35109f9d4e4e1ad1e8003aa17da5a1e436bf3e63a493d7528a3a566","src/int/specialized_div_rem/binary_long.rs":"9f1ced81a394f000a21a329683144d68ee431a954136a3634eb55b1ee2cf6d51","src/int/specialized_div_rem/delegate.rs":"9df141af98e391361e25d71ae38d5e845a91d896edd2c041132fd46af8268e85","src/int/specialized_div_rem/mod.rs":"73c98b9f69cc9b101ae4c9081e82d66af1df4a58cf0c9bb2a8c8659265687f12","src/int/specialized_div_rem/norm_shift.rs":"3be7ee0dea545c1f702d9daf67dad2b624bf7b17b075c8b90d3d3f7b53df4c21","src/int/specialized_div_rem/trifecta.rs":"87eef69da255b809fd710b14f2eb3f9f59e3dac625f8564ebc8ba78f9763523b","src/int/udiv.rs":"3732b490a472505411577f008b92f489287745968ce6791665201201377d3475","src/lib.rs":"d0e85291d12a57c61791257e3adefb8f2222e1ba6f9e5cd4cf7fba59d26477f4","src/macros.rs":"de690dffc59a5884ed06c67d38f06c41ed02fcd6318189397a0d4aafbd375ad8","src/math.rs":"7cafdf3d65e083b31a9ceebab9510236b2c7290dbf1927f435d0f9b2d62d2a0b","src/mem/impls.rs":"a8d1c28a77d9b334872abbebfcba3fd1802175bef53c0b545e85242860698780","src/mem/mod.rs":"5034543d963149c14a6823bee32a1fb9dfd950c32153d37f97e9df1dc6c23129","src/mem/x86_64.rs":"9f740891f666acf384159128eef233d9e15c6120da8016370c6f9f05cc29d653","src/probestack.rs":"ef5c07e9b95de7b2b77a937789fcfefd9846274317489ad6d623e377c9888601","src/riscv.rs":"8aa8cde1106a179e9a37724193bc5cea5defe212eb38e3049c23b254578f78d4","src/x86.rs":"117b50d6725ee0af0a7b3d197ea580655561f66a870ebc450d96af22bf7f39f6","src/x86_64.rs":"4f16bc9fad7757d48a6da3a078c715dd3a22154aadb4f1998d4c1b5d91396f9e"},"package":"18cd7635fea7bb481ea543b392789844c1ad581299da70184c7175ce3af76603"} \ No newline at end of file diff --git a/vendor/compiler_builtins/Cargo.lock b/vendor/compiler_builtins/Cargo.lock index e184f7e20..a498ea0ea 100644 --- a/vendor/compiler_builtins/Cargo.lock +++ b/vendor/compiler_builtins/Cargo.lock @@ -4,13 +4,13 @@ version = 3 [[package]] name = "cc" -version = "1.0.70" +version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26a6ce4b6a484fa3edb70f7efa6fc430fd2b87285fe8b84304fd0936faa0dc0" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" [[package]] name = "compiler_builtins" -version = "0.1.73" +version = "0.1.82" dependencies = [ "cc", "rustc-std-workspace-core", diff --git a/vendor/compiler_builtins/Cargo.toml b/vendor/compiler_builtins/Cargo.toml index 765e99f94..13ec182df 100644 --- a/vendor/compiler_builtins/Cargo.toml +++ b/vendor/compiler_builtins/Cargo.toml @@ -11,7 +11,7 @@ [package] name = "compiler_builtins" -version = "0.1.73" +version = "0.1.82" authors = ["Jorge Aparicio "] links = "compiler-rt" include = [ diff --git a/vendor/compiler_builtins/LICENSE.txt b/vendor/compiler_builtins/LICENSE.txt new file mode 100644 index 000000000..92bbe113a --- /dev/null +++ b/vendor/compiler_builtins/LICENSE.txt @@ -0,0 +1,91 @@ +============================================================================== +compiler-builtins License +============================================================================== + +The compiler-builtins crate is dual licensed under both the University of +Illinois "BSD-Like" license and the MIT license. As a user of this code you may +choose to use it under either license. As a contributor, you agree to allow +your code to be used under both. + +Full text of the relevant licenses is included below. + +============================================================================== + +University of Illinois/NCSA +Open Source License + +Copyright (c) 2009-2016 by the contributors listed in CREDITS.TXT + +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== + +Copyright (c) 2009-2015 by the contributors listed in CREDITS.TXT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +============================================================================== +Copyrights and Licenses for Third Party Software Distributed with LLVM: +============================================================================== +The LLVM software contains code written by third parties. Such software will +have its own individual LICENSE.TXT file in the directory in which it appears. +This file will describe the copyrights, license, and restrictions which apply +to that code. + +The disclaimer of warranty in the University of Illinois Open Source License +applies to all code in the LLVM Distribution, and nothing in any of the +other licenses gives permission to use the names of the LLVM Team or the +University of Illinois to endorse or promote products derived from this +Software. + diff --git a/vendor/compiler_builtins/build.rs b/vendor/compiler_builtins/build.rs index 11deffb9c..73952bb9f 100644 --- a/vendor/compiler_builtins/build.rs +++ b/vendor/compiler_builtins/build.rs @@ -29,6 +29,7 @@ fn main() { || (target.contains("sgx") && target.contains("fortanix")) || target.contains("-none") || target.contains("nvptx") + || target.contains("uefi") { println!("cargo:rustc-cfg=feature=\"mem\""); } @@ -58,9 +59,11 @@ fn main() { // unlikely that the C is really that much better than our own Rust. // * nvptx - everything is bitcode, not compatible with mixed C/Rust // * riscv - the rust-lang/rust distribution container doesn't have a C - // compiler nor is cc-rs ready for compilation to riscv (at this - // time). This can probably be removed in the future - if !target.contains("wasm") && !target.contains("nvptx") && !target.starts_with("riscv") { + // compiler. + if !target.contains("wasm") + && !target.contains("nvptx") + && (!target.starts_with("riscv") || target.contains("xous")) + { #[cfg(feature = "c")] c::compile(&llvm_target, &target); } @@ -457,6 +460,7 @@ mod c { ("__fe_getround", "fp_mode.c"), ("__divtf3", "divtf3.c"), ("__trunctfdf2", "trunctfdf2.c"), + ("__trunctfsf2", "trunctfsf2.c"), ]); } diff --git a/vendor/compiler_builtins/libm/src/math/acosh.rs b/vendor/compiler_builtins/libm/src/math/acosh.rs index ac7a5f1c6..d1f5b9fa9 100644 --- a/vendor/compiler_builtins/libm/src/math/acosh.rs +++ b/vendor/compiler_builtins/libm/src/math/acosh.rs @@ -7,6 +7,7 @@ const LN2: f64 = 0.693147180559945309417232121458176568; /* 0x3fe62e42, 0xfefa3 /// Calculates the inverse hyperbolic cosine of `x`. /// Is defined as `log(x + sqrt(x*x-1))`. /// `x` must be a number greater than or equal to 1. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn acosh(x: f64) -> f64 { let u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/vendor/compiler_builtins/libm/src/math/acoshf.rs b/vendor/compiler_builtins/libm/src/math/acoshf.rs index 0879e1edb..ad3455fdd 100644 --- a/vendor/compiler_builtins/libm/src/math/acoshf.rs +++ b/vendor/compiler_builtins/libm/src/math/acoshf.rs @@ -7,6 +7,7 @@ const LN2: f32 = 0.693147180559945309417232121458176568; /// Calculates the inverse hyperbolic cosine of `x`. /// Is defined as `log(x + sqrt(x*x-1))`. /// `x` must be a number greater than or equal to 1. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn acoshf(x: f32) -> f32 { let u = x.to_bits(); let a = u & 0x7fffffff; diff --git a/vendor/compiler_builtins/libm/src/math/asinh.rs b/vendor/compiler_builtins/libm/src/math/asinh.rs index 14295357a..0abd80c2f 100644 --- a/vendor/compiler_builtins/libm/src/math/asinh.rs +++ b/vendor/compiler_builtins/libm/src/math/asinh.rs @@ -7,6 +7,7 @@ const LN2: f64 = 0.693147180559945309417232121458176568; /* 0x3fe62e42, 0xfefa3 /// /// Calculates the inverse hyperbolic sine of `x`. /// Is defined as `sgn(x)*log(|x|+sqrt(x*x+1))`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn asinh(mut x: f64) -> f64 { let mut u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/vendor/compiler_builtins/libm/src/math/asinhf.rs b/vendor/compiler_builtins/libm/src/math/asinhf.rs index e22a29132..09c77823e 100644 --- a/vendor/compiler_builtins/libm/src/math/asinhf.rs +++ b/vendor/compiler_builtins/libm/src/math/asinhf.rs @@ -7,6 +7,7 @@ const LN2: f32 = 0.693147180559945309417232121458176568; /// /// Calculates the inverse hyperbolic sine of `x`. /// Is defined as `sgn(x)*log(|x|+sqrt(x*x+1))`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn asinhf(mut x: f32) -> f32 { let u = x.to_bits(); let i = u & 0x7fffffff; diff --git a/vendor/compiler_builtins/libm/src/math/atanh.rs b/vendor/compiler_builtins/libm/src/math/atanh.rs index 79a989c42..b984c4ac6 100644 --- a/vendor/compiler_builtins/libm/src/math/atanh.rs +++ b/vendor/compiler_builtins/libm/src/math/atanh.rs @@ -5,6 +5,7 @@ use super::log1p; /// /// Calculates the inverse hyperbolic tangent of `x`. /// Is defined as `log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn atanh(x: f64) -> f64 { let u = x.to_bits(); let e = ((u >> 52) as usize) & 0x7ff; diff --git a/vendor/compiler_builtins/libm/src/math/atanhf.rs b/vendor/compiler_builtins/libm/src/math/atanhf.rs index 7b2f34d97..a1aa314a5 100644 --- a/vendor/compiler_builtins/libm/src/math/atanhf.rs +++ b/vendor/compiler_builtins/libm/src/math/atanhf.rs @@ -5,6 +5,7 @@ use super::log1pf; /// /// Calculates the inverse hyperbolic tangent of `x`. /// Is defined as `log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn atanhf(mut x: f32) -> f32 { let mut u = x.to_bits(); let sign = (u >> 31) != 0; diff --git a/vendor/compiler_builtins/libm/src/math/copysign.rs b/vendor/compiler_builtins/libm/src/math/copysign.rs index 1527fb6ea..1f4a35a33 100644 --- a/vendor/compiler_builtins/libm/src/math/copysign.rs +++ b/vendor/compiler_builtins/libm/src/math/copysign.rs @@ -2,6 +2,7 @@ /// /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn copysign(x: f64, y: f64) -> f64 { let mut ux = x.to_bits(); let uy = y.to_bits(); diff --git a/vendor/compiler_builtins/libm/src/math/copysignf.rs b/vendor/compiler_builtins/libm/src/math/copysignf.rs index 35148561a..6c346e3a5 100644 --- a/vendor/compiler_builtins/libm/src/math/copysignf.rs +++ b/vendor/compiler_builtins/libm/src/math/copysignf.rs @@ -2,6 +2,7 @@ /// /// Constructs a number with the magnitude (absolute value) of its /// first argument, `x`, and the sign of its second argument, `y`. +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn copysignf(x: f32, y: f32) -> f32 { let mut ux = x.to_bits(); let uy = y.to_bits(); diff --git a/vendor/compiler_builtins/libm/src/math/erf.rs b/vendor/compiler_builtins/libm/src/math/erf.rs index a2c617d34..5e21ba578 100644 --- a/vendor/compiler_builtins/libm/src/math/erf.rs +++ b/vendor/compiler_builtins/libm/src/math/erf.rs @@ -219,6 +219,7 @@ fn erfc2(ix: u32, mut x: f64) -> f64 { /// Calculates an approximation to the “error function”, which estimates /// the probability that an observation will fall within x standard /// deviations of the mean (assuming a normal distribution). +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn erf(x: f64) -> f64 { let r: f64; let s: f64; diff --git a/vendor/compiler_builtins/libm/src/math/erff.rs b/vendor/compiler_builtins/libm/src/math/erff.rs index 384052293..f74d4b632 100644 --- a/vendor/compiler_builtins/libm/src/math/erff.rs +++ b/vendor/compiler_builtins/libm/src/math/erff.rs @@ -130,6 +130,7 @@ fn erfc2(mut ix: u32, mut x: f32) -> f32 { /// Calculates an approximation to the “error function”, which estimates /// the probability that an observation will fall within x standard /// deviations of the mean (assuming a normal distribution). +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn erff(x: f32) -> f32 { let r: f32; let s: f32; diff --git a/vendor/compiler_builtins/libm/src/math/exp10.rs b/vendor/compiler_builtins/libm/src/math/exp10.rs index 9537f76f1..559930e10 100644 --- a/vendor/compiler_builtins/libm/src/math/exp10.rs +++ b/vendor/compiler_builtins/libm/src/math/exp10.rs @@ -6,16 +6,17 @@ const P10: &[f64] = &[ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, ]; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn exp10(x: f64) -> f64 { let (mut y, n) = modf(x); let u: u64 = n.to_bits(); /* fabs(n) < 16 without raising invalid on nan */ if (u >> 52 & 0x7ff) < 0x3ff + 4 { if y == 0.0 { - return P10[((n as isize) + 15) as usize]; + return i!(P10, ((n as isize) + 15) as usize); } y = exp2(LN10 * y); - return y * P10[((n as isize) + 15) as usize]; + return y * i!(P10, ((n as isize) + 15) as usize); } return pow(10.0, x); } diff --git a/vendor/compiler_builtins/libm/src/math/exp10f.rs b/vendor/compiler_builtins/libm/src/math/exp10f.rs index d45fff36e..1279bc6c5 100644 --- a/vendor/compiler_builtins/libm/src/math/exp10f.rs +++ b/vendor/compiler_builtins/libm/src/math/exp10f.rs @@ -6,16 +6,17 @@ const P10: &[f32] = &[ 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, ]; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn exp10f(x: f32) -> f32 { let (mut y, n) = modff(x); let u = n.to_bits(); /* fabsf(n) < 8 without raising invalid on nan */ if (u >> 23 & 0xff) < 0x7f + 3 { if y == 0.0 { - return P10[((n as isize) + 7) as usize]; + return i!(P10, ((n as isize) + 7) as usize); } y = exp2f(LN10_F32 * y); - return y * P10[((n as isize) + 7) as usize]; + return y * i!(P10, ((n as isize) + 7) as usize); } return exp2(LN10_F64 * (x as f64)) as f32; } diff --git a/vendor/compiler_builtins/libm/src/math/fenv.rs b/vendor/compiler_builtins/libm/src/math/fenv.rs index 652e60324..c91272e82 100644 --- a/vendor/compiler_builtins/libm/src/math/fenv.rs +++ b/vendor/compiler_builtins/libm/src/math/fenv.rs @@ -5,7 +5,6 @@ pub(crate) const FE_UNDERFLOW: i32 = 0; pub(crate) const FE_INEXACT: i32 = 0; pub(crate) const FE_TONEAREST: i32 = 0; -pub(crate) const FE_TOWARDZERO: i32 = 0; #[inline] pub(crate) fn feclearexcept(_mask: i32) -> i32 { @@ -26,8 +25,3 @@ pub(crate) fn fetestexcept(_mask: i32) -> i32 { pub(crate) fn fegetround() -> i32 { FE_TONEAREST } - -#[inline] -pub(crate) fn fesetround(_r: i32) -> i32 { - 0 -} diff --git a/vendor/compiler_builtins/libm/src/math/fmaf.rs b/vendor/compiler_builtins/libm/src/math/fmaf.rs index 03d371c55..2848f2aee 100644 --- a/vendor/compiler_builtins/libm/src/math/fmaf.rs +++ b/vendor/compiler_builtins/libm/src/math/fmaf.rs @@ -29,8 +29,7 @@ use core::f32; use core::ptr::read_volatile; use super::fenv::{ - feclearexcept, fegetround, feraiseexcept, fesetround, fetestexcept, FE_INEXACT, FE_TONEAREST, - FE_TOWARDZERO, FE_UNDERFLOW, + feclearexcept, fegetround, feraiseexcept, fetestexcept, FE_INEXACT, FE_TONEAREST, FE_UNDERFLOW, }; /* @@ -91,16 +90,28 @@ pub fn fmaf(x: f32, y: f32, mut z: f32) -> f32 { * If result is inexact, and exactly halfway between two float values, * we need to adjust the low-order bit in the direction of the error. */ - fesetround(FE_TOWARDZERO); - // prevent `vxy + z` from being CSE'd with `xy + z` above - let vxy: f64 = unsafe { read_volatile(&xy) }; - let mut adjusted_result: f64 = vxy + z as f64; - fesetround(FE_TONEAREST); - if result == adjusted_result { - ui = adjusted_result.to_bits(); + let neg = ui >> 63 != 0; + let err = if neg == (z as f64 > xy) { + xy - result + z as f64 + } else { + z as f64 - result + xy + }; + if neg == (err < 0.0) { ui += 1; - adjusted_result = f64::from_bits(ui); + } else { + ui -= 1; + } + f64::from_bits(ui) as f32 +} + +#[cfg(test)] +mod tests { + #[test] + fn issue_263() { + let a = f32::from_bits(1266679807); + let b = f32::from_bits(1300234242); + let c = f32::from_bits(1115553792); + let expected = f32::from_bits(1501560833); + assert_eq!(super::fmaf(a, b, c), expected); } - z = adjusted_result as f32; - z } diff --git a/vendor/compiler_builtins/libm/src/math/ilogb.rs b/vendor/compiler_builtins/libm/src/math/ilogb.rs index 0a380b7ef..7d74dcfb6 100644 --- a/vendor/compiler_builtins/libm/src/math/ilogb.rs +++ b/vendor/compiler_builtins/libm/src/math/ilogb.rs @@ -1,6 +1,7 @@ const FP_ILOGBNAN: i32 = -1 - 0x7fffffff; const FP_ILOGB0: i32 = FP_ILOGBNAN; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn ilogb(x: f64) -> i32 { let mut i: u64 = x.to_bits(); let e = ((i >> 52) & 0x7ff) as i32; diff --git a/vendor/compiler_builtins/libm/src/math/ilogbf.rs b/vendor/compiler_builtins/libm/src/math/ilogbf.rs index b384fa4b2..0fa58748c 100644 --- a/vendor/compiler_builtins/libm/src/math/ilogbf.rs +++ b/vendor/compiler_builtins/libm/src/math/ilogbf.rs @@ -1,6 +1,7 @@ const FP_ILOGBNAN: i32 = -1 - 0x7fffffff; const FP_ILOGB0: i32 = FP_ILOGBNAN; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn ilogbf(x: f32) -> i32 { let mut i = x.to_bits(); let e = ((i >> 23) & 0xff) as i32; diff --git a/vendor/compiler_builtins/libm/src/math/lgamma.rs b/vendor/compiler_builtins/libm/src/math/lgamma.rs index 5bc87e85e..a08bc5b64 100644 --- a/vendor/compiler_builtins/libm/src/math/lgamma.rs +++ b/vendor/compiler_builtins/libm/src/math/lgamma.rs @@ -1,5 +1,6 @@ use super::lgamma_r; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn lgamma(x: f64) -> f64 { lgamma_r(x).0 } diff --git a/vendor/compiler_builtins/libm/src/math/lgamma_r.rs b/vendor/compiler_builtins/libm/src/math/lgamma_r.rs index 9533e882c..b26177e6e 100644 --- a/vendor/compiler_builtins/libm/src/math/lgamma_r.rs +++ b/vendor/compiler_builtins/libm/src/math/lgamma_r.rs @@ -152,7 +152,7 @@ fn sin_pi(mut x: f64) -> f64 { x = 2.0 * (x * 0.5 - floor(x * 0.5)); /* x mod 2.0 */ n = (x * 4.0) as i32; - n = (n + 1) / 2; + n = div!(n + 1, 2); x -= (n as f64) * 0.5; x *= PI; @@ -164,6 +164,7 @@ fn sin_pi(mut x: f64) -> f64 { } } +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn lgamma_r(mut x: f64) -> (f64, i32) { let u: u64 = x.to_bits(); let mut t: f64; diff --git a/vendor/compiler_builtins/libm/src/math/lgammaf.rs b/vendor/compiler_builtins/libm/src/math/lgammaf.rs index dfdc87f96..a9c2da75b 100644 --- a/vendor/compiler_builtins/libm/src/math/lgammaf.rs +++ b/vendor/compiler_builtins/libm/src/math/lgammaf.rs @@ -1,5 +1,6 @@ use super::lgammaf_r; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn lgammaf(x: f32) -> f32 { lgammaf_r(x).0 } diff --git a/vendor/compiler_builtins/libm/src/math/lgammaf_r.rs b/vendor/compiler_builtins/libm/src/math/lgammaf_r.rs index c5e559f46..723c90daf 100644 --- a/vendor/compiler_builtins/libm/src/math/lgammaf_r.rs +++ b/vendor/compiler_builtins/libm/src/math/lgammaf_r.rs @@ -88,7 +88,7 @@ fn sin_pi(mut x: f32) -> f32 { x = 2.0 * (x * 0.5 - floorf(x * 0.5)); /* x mod 2.0 */ n = (x * 4.0) as isize; - n = (n + 1) / 2; + n = div!(n + 1, 2); y = (x as f64) - (n as f64) * 0.5; y *= 3.14159265358979323846; match n { @@ -99,6 +99,7 @@ fn sin_pi(mut x: f32) -> f32 { } } +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn lgammaf_r(mut x: f32) -> (f32, i32) { let u = x.to_bits(); let mut t: f32; diff --git a/vendor/compiler_builtins/libm/src/math/rem_pio2_large.rs b/vendor/compiler_builtins/libm/src/math/rem_pio2_large.rs index 65473f0ab..db97a39d4 100644 --- a/vendor/compiler_builtins/libm/src/math/rem_pio2_large.rs +++ b/vendor/compiler_builtins/libm/src/math/rem_pio2_large.rs @@ -27,7 +27,7 @@ const INIT_JK: [usize; 4] = [3, 4, 4, 6]; // // NB: This table must have at least (e0-3)/24 + jk terms. // For quad precision (e0 <= 16360, jk = 6), this is 686. -#[cfg(target_pointer_width = "32")] +#[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] const IPIO2: [i32; 66] = [ 0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, 0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, 0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, diff --git a/vendor/compiler_builtins/libm/src/math/sincos.rs b/vendor/compiler_builtins/libm/src/math/sincos.rs index 4ab588412..ff5d87a1c 100644 --- a/vendor/compiler_builtins/libm/src/math/sincos.rs +++ b/vendor/compiler_builtins/libm/src/math/sincos.rs @@ -12,6 +12,7 @@ use super::{get_high_word, k_cos, k_sin, rem_pio2}; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn sincos(x: f64) -> (f64, f64) { let s: f64; let c: f64; diff --git a/vendor/compiler_builtins/libm/src/math/sincosf.rs b/vendor/compiler_builtins/libm/src/math/sincosf.rs index 5304e8ca0..9a4c36104 100644 --- a/vendor/compiler_builtins/libm/src/math/sincosf.rs +++ b/vendor/compiler_builtins/libm/src/math/sincosf.rs @@ -23,6 +23,7 @@ const S2PIO2: f32 = 2.0 * PI_2; /* 0x400921FB, 0x54442D18 */ const S3PIO2: f32 = 3.0 * PI_2; /* 0x4012D97C, 0x7F3321D2 */ const S4PIO2: f32 = 4.0 * PI_2; /* 0x401921FB, 0x54442D18 */ +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn sincosf(x: f32) -> (f32, f32) { let s: f32; let c: f32; diff --git a/vendor/compiler_builtins/libm/src/math/tgamma.rs b/vendor/compiler_builtins/libm/src/math/tgamma.rs index f8ccf669a..e64eff61f 100644 --- a/vendor/compiler_builtins/libm/src/math/tgamma.rs +++ b/vendor/compiler_builtins/libm/src/math/tgamma.rs @@ -38,7 +38,7 @@ fn sinpi(mut x: f64) -> f64 { /* reduce x into [-.25,.25] */ n = (4.0 * x) as isize; - n = (n + 1) / 2; + n = div!(n + 1, 2); x -= (n as f64) * 0.5; x *= PI; @@ -118,18 +118,19 @@ fn s(x: f64) -> f64 { /* to avoid overflow handle large x differently */ if x < 8.0 { for i in (0..=N).rev() { - num = num * x + SNUM[i]; - den = den * x + SDEN[i]; + num = num * x + i!(SNUM, i); + den = den * x + i!(SDEN, i); } } else { for i in 0..=N { - num = num / x + SNUM[i]; - den = den / x + SDEN[i]; + num = num / x + i!(SNUM, i); + den = den / x + i!(SDEN, i); } } return num / den; } +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn tgamma(mut x: f64) -> f64 { let u: u64 = x.to_bits(); let absx: f64; @@ -157,7 +158,7 @@ pub fn tgamma(mut x: f64) -> f64 { return 0.0 / 0.0; } if x <= FACT.len() as f64 { - return FACT[(x as usize) - 1]; + return i!(FACT, (x as usize) - 1); } } diff --git a/vendor/compiler_builtins/libm/src/math/tgammaf.rs b/vendor/compiler_builtins/libm/src/math/tgammaf.rs index a8f161f0c..23e3814f9 100644 --- a/vendor/compiler_builtins/libm/src/math/tgammaf.rs +++ b/vendor/compiler_builtins/libm/src/math/tgammaf.rs @@ -1,5 +1,6 @@ use super::tgamma; +#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn tgammaf(x: f32) -> f32 { tgamma(x as f64) as f32 } diff --git a/vendor/compiler_builtins/src/arm.rs b/vendor/compiler_builtins/src/arm.rs index 9c1b6ad12..e517a9ef3 100644 --- a/vendor/compiler_builtins/src/arm.rs +++ b/vendor/compiler_builtins/src/arm.rs @@ -22,6 +22,7 @@ intrinsics! { // custom calling convention which can't be implemented using a normal Rust function. #[naked] #[cfg(not(target_env = "msvc"))] + #[cfg_attr(all(not(windows), not(target_vendor="apple")), linkage = "weak")] pub unsafe extern "C" fn __aeabi_uidivmod() { core::arch::asm!( "push {{lr}}", @@ -36,6 +37,7 @@ intrinsics! { } #[naked] + #[cfg_attr(all(not(windows), not(target_vendor="apple")), linkage = "weak")] pub unsafe extern "C" fn __aeabi_uldivmod() { core::arch::asm!( "push {{r4, lr}}", @@ -52,6 +54,7 @@ intrinsics! { } #[naked] + #[cfg_attr(all(not(windows), not(target_vendor="apple")), linkage = "weak")] pub unsafe extern "C" fn __aeabi_idivmod() { core::arch::asm!( "push {{r0, r1, r4, lr}}", @@ -65,6 +68,7 @@ intrinsics! { } #[naked] + #[cfg_attr(all(not(windows), not(target_vendor="apple")), linkage = "weak")] pub unsafe extern "C" fn __aeabi_ldivmod() { core::arch::asm!( "push {{r4, lr}}", diff --git a/vendor/compiler_builtins/src/arm_linux.rs b/vendor/compiler_builtins/src/arm_linux.rs index 8fe09485b..8f22eb628 100644 --- a/vendor/compiler_builtins/src/arm_linux.rs +++ b/vendor/compiler_builtins/src/arm_linux.rs @@ -55,7 +55,7 @@ fn insert_aligned(aligned: u32, val: u32, shift: u32, mask: u32) -> u32 { } // Generic atomic read-modify-write operation -unsafe fn atomic_rmw u32>(ptr: *mut T, f: F) -> u32 { +unsafe fn atomic_rmw u32, G: Fn(u32, u32) -> u32>(ptr: *mut T, f: F, g: G) -> u32 { let aligned_ptr = align_ptr(ptr); let (shift, mask) = get_shift_mask(ptr); @@ -65,7 +65,7 @@ unsafe fn atomic_rmw u32>(ptr: *mut T, f: F) -> u32 { let newval = f(curval); let newval_aligned = insert_aligned(curval_aligned, newval, shift, mask); if __kuser_cmpxchg(curval_aligned, newval_aligned, aligned_ptr) { - return curval; + return g(curval, newval); } } } @@ -89,13 +89,21 @@ unsafe fn atomic_cmpxchg(ptr: *mut T, oldval: u32, newval: u32) -> u32 { } macro_rules! atomic_rmw { - ($name:ident, $ty:ty, $op:expr) => { + ($name:ident, $ty:ty, $op:expr, $fetch:expr) => { intrinsics! { pub unsafe extern "C" fn $name(ptr: *mut $ty, val: $ty) -> $ty { - atomic_rmw(ptr, |x| $op(x as $ty, val) as u32) as $ty + atomic_rmw(ptr, |x| $op(x as $ty, val) as u32, |old, new| $fetch(old, new)) as $ty } } }; + + (@old $name:ident, $ty:ty, $op:expr) => { + atomic_rmw!($name, $ty, $op, |old, _| old); + }; + + (@new $name:ident, $ty:ty, $op:expr) => { + atomic_rmw!($name, $ty, $op, |_, new| new); + }; } macro_rules! atomic_cmpxchg { ($name:ident, $ty:ty) => { @@ -107,101 +115,129 @@ macro_rules! atomic_cmpxchg { }; } -atomic_rmw!(__sync_fetch_and_add_1, u8, |a: u8, b: u8| a.wrapping_add(b)); -atomic_rmw!(__sync_fetch_and_add_2, u16, |a: u16, b: u16| a +atomic_rmw!(@old __sync_fetch_and_add_1, u8, |a: u8, b: u8| a.wrapping_add(b)); +atomic_rmw!(@old __sync_fetch_and_add_2, u16, |a: u16, b: u16| a + .wrapping_add(b)); +atomic_rmw!(@old __sync_fetch_and_add_4, u32, |a: u32, b: u32| a + .wrapping_add(b)); + +atomic_rmw!(@new __sync_add_and_fetch_1, u8, |a: u8, b: u8| a.wrapping_add(b)); +atomic_rmw!(@new __sync_add_and_fetch_2, u16, |a: u16, b: u16| a .wrapping_add(b)); -atomic_rmw!(__sync_fetch_and_add_4, u32, |a: u32, b: u32| a +atomic_rmw!(@new __sync_add_and_fetch_4, u32, |a: u32, b: u32| a .wrapping_add(b)); -atomic_rmw!(__sync_fetch_and_sub_1, u8, |a: u8, b: u8| a.wrapping_sub(b)); -atomic_rmw!(__sync_fetch_and_sub_2, u16, |a: u16, b: u16| a +atomic_rmw!(@old __sync_fetch_and_sub_1, u8, |a: u8, b: u8| a.wrapping_sub(b)); +atomic_rmw!(@old __sync_fetch_and_sub_2, u16, |a: u16, b: u16| a .wrapping_sub(b)); -atomic_rmw!(__sync_fetch_and_sub_4, u32, |a: u32, b: u32| a +atomic_rmw!(@old __sync_fetch_and_sub_4, u32, |a: u32, b: u32| a .wrapping_sub(b)); -atomic_rmw!(__sync_fetch_and_and_1, u8, |a: u8, b: u8| a & b); -atomic_rmw!(__sync_fetch_and_and_2, u16, |a: u16, b: u16| a & b); -atomic_rmw!(__sync_fetch_and_and_4, u32, |a: u32, b: u32| a & b); +atomic_rmw!(@new __sync_sub_and_fetch_1, u8, |a: u8, b: u8| a.wrapping_sub(b)); +atomic_rmw!(@new __sync_sub_and_fetch_2, u16, |a: u16, b: u16| a + .wrapping_sub(b)); +atomic_rmw!(@new __sync_sub_and_fetch_4, u32, |a: u32, b: u32| a + .wrapping_sub(b)); + +atomic_rmw!(@old __sync_fetch_and_and_1, u8, |a: u8, b: u8| a & b); +atomic_rmw!(@old __sync_fetch_and_and_2, u16, |a: u16, b: u16| a & b); +atomic_rmw!(@old __sync_fetch_and_and_4, u32, |a: u32, b: u32| a & b); + +atomic_rmw!(@new __sync_and_and_fetch_1, u8, |a: u8, b: u8| a & b); +atomic_rmw!(@new __sync_and_and_fetch_2, u16, |a: u16, b: u16| a & b); +atomic_rmw!(@new __sync_and_and_fetch_4, u32, |a: u32, b: u32| a & b); + +atomic_rmw!(@old __sync_fetch_and_or_1, u8, |a: u8, b: u8| a | b); +atomic_rmw!(@old __sync_fetch_and_or_2, u16, |a: u16, b: u16| a | b); +atomic_rmw!(@old __sync_fetch_and_or_4, u32, |a: u32, b: u32| a | b); + +atomic_rmw!(@new __sync_or_and_fetch_1, u8, |a: u8, b: u8| a | b); +atomic_rmw!(@new __sync_or_and_fetch_2, u16, |a: u16, b: u16| a | b); +atomic_rmw!(@new __sync_or_and_fetch_4, u32, |a: u32, b: u32| a | b); + +atomic_rmw!(@old __sync_fetch_and_xor_1, u8, |a: u8, b: u8| a ^ b); +atomic_rmw!(@old __sync_fetch_and_xor_2, u16, |a: u16, b: u16| a ^ b); +atomic_rmw!(@old __sync_fetch_and_xor_4, u32, |a: u32, b: u32| a ^ b); -atomic_rmw!(__sync_fetch_and_or_1, u8, |a: u8, b: u8| a | b); -atomic_rmw!(__sync_fetch_and_or_2, u16, |a: u16, b: u16| a | b); -atomic_rmw!(__sync_fetch_and_or_4, u32, |a: u32, b: u32| a | b); +atomic_rmw!(@new __sync_xor_and_fetch_1, u8, |a: u8, b: u8| a ^ b); +atomic_rmw!(@new __sync_xor_and_fetch_2, u16, |a: u16, b: u16| a ^ b); +atomic_rmw!(@new __sync_xor_and_fetch_4, u32, |a: u32, b: u32| a ^ b); -atomic_rmw!(__sync_fetch_and_xor_1, u8, |a: u8, b: u8| a ^ b); -atomic_rmw!(__sync_fetch_and_xor_2, u16, |a: u16, b: u16| a ^ b); -atomic_rmw!(__sync_fetch_and_xor_4, u32, |a: u32, b: u32| a ^ b); +atomic_rmw!(@old __sync_fetch_and_nand_1, u8, |a: u8, b: u8| !(a & b)); +atomic_rmw!(@old __sync_fetch_and_nand_2, u16, |a: u16, b: u16| !(a & b)); +atomic_rmw!(@old __sync_fetch_and_nand_4, u32, |a: u32, b: u32| !(a & b)); -atomic_rmw!(__sync_fetch_and_nand_1, u8, |a: u8, b: u8| !(a & b)); -atomic_rmw!(__sync_fetch_and_nand_2, u16, |a: u16, b: u16| !(a & b)); -atomic_rmw!(__sync_fetch_and_nand_4, u32, |a: u32, b: u32| !(a & b)); +atomic_rmw!(@new __sync_nand_and_fetch_1, u8, |a: u8, b: u8| !(a & b)); +atomic_rmw!(@new __sync_nand_and_fetch_2, u16, |a: u16, b: u16| !(a & b)); +atomic_rmw!(@new __sync_nand_and_fetch_4, u32, |a: u32, b: u32| !(a & b)); -atomic_rmw!(__sync_fetch_and_max_1, i8, |a: i8, b: i8| if a > b { +atomic_rmw!(@old __sync_fetch_and_max_1, i8, |a: i8, b: i8| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_max_2, i16, |a: i16, b: i16| if a > b { +atomic_rmw!(@old __sync_fetch_and_max_2, i16, |a: i16, b: i16| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_max_4, i32, |a: i32, b: i32| if a > b { +atomic_rmw!(@old __sync_fetch_and_max_4, i32, |a: i32, b: i32| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umax_1, u8, |a: u8, b: u8| if a > b { +atomic_rmw!(@old __sync_fetch_and_umax_1, u8, |a: u8, b: u8| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umax_2, u16, |a: u16, b: u16| if a > b { +atomic_rmw!(@old __sync_fetch_and_umax_2, u16, |a: u16, b: u16| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umax_4, u32, |a: u32, b: u32| if a > b { +atomic_rmw!(@old __sync_fetch_and_umax_4, u32, |a: u32, b: u32| if a > b { a } else { b }); -atomic_rmw!(__sync_fetch_and_min_1, i8, |a: i8, b: i8| if a < b { +atomic_rmw!(@old __sync_fetch_and_min_1, i8, |a: i8, b: i8| if a < b { a } else { b }); -atomic_rmw!(__sync_fetch_and_min_2, i16, |a: i16, b: i16| if a < b { +atomic_rmw!(@old __sync_fetch_and_min_2, i16, |a: i16, b: i16| if a < b { a } else { b }); -atomic_rmw!(__sync_fetch_and_min_4, i32, |a: i32, b: i32| if a < b { +atomic_rmw!(@old __sync_fetch_and_min_4, i32, |a: i32, b: i32| if a < b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umin_1, u8, |a: u8, b: u8| if a < b { +atomic_rmw!(@old __sync_fetch_and_umin_1, u8, |a: u8, b: u8| if a < b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umin_2, u16, |a: u16, b: u16| if a < b { +atomic_rmw!(@old __sync_fetch_and_umin_2, u16, |a: u16, b: u16| if a < b { a } else { b }); -atomic_rmw!(__sync_fetch_and_umin_4, u32, |a: u32, b: u32| if a < b { +atomic_rmw!(@old __sync_fetch_and_umin_4, u32, |a: u32, b: u32| if a < b { a } else { b }); -atomic_rmw!(__sync_lock_test_and_set_1, u8, |_: u8, b: u8| b); -atomic_rmw!(__sync_lock_test_and_set_2, u16, |_: u16, b: u16| b); -atomic_rmw!(__sync_lock_test_and_set_4, u32, |_: u32, b: u32| b); +atomic_rmw!(@old __sync_lock_test_and_set_1, u8, |_: u8, b: u8| b); +atomic_rmw!(@old __sync_lock_test_and_set_2, u16, |_: u16, b: u16| b); +atomic_rmw!(@old __sync_lock_test_and_set_4, u32, |_: u32, b: u32| b); atomic_cmpxchg!(__sync_val_compare_and_swap_1, u8); atomic_cmpxchg!(__sync_val_compare_and_swap_2, u16); diff --git a/vendor/compiler_builtins/src/float/conv.rs b/vendor/compiler_builtins/src/float/conv.rs index 07b58f3d2..19fdc2fdc 100644 --- a/vendor/compiler_builtins/src/float/conv.rs +++ b/vendor/compiler_builtins/src/float/conv.rs @@ -13,7 +13,7 @@ mod int_to_float { let a = (i << n) >> 8; // Significant bits, with bit 24 still in tact. let b = (i << n) << 24; // Insignificant bits, only relevant for rounding. let m = a + ((b - (b >> 31 & !a)) >> 31); // Add one when we need to round up. Break ties to even. - let e = 157 - n as u32; // Exponent plus 127, minus one. + let e = 157 - n; // Exponent plus 127, minus one. (e << 23) + m // + not |, so the mantissa can overflow into the exponent. } @@ -42,8 +42,8 @@ mod int_to_float { return 0; } let n = i.leading_zeros(); - let a = ((i << n) >> 11) as u64; // Significant bits, with bit 53 still in tact. - let b = ((i << n) << 53) as u64; // Insignificant bits, only relevant for rounding. + let a = (i << n) >> 11; // Significant bits, with bit 53 still in tact. + let b = (i << n) << 53; // Insignificant bits, only relevant for rounding. let m = a + ((b - (b >> 63 & !a)) >> 63); // Add one when we need to round up. Break ties to even. let e = 1085 - n as u64; // Exponent plus 1023, minus one. (e << 52) + m // + not |, so the mantissa can overflow into the exponent. @@ -92,12 +92,12 @@ intrinsics! { f64::from_bits(int_to_float::u64_to_f64_bits(i)) } - #[cfg_attr(not(target_feature = "llvm14-builtins-abi"), unadjusted_on_win64)] + #[cfg_attr(any(not(target_feature = "llvm14-builtins-abi"), target_os = "uefi"), unadjusted_on_win64)] pub extern "C" fn __floatuntisf(i: u128) -> f32 { f32::from_bits(int_to_float::u128_to_f32_bits(i)) } - #[cfg_attr(not(target_feature = "llvm14-builtins-abi"), unadjusted_on_win64)] + #[cfg_attr(any(not(target_feature = "llvm14-builtins-abi"), target_os = "uefi"), unadjusted_on_win64)] pub extern "C" fn __floatuntidf(i: u128) -> f64 { f64::from_bits(int_to_float::u128_to_f64_bits(i)) } @@ -129,13 +129,13 @@ intrinsics! { f64::from_bits(int_to_float::u64_to_f64_bits(i.unsigned_abs()) | sign_bit) } - #[cfg_attr(not(target_feature = "llvm14-builtins-abi"), unadjusted_on_win64)] + #[cfg_attr(any(not(target_feature = "llvm14-builtins-abi"), target_os = "uefi"), unadjusted_on_win64)] pub extern "C" fn __floattisf(i: i128) -> f32 { let sign_bit = ((i >> 127) as u32) << 31; f32::from_bits(int_to_float::u128_to_f32_bits(i.unsigned_abs()) | sign_bit) } - #[cfg_attr(not(target_feature = "llvm14-builtins-abi"), unadjusted_on_win64)] + #[cfg_attr(any(not(target_feature = "llvm14-builtins-abi"), target_os = "uefi"), unadjusted_on_win64)] pub extern "C" fn __floattidf(i: i128) -> f64 { let sign_bit = ((i >> 127) as u64) << 63; f64::from_bits(int_to_float::u128_to_f64_bits(i.unsigned_abs()) | sign_bit) diff --git a/vendor/compiler_builtins/src/float/div.rs b/vendor/compiler_builtins/src/float/div.rs index 528a8368d..c2d6c07e7 100644 --- a/vendor/compiler_builtins/src/float/div.rs +++ b/vendor/compiler_builtins/src/float/div.rs @@ -135,11 +135,11 @@ where let mut correction: u32 = negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32); - reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32; + reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) >> 31) as u32; correction = negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32); - reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32; + reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) >> 31) as u32; correction = negate_u32(((reciprocal as u64).wrapping_mul(q31b as u64) >> 32) as u32); - reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) as u64 >> 31) as u32; + reciprocal = ((reciprocal as u64).wrapping_mul(correction as u64) >> 31) as u32; // Exhaustive testing shows that the error in reciprocal after three steps // is in the interval [-0x1.f58108p-31, 0x1.d0e48cp-29], in line with our diff --git a/vendor/compiler_builtins/src/int/specialized_div_rem/mod.rs b/vendor/compiler_builtins/src/int/specialized_div_rem/mod.rs index 6ec4675df..77034eb54 100644 --- a/vendor/compiler_builtins/src/int/specialized_div_rem/mod.rs +++ b/vendor/compiler_builtins/src/int/specialized_div_rem/mod.rs @@ -72,7 +72,10 @@ mod asymmetric; /// impossible to reach by Rust users, unless `compiler-builtins` public division functions or /// `core/std::unchecked_div/rem` are directly used without a zero check in front. fn zero_div_fn() -> ! { - unsafe { core::hint::unreachable_unchecked() } + // Calling the intrinsic directly, to avoid the `assert_unsafe_precondition` that cannot be used + // here because it involves non-`inline` functions + // (https://github.com/rust-lang/compiler-builtins/issues/491). + unsafe { core::intrinsics::unreachable() } } const USE_LZ: bool = { diff --git a/vendor/compiler_builtins/src/lib.rs b/vendor/compiler_builtins/src/lib.rs index 009923d27..e7bc61e4c 100644 --- a/vendor/compiler_builtins/src/lib.rs +++ b/vendor/compiler_builtins/src/lib.rs @@ -6,6 +6,7 @@ #![feature(compiler_builtins)] #![feature(core_ffi_c)] #![feature(core_intrinsics)] +#![feature(inline_const)] #![feature(lang_items)] #![feature(linkage)] #![feature(naked_functions)] @@ -45,6 +46,7 @@ pub mod int; all(target_family = "wasm", target_os = "unknown"), all(target_arch = "x86_64", target_os = "uefi"), all(target_arch = "arm", target_os = "none"), + target_os = "xous", all(target_vendor = "fortanix", target_env = "sgx") ))] pub mod math; diff --git a/vendor/compiler_builtins/src/macros.rs b/vendor/compiler_builtins/src/macros.rs index 518a18d4d..477c25684 100644 --- a/vendor/compiler_builtins/src/macros.rs +++ b/vendor/compiler_builtins/src/macros.rs @@ -174,7 +174,7 @@ macro_rules! intrinsics { $($rest:tt)* ) => ( - #[cfg(all(windows, target_pointer_width = "64"))] + #[cfg(all(any(windows, all(target_os = "uefi", target_arch = "x86_64")), target_pointer_width = "64"))] intrinsics! { $(#[$($attr)*])* pub extern "unadjusted" fn $name( $($argname: $ty),* ) $(-> $ret)? { @@ -182,7 +182,7 @@ macro_rules! intrinsics { } } - #[cfg(not(all(windows, target_pointer_width = "64")))] + #[cfg(not(all(any(windows, all(target_os = "uefi", target_arch = "x86_64")), target_pointer_width = "64")))] intrinsics! { $(#[$($attr)*])* pub extern $abi fn $name( $($argname: $ty),* ) $(-> $ret)? { @@ -209,13 +209,13 @@ macro_rules! intrinsics { $($rest:tt)* ) => ( - #[cfg(all(windows, target_arch = "x86_64"))] + #[cfg(all(any(windows, target_os = "uefi"), target_arch = "x86_64"))] $(#[$($attr)*])* pub extern $abi fn $name( $($argname: $ty),* ) $(-> $ret)? { $($body)* } - #[cfg(all(windows, target_arch = "x86_64"))] + #[cfg(all(any(windows, target_os = "uefi"), target_arch = "x86_64"))] pub mod $name { #[cfg_attr(not(feature = "mangled-names"), no_mangle)] pub extern $abi fn $name( $($argname: $ty),* ) @@ -226,7 +226,7 @@ macro_rules! intrinsics { } } - #[cfg(not(all(windows, target_arch = "x86_64")))] + #[cfg(not(all(any(windows, target_os = "uefi"), target_arch = "x86_64")))] intrinsics! { $(#[$($attr)*])* pub extern $abi fn $name( $($argname: $ty),* ) $(-> $ret)? { @@ -266,6 +266,7 @@ macro_rules! intrinsics { #[cfg(target_arch = "arm")] pub mod $alias { #[cfg_attr(not(feature = "mangled-names"), no_mangle)] + #[cfg_attr(all(not(windows), not(target_vendor="apple")), linkage = "weak")] pub extern "aapcs" fn $alias( $($argname: $ty),* ) $(-> $ret)? { super::$name($($argname),*) } @@ -426,7 +427,7 @@ macro_rules! intrinsics { // Hack for LLVM expectations for ABI on windows. This is used by the // `#[win64_128bit_abi_hack]` attribute recognized above -#[cfg(all(windows, target_pointer_width = "64"))] +#[cfg(all(any(windows, target_os = "uefi"), target_pointer_width = "64"))] pub mod win64_128bit_abi_hack { #[repr(simd)] pub struct U64x2(u64, u64); diff --git a/vendor/compiler_builtins/src/math.rs b/vendor/compiler_builtins/src/math.rs index fa59753f8..3fc33b127 100644 --- a/vendor/compiler_builtins/src/math.rs +++ b/vendor/compiler_builtins/src/math.rs @@ -20,6 +20,7 @@ macro_rules! no_mangle { target_os = "unknown", not(target_env = "wasi") ), + target_os = "xous", all(target_arch = "x86_64", target_os = "uefi"), all(target_arch = "xtensa", target_os = "none"), all(target_vendor = "fortanix", target_env = "sgx") @@ -62,6 +63,8 @@ no_mangle! { fn tanhf(n: f32) -> f32; fn ldexp(f: f64, n: i32) -> f64; fn ldexpf(f: f32, n: i32) -> f32; + fn tgamma(x: f64) -> f64; + fn tgammaf(x: f32) -> f32; } #[cfg(any( @@ -70,6 +73,8 @@ no_mangle! { target_os = "unknown", not(target_env = "wasi") ), + target_os = "xous", + all(target_arch = "x86_64", target_os = "uefi"), all(target_arch = "xtensa", target_os = "none"), all(target_vendor = "fortanix", target_env = "sgx") ))] @@ -93,7 +98,17 @@ no_mangle! { fn tanf(n: f32) -> f32; } -#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] +#[cfg(any(target_os = "xous", target_os = "uefi"))] +no_mangle! { + fn sqrtf(x: f32) -> f32; + fn sqrt(x: f64) -> f64; +} + +#[cfg(any( + all(target_vendor = "fortanix", target_env = "sgx"), + target_os = "xous", + target_os = "uefi" +))] no_mangle! { fn ceil(x: f64) -> f64; fn ceilf(x: f32) -> f32; @@ -103,8 +118,11 @@ no_mangle! { fn truncf(x: f32) -> f32; } -// only for the thumb*-none-eabi* targets -#[cfg(all(target_arch = "arm", target_os = "none"))] +// only for the thumb*-none-eabi* targets and riscv32*-none-elf targets that lack the floating point instruction set +#[cfg(any( + all(target_arch = "arm", target_os = "none"), + all(target_arch = "riscv32", not(target_feature = "f"), target_os = "none") +))] no_mangle! { fn fmin(x: f64, y: f64) -> f64; fn fminf(x: f32, y: f32) -> f32; diff --git a/vendor/compiler_builtins/src/mem/impls.rs b/vendor/compiler_builtins/src/mem/impls.rs index 815132425..72003a5c4 100644 --- a/vendor/compiler_builtins/src/mem/impls.rs +++ b/vendor/compiler_builtins/src/mem/impls.rs @@ -265,3 +265,17 @@ pub unsafe fn set_bytes(mut s: *mut u8, c: u8, mut n: usize) { } set_bytes_bytes(s, c, n); } + +#[inline(always)] +pub unsafe fn compare_bytes(s1: *const u8, s2: *const u8, n: usize) -> i32 { + let mut i = 0; + while i < n { + let a = *s1.add(i); + let b = *s2.add(i); + if a != b { + return a as i32 - b as i32; + } + i += 1; + } + 0 +} diff --git a/vendor/compiler_builtins/src/mem/mod.rs b/vendor/compiler_builtins/src/mem/mod.rs index a55113861..c5b0ddc16 100644 --- a/vendor/compiler_builtins/src/mem/mod.rs +++ b/vendor/compiler_builtins/src/mem/mod.rs @@ -51,16 +51,7 @@ intrinsics! { #[mem_builtin] #[cfg_attr(not(all(target_os = "windows", target_env = "gnu")), linkage = "weak")] pub unsafe extern "C" fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32 { - let mut i = 0; - while i < n { - let a = *s1.add(i); - let b = *s2.add(i); - if a != b { - return a as i32 - b as i32; - } - i += 1; - } - 0 + impls::compare_bytes(s1, s2, n) } #[mem_builtin] diff --git a/vendor/compiler_builtins/src/mem/x86_64.rs b/vendor/compiler_builtins/src/mem/x86_64.rs index a7ab6f605..17b461f79 100644 --- a/vendor/compiler_builtins/src/mem/x86_64.rs +++ b/vendor/compiler_builtins/src/mem/x86_64.rs @@ -16,6 +16,10 @@ // feature is present at compile-time. We don't bother detecting other features. // Note that ERMSB does not enhance the backwards (DF=1) "rep movsb". +use core::arch::asm; +use core::intrinsics; +use core::mem; + #[inline(always)] #[cfg(target_feature = "ermsb")] pub unsafe fn copy_forward(dest: *mut u8, src: *const u8, count: usize) { @@ -31,16 +35,26 @@ pub unsafe fn copy_forward(dest: *mut u8, src: *const u8, count: usize) { #[inline(always)] #[cfg(not(target_feature = "ermsb"))] -pub unsafe fn copy_forward(dest: *mut u8, src: *const u8, count: usize) { - let qword_count = count >> 3; - let byte_count = count & 0b111; - // FIXME: Use the Intel syntax once we drop LLVM 9 support on rust-lang/rust. - core::arch::asm!( - "repe movsq (%rsi), (%rdi)", - "mov {byte_count:e}, %ecx", - "repe movsb (%rsi), (%rdi)", - byte_count = in(reg) byte_count, +pub unsafe fn copy_forward(mut dest: *mut u8, mut src: *const u8, count: usize) { + let (pre_byte_count, qword_count, byte_count) = rep_param(dest, count); + // Separating the blocks gives the compiler more freedom to reorder instructions. + asm!( + "rep movsb", + inout("ecx") pre_byte_count => _, + inout("rdi") dest => dest, + inout("rsi") src => src, + options(att_syntax, nostack, preserves_flags) + ); + asm!( + "rep movsq", inout("rcx") qword_count => _, + inout("rdi") dest => dest, + inout("rsi") src => src, + options(att_syntax, nostack, preserves_flags) + ); + asm!( + "rep movsb", + inout("ecx") byte_count => _, inout("rdi") dest => _, inout("rsi") src => _, options(att_syntax, nostack, preserves_flags) @@ -49,22 +63,28 @@ pub unsafe fn copy_forward(dest: *mut u8, src: *const u8, count: usize) { #[inline(always)] pub unsafe fn copy_backward(dest: *mut u8, src: *const u8, count: usize) { - let qword_count = count >> 3; - let byte_count = count & 0b111; - // FIXME: Use the Intel syntax once we drop LLVM 9 support on rust-lang/rust. - core::arch::asm!( + let (pre_byte_count, qword_count, byte_count) = rep_param(dest, count); + // We can't separate this block due to std/cld + asm!( "std", - "repe movsq (%rsi), (%rdi)", - "movl {byte_count:e}, %ecx", - "addq $7, %rdi", - "addq $7, %rsi", - "repe movsb (%rsi), (%rdi)", + "rep movsb", + "sub $7, %rsi", + "sub $7, %rdi", + "mov {qword_count}, %rcx", + "rep movsq", + "test {pre_byte_count:e}, {pre_byte_count:e}", + "add $7, %rsi", + "add $7, %rdi", + "mov {pre_byte_count:e}, %ecx", + "rep movsb", "cld", - byte_count = in(reg) byte_count, - inout("rcx") qword_count => _, - inout("rdi") dest.add(count).wrapping_sub(8) => _, - inout("rsi") src.add(count).wrapping_sub(8) => _, - options(att_syntax, nostack) + pre_byte_count = in(reg) pre_byte_count, + qword_count = in(reg) qword_count, + inout("ecx") byte_count => _, + inout("rdi") dest.add(count - 1) => _, + inout("rsi") src.add(count - 1) => _, + // We modify flags, but we restore it afterwards + options(att_syntax, nostack, preserves_flags) ); } @@ -83,18 +103,82 @@ pub unsafe fn set_bytes(dest: *mut u8, c: u8, count: usize) { #[inline(always)] #[cfg(not(target_feature = "ermsb"))] -pub unsafe fn set_bytes(dest: *mut u8, c: u8, count: usize) { - let qword_count = count >> 3; - let byte_count = count & 0b111; - // FIXME: Use the Intel syntax once we drop LLVM 9 support on rust-lang/rust. - core::arch::asm!( - "repe stosq %rax, (%rdi)", - "mov {byte_count:e}, %ecx", - "repe stosb %al, (%rdi)", - byte_count = in(reg) byte_count, +pub unsafe fn set_bytes(mut dest: *mut u8, c: u8, count: usize) { + let c = c as u64 * 0x0101_0101_0101_0101; + let (pre_byte_count, qword_count, byte_count) = rep_param(dest, count); + // Separating the blocks gives the compiler more freedom to reorder instructions. + asm!( + "rep stosb", + inout("ecx") pre_byte_count => _, + inout("rdi") dest => dest, + in("rax") c, + options(att_syntax, nostack, preserves_flags) + ); + asm!( + "rep stosq", inout("rcx") qword_count => _, + inout("rdi") dest => dest, + in("rax") c, + options(att_syntax, nostack, preserves_flags) + ); + asm!( + "rep stosb", + inout("ecx") byte_count => _, inout("rdi") dest => _, - in("rax") (c as u64) * 0x0101010101010101, + in("rax") c, options(att_syntax, nostack, preserves_flags) ); } + +#[inline(always)] +pub unsafe fn compare_bytes(a: *const u8, b: *const u8, n: usize) -> i32 { + #[inline(always)] + unsafe fn cmp(mut a: *const T, mut b: *const T, n: usize, f: F) -> i32 + where + T: Clone + Copy + Eq, + U: Clone + Copy + Eq, + F: FnOnce(*const U, *const U, usize) -> i32, + { + // Ensure T is not a ZST. + const { assert!(mem::size_of::() != 0) }; + + let end = a.add(intrinsics::unchecked_div(n, mem::size_of::())); + while a != end { + if a.read_unaligned() != b.read_unaligned() { + return f(a.cast(), b.cast(), mem::size_of::()); + } + a = a.add(1); + b = b.add(1); + } + f( + a.cast(), + b.cast(), + intrinsics::unchecked_rem(n, mem::size_of::()), + ) + } + let c1 = |mut a: *const u8, mut b: *const u8, n| { + for _ in 0..n { + if a.read() != b.read() { + return i32::from(a.read()) - i32::from(b.read()); + } + a = a.add(1); + b = b.add(1); + } + 0 + }; + let c2 = |a: *const u16, b, n| cmp(a, b, n, c1); + let c4 = |a: *const u32, b, n| cmp(a, b, n, c2); + let c8 = |a: *const u64, b, n| cmp(a, b, n, c4); + let c16 = |a: *const u128, b, n| cmp(a, b, n, c8); + c16(a.cast(), b.cast(), n) +} + +/// Determine optimal parameters for a `rep` instruction. +fn rep_param(dest: *mut u8, mut count: usize) -> (usize, usize, usize) { + // Unaligned writes are still slow on modern processors, so align the destination address. + let pre_byte_count = ((8 - (dest as usize & 0b111)) & 0b111).min(count); + count -= pre_byte_count; + let qword_count = count >> 3; + let byte_count = count & 0b111; + (pre_byte_count, qword_count, byte_count) +} diff --git a/vendor/compiletest_rs/.cargo-checksum.json b/vendor/compiletest_rs/.cargo-checksum.json index 8533fd089..c7ba6752d 100644 --- a/vendor/compiletest_rs/.cargo-checksum.json +++ b/vendor/compiletest_rs/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"e66bd0207f0ea860188e04376705d67a4658e78295bcaf579b2a89dbd9088d54","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"e0655e85239c6e887c0f35e1b97fb2574127ea61c28e3deec93c20b560f47892","build.rs":"905784fbb4a75c17279a88fd476e7221104adf00b4dd745a4a66bd41cac8d77a","src/common.rs":"df14f9c75c6a341c5bbc90c4b386c20f66164196f3b4b2ffc19b454d6b658e2b","src/errors.rs":"88a36d1726d90b11bf9272b1439dd52cd4fdf2e70e6e0cb6cfb323f76d84e3ff","src/header.rs":"04e405d100c46dd82139705e8b833e03d19c597edf3a5f7fee92ad9cbd12c201","src/json.rs":"e278c4c3c32c60e840a250b0979926e2ac333dcbbbaae5ab6fcf01ca05bef625","src/lib.rs":"ac780a6ad8d9eb84bd0c6bd7c56fab64a98ef29b9133f1b4fb2a845b58c839bc","src/raise_fd_limit.rs":"b0840fe16df9edaae0571499e105db47768050fcd62729d1e56295f2db34318e","src/read2.rs":"fb9caa84bec8c9c3d2c1ee39a4a6698c461fdc77aec086c74fd7738a6acf4155","src/runtest.rs":"9dc12384637275790ca5a030f79e7ea72be991ff8d5365193e48895a30db6454","src/uidiff.rs":"2f612bd4ed76d68c0f6b3eb8dda5adf14a3e6ceef261c88c810ac6b6857e2d34","src/util.rs":"9cda9e803ffe5e1b5d4c74cf7da7bd51e28a8d1b09bda3d31e01c0f648c3262d","tests/bless.rs":"29031f02666102ab8cde316b9206bf1e770275f9fa6e0172754dcad859a52b5b","tests/test_support/mod.rs":"21ec96cca07cf95b6e3333917a5158a6c47356940063f77d52503b97fd3d8b79"},"package":"262134ef87408da1ddfe45e33daa0ca43b75286d6b1076446e602d264cf9847e"} \ No newline at end of file +{"files":{"Cargo.toml":"cc0342b513ff3ec9dd349398d0a851131ce10afa5b7748997fe7b66f4c75ad32","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"043fc0e7bbad6798c80b81640db2f45cea97b2cadadf8d21e08fe89119872e07","build.rs":"905784fbb4a75c17279a88fd476e7221104adf00b4dd745a4a66bd41cac8d77a","src/common.rs":"df14f9c75c6a341c5bbc90c4b386c20f66164196f3b4b2ffc19b454d6b658e2b","src/errors.rs":"88a36d1726d90b11bf9272b1439dd52cd4fdf2e70e6e0cb6cfb323f76d84e3ff","src/header.rs":"04e405d100c46dd82139705e8b833e03d19c597edf3a5f7fee92ad9cbd12c201","src/json.rs":"e278c4c3c32c60e840a250b0979926e2ac333dcbbbaae5ab6fcf01ca05bef625","src/lib.rs":"ac780a6ad8d9eb84bd0c6bd7c56fab64a98ef29b9133f1b4fb2a845b58c839bc","src/raise_fd_limit.rs":"b0840fe16df9edaae0571499e105db47768050fcd62729d1e56295f2db34318e","src/read2.rs":"fb9caa84bec8c9c3d2c1ee39a4a6698c461fdc77aec086c74fd7738a6acf4155","src/runtest.rs":"4d0d761d8f848ceda532ecc1363d5280951656c5a9ea7eff75d91475e7fcf269","src/uidiff.rs":"2f612bd4ed76d68c0f6b3eb8dda5adf14a3e6ceef261c88c810ac6b6857e2d34","src/util.rs":"9cda9e803ffe5e1b5d4c74cf7da7bd51e28a8d1b09bda3d31e01c0f648c3262d","tests/bless.rs":"29031f02666102ab8cde316b9206bf1e770275f9fa6e0172754dcad859a52b5b","tests/test_support/mod.rs":"21ec96cca07cf95b6e3333917a5158a6c47356940063f77d52503b97fd3d8b79"},"package":"70489bbb718aea4f92e5f48f2e3b5be670c2051de30e57cb6e5377b4aa08b372"} \ No newline at end of file diff --git a/vendor/compiletest_rs/Cargo.toml b/vendor/compiletest_rs/Cargo.toml index 9403548b8..f56e4d712 100644 --- a/vendor/compiletest_rs/Cargo.toml +++ b/vendor/compiletest_rs/Cargo.toml @@ -11,7 +11,7 @@ [package] name = "compiletest_rs" -version = "0.8.0" +version = "0.9.0" authors = [ "The Rust Project Developers", "Thomas Bracht Laumann Jespersen ", diff --git a/vendor/compiletest_rs/README.md b/vendor/compiletest_rs/README.md index bf7cac194..c01a40c9b 100644 --- a/vendor/compiletest_rs/README.md +++ b/vendor/compiletest_rs/README.md @@ -14,7 +14,7 @@ To use `compiletest-rs` in your application, add the following to `Cargo.toml` ```toml [dev-dependencies] -compiletest_rs = "0.7" +compiletest_rs = "0.9" ``` By default, `compiletest-rs` should be able to run on both stable, beta and @@ -28,7 +28,7 @@ crate. ```toml [dev-dependencies] -compiletest_rs = { version = "0.7", features = [ "rustc" ] } +compiletest_rs = { version = "0.9", features = [ "rustc" ] } ``` Create a `tests` folder in the root folder of your project. Create a test file diff --git a/vendor/compiletest_rs/src/runtest.rs b/vendor/compiletest_rs/src/runtest.rs index c52551488..47f9c4870 100644 --- a/vendor/compiletest_rs/src/runtest.rs +++ b/vendor/compiletest_rs/src/runtest.rs @@ -33,9 +33,28 @@ use std::io::{self, BufReader}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, ExitStatus, Stdio, Child}; use std::str; +use std::sync::{Arc, Mutex, RwLock}; use extract_gdb_version; +fn get_or_create_coverage_file(path: &Path, create: impl FnOnce() -> File) -> Arc> { + lazy_static::lazy_static! { + static ref COVERAGE_FILE_LOCKS: RwLock>>> = RwLock::new(HashMap::new()); + } + + { + let locks = COVERAGE_FILE_LOCKS.read().unwrap(); + locks.get(path).map(Arc::clone) + } + .unwrap_or_else(|| { + let mut locks = COVERAGE_FILE_LOCKS.write().unwrap(); + locks + .entry(path.to_path_buf()) + .or_insert_with(|| Arc::new(Mutex::new(create()))) + .clone() + }) +} + /// The name of the environment variable that holds dynamic library locations. pub fn dylib_env_var() -> &'static str { if cfg!(windows) { @@ -2343,16 +2362,23 @@ actual:\n\ coverage_file_path.push("rustfix_missing_coverage.txt"); debug!("coverage_file_path: {}", coverage_file_path.display()); - let mut file = OpenOptions::new() - .create(true) - .append(true) - .open(coverage_file_path.as_path()) - .expect("could not create or open file"); - - if let Err(_) = writeln!(file, "{}", self.testpaths.file.display()) { + let file_ref = get_or_create_coverage_file(&coverage_file_path, || { + OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(coverage_file_path.as_path()) + .expect("could not create or open file") + }); + let mut file = file_ref.lock().unwrap(); + + if writeln!(file, "{}", self.testpaths.file.display()) + .and_then(|_| file.sync_data()) + .is_err() + { panic!("couldn't write to {}", coverage_file_path.display()); } - } + } } if self.props.run_rustfix { @@ -2408,10 +2434,13 @@ actual:\n\ // And finally, compile the fixed code and make sure it both // succeeds and has no diagnostics. let mut rustc = self.make_compile_args( - &self.testpaths.file.with_extension(UI_FIXED), + &expected_fixed_path, TargetLocation::ThisFile(self.make_exe_name()), AllowUnused::No, ); + // Set the crate name to avoid `file.revision.fixed` inferring the + // invalid name `file.revision` + rustc.arg("--crate-name=fixed"); rustc.arg("-L").arg(&self.aux_output_dir_name()); let res = self.compose_and_run_compiler(rustc, None); if !res.status.success() { diff --git a/vendor/crossbeam-channel/.cargo-checksum.json b/vendor/crossbeam-channel/.cargo-checksum.json index dd210c73b..96db2f1ab 100644 --- a/vendor/crossbeam-channel/.cargo-checksum.json +++ b/vendor/crossbeam-channel/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"704f57293fd91b9801cb8befda7622900b6f02ffe76387ea03bd7e9a041ede50","Cargo.lock":"3b56bd551cb1b7d4e733413036c67b1407ac40e4899e8a368641884e0986ce60","Cargo.toml":"d5d17d3cace2539f582aa6aa6b41c1be09e621266fd0839cdb63920db04e229a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","LICENSE-THIRD-PARTY":"b16db96b93b1d7cf7bea533f572091ec6bca3234fbe0a83038be772ff391a44c","README.md":"415a71d4978cfd338a6ae1f1b41284652eccd277a815542c304647dc437a8274","benches/crossbeam.rs":"96cb1abd23cac3ef8a7174a802e94609926b555bb02c9658c78723d433f1dd92","examples/fibonacci.rs":"4e88fa40048cdc31e9c7bb60347d46f92543d7ddf39cab3b52bfe44affdb6a02","examples/matching.rs":"63c250e164607a7a9f643d46f107bb5da846d49e89cf9069909562d20e530f71","examples/stopwatch.rs":"d02121258f08d56f1eb7997e19bcb9bacb6836cfa0abbba90a9e59d8a50ae5cf","src/channel.rs":"9538e285101c152e23c5ff6a47b0305753d94a5b27f3426499052b0e3d0f97ee","src/context.rs":"ff4d39639ddf16aaab582d4a5f3d10ef2c71afe1abbf4e60f3d9d2ddbd72c230","src/counter.rs":"c49a9f44587888850edeb62f7c8ecd1acecb39c836834254ff3ac934c478440a","src/err.rs":"44cb2024ee6b0cd6fd24996430e53720769f64b4ac35016bc3e05cb9db48681d","src/flavors/array.rs":"08e37b7c07e9a525a32cc61f89b384b897a8d852b2eda5e85ea0cf4ba7527a3f","src/flavors/at.rs":"1db64919593b7c14f838c16a22732515f1e716d2d5f6cc639f42631380e545cd","src/flavors/list.rs":"c05da598d0759b05c345050df1f6206946098203e3021260bd722f5ea24d9240","src/flavors/mod.rs":"3d9d43bc38b0adb18c96c995c2bd3421d8e33ab6c30b20c3c467d21d48e485dc","src/flavors/never.rs":"747da857aa1a7601641f23f4930e6ad00ebaf50456d9be5c7aa270e2ecc24dcb","src/flavors/tick.rs":"69b2dfe0186bc8b9fd7a73e32da59d2656d8150da1e00fba92a412e0907568a3","src/flavors/zero.rs":"d7e67264d7b33152f52f1d4d8cdb565334b53508f56308f72140528d0645aa73","src/lib.rs":"3a65706d4124844ffc4c8cb1f8cc779631ec94f449f85cbb68364ad3619404f1","src/select.rs":"3b00c3929d3a8973e46188db41f6ae0b47c89ab108cf7ec2cb348e272e77e132","src/select_macro.rs":"283acd04870356b0c4d3d4046c5070638b562c9ffb8fa29c1a5b90a2509bf3af","src/utils.rs":"0b6e6621198236c077fcb6b66203317e36dc8f1a157dd3b22ad422b6599ae389","src/waker.rs":"6839108d1c9357b3c0c1c162c8b4633ff5ac4f756e95e677ac1293e7df942635","tests/after.rs":"0154a8e152880db17a20514ecdd49dabc361d3629858d119b9746b5e932c780c","tests/array.rs":"be8176ac8f1376567f28e60c15e95b9baf8cb4c8e0e2c1de9b286a49c988dc73","tests/golang.rs":"708a4d0d94abacb2c054ac117eff79689398f76a5cb089ca188dd2b4ed53ec6b","tests/iter.rs":"25dc02135bbae9d47a30f9047661648e66bdc134e40ba78bc2fbacbb8b3819bc","tests/list.rs":"0937da0413fa9ecdcba687c4c07c9b254bc82fb85cb2f836425550890c31ed36","tests/mpsc.rs":"5a49429a29c9028ade618994e82d03d4f4405b62fb89a4464ba9d89e68a1a88d","tests/never.rs":"ee40c4fc4dd5af4983fae8de6927f52b81174d222c162f745b26c4a6c7108e4f","tests/ready.rs":"d349702f123925a0781b48d677e6dcf64fc5d1fc788a7bf1e151a3d57e81871c","tests/same_channel.rs":"2bab761443671e841e1b2476bd8082d75533a2f6be7946f5dbcee67cdc82dccb","tests/select.rs":"e5e9308e3adcc4c99f98cd7ad5f8149ec7030845d6263e9a5a27c317aa96363f","tests/select_macro.rs":"141adb62fddc1c1973b24b0cbcf87bae06fc537be4f8fbb68e12e0864e73795c","tests/thread_locals.rs":"a1ce59e2aff69161621c0cb215eb6ea238088c06a31a8507a74cf179fd5a4299","tests/tick.rs":"5f697bd14c48505d932e82065b5302ef668e1cc19cac18e8ac22e0c83c221c1d","tests/zero.rs":"54f8ee1fa8316a99457f1c6bb5a8e31c4b21d39b3b4d79b276a53c6340940c8f"},"package":"4c02a4d71819009c192cf4872265391563fd6a84c81ff2c0f2a7026ca4c1d85c"} \ No newline at end of file +{"files":{"CHANGELOG.md":"f87a526ab720644e07509dd76d29c08993a5e52a6d6ec230d809fc31a1c0e403","Cargo.lock":"8af0a5f8b3d1e6f036332a5ecc91b30222343f29a465ea398bca3298c0212f4a","Cargo.toml":"81a227ee6f529cd0cf62327f63eb098fed59c04dde2a8e68aeaa0ea32dbafbcf","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","LICENSE-THIRD-PARTY":"b16db96b93b1d7cf7bea533f572091ec6bca3234fbe0a83038be772ff391a44c","README.md":"4e16587d8f6a15f2016f256535aa6c9429424672ebdcd03c1a7d964746e46127","benches/crossbeam.rs":"96cb1abd23cac3ef8a7174a802e94609926b555bb02c9658c78723d433f1dd92","examples/fibonacci.rs":"4e88fa40048cdc31e9c7bb60347d46f92543d7ddf39cab3b52bfe44affdb6a02","examples/matching.rs":"63c250e164607a7a9f643d46f107bb5da846d49e89cf9069909562d20e530f71","examples/stopwatch.rs":"d02121258f08d56f1eb7997e19bcb9bacb6836cfa0abbba90a9e59d8a50ae5cf","src/channel.rs":"9538e285101c152e23c5ff6a47b0305753d94a5b27f3426499052b0e3d0f97ee","src/context.rs":"ff4d39639ddf16aaab582d4a5f3d10ef2c71afe1abbf4e60f3d9d2ddbd72c230","src/counter.rs":"c49a9f44587888850edeb62f7c8ecd1acecb39c836834254ff3ac934c478440a","src/err.rs":"44cb2024ee6b0cd6fd24996430e53720769f64b4ac35016bc3e05cb9db48681d","src/flavors/array.rs":"508e54587fc8d9e8dfacd16446a601e33838d7bb1dfd9d7ccc3e65315b66b35a","src/flavors/at.rs":"1db64919593b7c14f838c16a22732515f1e716d2d5f6cc639f42631380e545cd","src/flavors/list.rs":"d901d9259185a71aeb5cf74be70e5c38b550c7f38b87e023196cb47fed2d1a11","src/flavors/mod.rs":"3d9d43bc38b0adb18c96c995c2bd3421d8e33ab6c30b20c3c467d21d48e485dc","src/flavors/never.rs":"747da857aa1a7601641f23f4930e6ad00ebaf50456d9be5c7aa270e2ecc24dcb","src/flavors/tick.rs":"69b2dfe0186bc8b9fd7a73e32da59d2656d8150da1e00fba92a412e0907568a3","src/flavors/zero.rs":"7458eb0ece475dc5093b4f2cde13f6de57e4f70291258850de4fa3c951c8f594","src/lib.rs":"3a65706d4124844ffc4c8cb1f8cc779631ec94f449f85cbb68364ad3619404f1","src/select.rs":"3b00c3929d3a8973e46188db41f6ae0b47c89ab108cf7ec2cb348e272e77e132","src/select_macro.rs":"283acd04870356b0c4d3d4046c5070638b562c9ffb8fa29c1a5b90a2509bf3af","src/utils.rs":"0b6e6621198236c077fcb6b66203317e36dc8f1a157dd3b22ad422b6599ae389","src/waker.rs":"6839108d1c9357b3c0c1c162c8b4633ff5ac4f756e95e677ac1293e7df942635","tests/after.rs":"0154a8e152880db17a20514ecdd49dabc361d3629858d119b9746b5e932c780c","tests/array.rs":"a57ae6264e676f573d7adb5c4b024994e98bc6811352516adb3444f880f7125e","tests/golang.rs":"284bed0d4c07857f33de96f2addc9a69c5688f864935a3e3e113c88c04bd826b","tests/iter.rs":"25dc02135bbae9d47a30f9047661648e66bdc134e40ba78bc2fbacbb8b3819bc","tests/list.rs":"3d1a4ae23bb6b4767242b8109a8efda26f1d3b28c0f90da3368f8eb9ca0eee37","tests/mpsc.rs":"d1e185c6290240132a34aa91221271225959f8652d7fc4ceb546ee9712361176","tests/never.rs":"ee40c4fc4dd5af4983fae8de6927f52b81174d222c162f745b26c4a6c7108e4f","tests/ready.rs":"d349702f123925a0781b48d677e6dcf64fc5d1fc788a7bf1e151a3d57e81871c","tests/same_channel.rs":"2bab761443671e841e1b2476bd8082d75533a2f6be7946f5dbcee67cdc82dccb","tests/select.rs":"ce12a8e0284fb9ccf6c1543bec309d9054193e6d942663aed19aa8499ef69c43","tests/select_macro.rs":"597d526fbd021ce70619d9172c931439f778ee3034ec1479aea461b65971a81a","tests/thread_locals.rs":"25ab70a8dcd8a0da9173e5476e17dcc8916caa5b68207d9c403655deaa8e8f4a","tests/tick.rs":"5f697bd14c48505d932e82065b5302ef668e1cc19cac18e8ac22e0c83c221c1d","tests/zero.rs":"9c5af802d5efb2c711f8242b8905ed29cc2601e48dbd95e41c7e6fbfe2918398"},"package":"c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521"} \ No newline at end of file diff --git a/vendor/crossbeam-channel/CHANGELOG.md b/vendor/crossbeam-channel/CHANGELOG.md index 2f627cf26..f0d11e60c 100644 --- a/vendor/crossbeam-channel/CHANGELOG.md +++ b/vendor/crossbeam-channel/CHANGELOG.md @@ -1,3 +1,7 @@ +# Version 0.5.6 + +- Bump the minimum supported Rust version to 1.38. (#877) + # Version 0.5.5 - Replace Spinlock with Mutex. (#835) diff --git a/vendor/crossbeam-channel/Cargo.lock b/vendor/crossbeam-channel/Cargo.lock index cd6eb056f..e40f83650 100644 --- a/vendor/crossbeam-channel/Cargo.lock +++ b/vendor/crossbeam-channel/Cargo.lock @@ -10,7 +10,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "crossbeam-channel" -version = "0.5.5" +version = "0.5.6" dependencies = [ "cfg-if", "crossbeam-utils", @@ -21,9 +21,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.9" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ff1f980957787286a554052d03c7aee98d99cc32e09f6d45f0a814133c87978" +checksum = "51887d4adc7b564537b15adcfb307936f8075dfcd5f00dde9a9f1d29383682bc" dependencies = [ "cfg-if", "once_cell", @@ -67,9 +67,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" +checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" [[package]] name = "ppv-lite86" diff --git a/vendor/crossbeam-channel/Cargo.toml b/vendor/crossbeam-channel/Cargo.toml index c02f8595c..619fad423 100644 --- a/vendor/crossbeam-channel/Cargo.toml +++ b/vendor/crossbeam-channel/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2018" -rust-version = "1.36" +rust-version = "1.38" name = "crossbeam-channel" -version = "0.5.5" +version = "0.5.6" description = "Multi-producer multi-consumer channels for message passing" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel" readme = "README.md" diff --git a/vendor/crossbeam-channel/README.md b/vendor/crossbeam-channel/README.md index f5077c556..4c42d863c 100644 --- a/vendor/crossbeam-channel/README.md +++ b/vendor/crossbeam-channel/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel#license) https://crates.io/crates/crossbeam-channel) [![Documentation](https://docs.rs/crossbeam-channel/badge.svg)]( https://docs.rs/crossbeam-channel) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( +[![Rust 1.38+](https://img.shields.io/badge/rust-1.38+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) @@ -48,7 +48,7 @@ crossbeam-channel = "0.5" Crossbeam Channel supports stable Rust releases going back at least six months, and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. +version is released. Currently, the minimum supported Rust version is 1.38. ## License diff --git a/vendor/crossbeam-channel/src/flavors/array.rs b/vendor/crossbeam-channel/src/flavors/array.rs index 73557d385..63b82eb85 100644 --- a/vendor/crossbeam-channel/src/flavors/array.rs +++ b/vendor/crossbeam-channel/src/flavors/array.rs @@ -216,7 +216,7 @@ impl Channel { return Err(msg); } - let slot: &Slot = &*(token.array.slot as *const Slot); + let slot: &Slot = &*token.array.slot.cast::>(); // Write the message into the slot and update the stamp. slot.msg.get().write(MaybeUninit::new(msg)); @@ -307,7 +307,7 @@ impl Channel { return Err(()); } - let slot: &Slot = &*(token.array.slot as *const Slot); + let slot: &Slot = &*token.array.slot.cast::>(); // Read the message from the slot and update the stamp. let msg = slot.msg.get().read().assume_init(); diff --git a/vendor/crossbeam-channel/src/flavors/list.rs b/vendor/crossbeam-channel/src/flavors/list.rs index 9bda6d1cc..6090b8d47 100644 --- a/vendor/crossbeam-channel/src/flavors/list.rs +++ b/vendor/crossbeam-channel/src/flavors/list.rs @@ -49,6 +49,11 @@ struct Slot { } impl Slot { + const UNINIT: Self = Self { + msg: UnsafeCell::new(MaybeUninit::uninit()), + state: AtomicUsize::new(0), + }; + /// Waits until a message is written into the slot. fn wait_write(&self) { let backoff = Backoff::new(); @@ -72,13 +77,10 @@ struct Block { impl Block { /// Creates an empty block. fn new() -> Block { - // SAFETY: This is safe because: - // [1] `Block::next` (AtomicPtr) may be safely zero initialized. - // [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4]. - // [3] `Slot::msg` (UnsafeCell) may be safely zero initialized because it - // holds a MaybeUninit. - // [4] `Slot::state` (AtomicUsize) may be safely zero initialized. - unsafe { MaybeUninit::zeroed().assume_init() } + Self { + next: AtomicPtr::new(ptr::null_mut()), + slots: [Slot::UNINIT; BLOCK_CAP], + } } /// Waits until the next pointer is set. @@ -283,7 +285,7 @@ impl Channel { } // Write the message into the slot. - let block = token.list.block as *mut Block; + let block = token.list.block.cast::>(); let offset = token.list.offset; let slot = (*block).slots.get_unchecked(offset); slot.msg.get().write(MaybeUninit::new(msg)); diff --git a/vendor/crossbeam-channel/src/flavors/zero.rs b/vendor/crossbeam-channel/src/flavors/zero.rs index 31e62afac..aae2ea300 100644 --- a/vendor/crossbeam-channel/src/flavors/zero.rs +++ b/vendor/crossbeam-channel/src/flavors/zero.rs @@ -190,7 +190,7 @@ impl Channel { // heap-allocated packet. packet.wait_ready(); let msg = packet.msg.get().replace(None).unwrap(); - drop(Box::from_raw(token.zero.0 as *mut Packet)); + drop(Box::from_raw(token.zero.0.cast::>())); Ok(msg) } } @@ -409,7 +409,7 @@ impl SelectHandle for Receiver<'_, T> { let mut inner = self.0.inner.lock().unwrap(); inner .receivers - .register_with_packet(oper, packet as *mut (), cx); + .register_with_packet(oper, packet.cast::<()>(), cx); inner.senders.notify(); inner.senders.can_select() || inner.is_disconnected } @@ -417,7 +417,7 @@ impl SelectHandle for Receiver<'_, T> { fn unregister(&self, oper: Operation) { if let Some(operation) = self.0.inner.lock().unwrap().receivers.unregister(oper) { unsafe { - drop(Box::from_raw(operation.packet as *mut Packet)); + drop(Box::from_raw(operation.packet.cast::>())); } } } @@ -459,7 +459,7 @@ impl SelectHandle for Sender<'_, T> { let mut inner = self.0.inner.lock().unwrap(); inner .senders - .register_with_packet(oper, packet as *mut (), cx); + .register_with_packet(oper, packet.cast::<()>(), cx); inner.receivers.notify(); inner.receivers.can_select() || inner.is_disconnected } @@ -467,7 +467,7 @@ impl SelectHandle for Sender<'_, T> { fn unregister(&self, oper: Operation) { if let Some(operation) = self.0.inner.lock().unwrap().senders.unregister(oper) { unsafe { - drop(Box::from_raw(operation.packet as *mut Packet)); + drop(Box::from_raw(operation.packet.cast::>())); } } } diff --git a/vendor/crossbeam-channel/tests/array.rs b/vendor/crossbeam-channel/tests/array.rs index de843cd32..6fd8ffcc6 100644 --- a/vendor/crossbeam-channel/tests/array.rs +++ b/vendor/crossbeam-channel/tests/array.rs @@ -377,7 +377,7 @@ fn spsc() { #[test] fn mpmc() { #[cfg(miri)] - const COUNT: usize = 100; + const COUNT: usize = 50; #[cfg(not(miri))] const COUNT: usize = 25_000; const THREADS: usize = 4; @@ -532,16 +532,12 @@ fn drops() { scope.spawn(|_| { for _ in 0..steps { r.recv().unwrap(); - #[cfg(miri)] - std::thread::yield_now(); // https://github.com/rust-lang/miri/issues/1388 } }); scope.spawn(|_| { for _ in 0..steps { s.send(DropCounter).unwrap(); - #[cfg(miri)] - std::thread::yield_now(); // https://github.com/rust-lang/miri/issues/1388 } }); }) diff --git a/vendor/crossbeam-channel/tests/golang.rs b/vendor/crossbeam-channel/tests/golang.rs index 6a46c0353..8050716c6 100644 --- a/vendor/crossbeam-channel/tests/golang.rs +++ b/vendor/crossbeam-channel/tests/golang.rs @@ -959,7 +959,7 @@ mod chan_test { #[test] fn test_chan() { #[cfg(miri)] - const N: i32 = 20; + const N: i32 = 12; #[cfg(not(miri))] const N: i32 = 200; @@ -1489,7 +1489,7 @@ mod chan_test { fn test_multi_consumer() { const NWORK: usize = 23; #[cfg(miri)] - const NITER: usize = 100; + const NITER: usize = 50; #[cfg(not(miri))] const NITER: usize = 271828; @@ -1580,9 +1580,7 @@ mod race_chan_test { } // https://github.com/golang/go/blob/master/test/ken/chan.go -#[cfg(not(miri))] // Miri is too slow mod chan { - use super::*; const MESSAGES_PER_CHANEL: u32 = 76; @@ -2052,6 +2050,7 @@ mod chan { } #[test] + #[cfg_attr(miri, ignore)] // Miri is too slow fn main() { let mut ctx = Context { nproc: Arc::new(Mutex::new(0)), diff --git a/vendor/crossbeam-channel/tests/list.rs b/vendor/crossbeam-channel/tests/list.rs index a0b908722..ebe6f6f85 100644 --- a/vendor/crossbeam-channel/tests/list.rs +++ b/vendor/crossbeam-channel/tests/list.rs @@ -67,6 +67,7 @@ fn len_empty_full() { } #[test] +#[cfg_attr(miri, ignore)] // this test makes timing assumptions, but Miri is so slow it violates them fn try_recv() { let (s, r) = unbounded(); @@ -433,8 +434,6 @@ fn drops() { scope.spawn(|_| { for _ in 0..steps { r.recv().unwrap(); - #[cfg(miri)] - std::thread::yield_now(); // https://github.com/rust-lang/miri/issues/1388 } }); diff --git a/vendor/crossbeam-channel/tests/mpsc.rs b/vendor/crossbeam-channel/tests/mpsc.rs index 3db4812c6..d7cc8e25f 100644 --- a/vendor/crossbeam-channel/tests/mpsc.rs +++ b/vendor/crossbeam-channel/tests/mpsc.rs @@ -339,25 +339,22 @@ mod channel_tests { #[test] fn stress_shared() { - #[cfg(miri)] - const AMT: u32 = 100; - #[cfg(not(miri))] - const AMT: u32 = 10000; - const NTHREADS: u32 = 8; + let amt: u32 = if cfg!(miri) { 100 } else { 10_000 }; + let nthreads: u32 = if cfg!(miri) { 4 } else { 8 }; let (tx, rx) = channel::(); let t = thread::spawn(move || { - for _ in 0..AMT * NTHREADS { + for _ in 0..amt * nthreads { assert_eq!(rx.recv().unwrap(), 1); } assert!(rx.try_recv().is_err()); }); - let mut ts = Vec::with_capacity(NTHREADS as usize); - for _ in 0..NTHREADS { + let mut ts = Vec::with_capacity(nthreads as usize); + for _ in 0..nthreads { let tx = tx.clone(); let t = thread::spawn(move || { - for _ in 0..AMT { + for _ in 0..amt { tx.send(1).unwrap(); } }); diff --git a/vendor/crossbeam-channel/tests/select.rs b/vendor/crossbeam-channel/tests/select.rs index e7691f52e..bc5824dab 100644 --- a/vendor/crossbeam-channel/tests/select.rs +++ b/vendor/crossbeam-channel/tests/select.rs @@ -408,7 +408,6 @@ fn both_ready() { .unwrap(); } -#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn loop_try() { const RUNS: usize = 20; diff --git a/vendor/crossbeam-channel/tests/select_macro.rs b/vendor/crossbeam-channel/tests/select_macro.rs index 91c04e1c3..119454cd6 100644 --- a/vendor/crossbeam-channel/tests/select_macro.rs +++ b/vendor/crossbeam-channel/tests/select_macro.rs @@ -284,7 +284,6 @@ fn both_ready() { .unwrap(); } -#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn loop_try() { const RUNS: usize = 20; diff --git a/vendor/crossbeam-channel/tests/thread_locals.rs b/vendor/crossbeam-channel/tests/thread_locals.rs index effb6a143..fb4e577f2 100644 --- a/vendor/crossbeam-channel/tests/thread_locals.rs +++ b/vendor/crossbeam-channel/tests/thread_locals.rs @@ -1,6 +1,6 @@ //! Tests that make sure accessing thread-locals while exiting the thread doesn't cause panics. -#![cfg(not(miri))] // error: abnormal termination: the evaluated program aborted execution +#![cfg(not(miri))] // Miri detects that this test is buggy: the destructor of `FOO` uses `std::thread::current()`! use std::thread; use std::time::Duration; diff --git a/vendor/crossbeam-channel/tests/zero.rs b/vendor/crossbeam-channel/tests/zero.rs index c90d74187..74c9a3e10 100644 --- a/vendor/crossbeam-channel/tests/zero.rs +++ b/vendor/crossbeam-channel/tests/zero.rs @@ -328,9 +328,11 @@ fn stress_oneshot() { } } -#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn stress_iter() { + #[cfg(miri)] + const COUNT: usize = 50; + #[cfg(not(miri))] const COUNT: usize = 1000; let (request_s, request_r) = bounded(0); @@ -403,7 +405,7 @@ fn drops() { #[cfg(not(miri))] const RUNS: usize = 100; #[cfg(miri)] - const STEPS: usize = 500; + const STEPS: usize = 100; #[cfg(not(miri))] const STEPS: usize = 10_000; @@ -485,7 +487,7 @@ fn fairness() { #[test] fn fairness_duplicates() { #[cfg(miri)] - const COUNT: usize = 50; + const COUNT: usize = 100; #[cfg(not(miri))] const COUNT: usize = 10_000; diff --git a/vendor/crossbeam-deque/.cargo-checksum.json b/vendor/crossbeam-deque/.cargo-checksum.json index c4f2a9329..45404d824 100644 --- a/vendor/crossbeam-deque/.cargo-checksum.json +++ b/vendor/crossbeam-deque/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"7d5f333652da0da5f068ff91ecf259599f9ff4a4448bd987dd451699b66f0f59","Cargo.toml":"a9a138b4e005ddea76f588ca7004629ebd8f1a64cd1d55474fe36cae4c57a890","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"6b0a911f542186ef96eb56537cade0ecf1a5731d5d494b7094ff87f0fdeb7710","src/deque.rs":"64a2153dc566847fd9fa0e6b2b7adb3933af9984fbe3429b6f1200b058bb9850","src/lib.rs":"9f0581481691bc698176f369410726adf597d470b9d14e226a65f490d6aff8c6","tests/fifo.rs":"1d83f9ffeeba2cd6bd32f1ab136d843b8c73075d5045619be12dc3c27d8ab3ba","tests/injector.rs":"6812c97615e3f685b5612c390861f2e570ff469f3b9871ba97ddbed5c1f5266b","tests/lifo.rs":"b2ddc8154492322e734b23f35ce54040f9ec84ef878009de3a64d44d35c365a6","tests/steal.rs":"cdf588cc13eeb275ef1231eb18e3245faca7a2d054fa6527bfdba2a34bc8f7bf"},"package":"6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e"} \ No newline at end of file +{"files":{"CHANGELOG.md":"ad5f2c10299e57aaed2d1b8f8a109faa2dfb16c52ce81f60ec5adb0ea9308d7f","Cargo.toml":"4802e7c0d5ab1dc35c162671483a6ee9bff5a3f1d6dd620a01863ac25068019e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"3c62aa0ee37cf714b5b3c304545d5caea4cc0a71020fccb1f146611d64202bb2","src/deque.rs":"cfb3c5b3bcea1f27ca2633d8b8576ff2080e1e9fc083236f2db7916bb77786ed","src/lib.rs":"ec0257a388627d691d652fd04d261c5c0590e1e31a35c8bf5912afac51fd5734","tests/fifo.rs":"3d98e0d4ca7cfddf10708b71642cf1ff05543d067ad837e48401d63cc31c0a18","tests/injector.rs":"fb054ef9fcac5f12e08b7b3451f370b96ab7589d32ef5c02e25958a473c45519","tests/lifo.rs":"57abdb3fc5920a422f785ba308b658bdc5400947532eeffb799f2395a2061549","tests/steal.rs":"cdf588cc13eeb275ef1231eb18e3245faca7a2d054fa6527bfdba2a34bc8f7bf"},"package":"715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc"} \ No newline at end of file diff --git a/vendor/crossbeam-deque/CHANGELOG.md b/vendor/crossbeam-deque/CHANGELOG.md index 14dcc20b7..855b714f4 100644 --- a/vendor/crossbeam-deque/CHANGELOG.md +++ b/vendor/crossbeam-deque/CHANGELOG.md @@ -1,3 +1,7 @@ +# Version 0.8.2 + +- Bump the minimum supported Rust version to 1.38. (#877) + # Version 0.8.1 - Fix deque steal race condition. (#726) @@ -5,26 +9,40 @@ # Version 0.8.0 +**Note:** This release has been yanked. See [GHSA-pqqp-xmhj-wgcw](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-pqqp-xmhj-wgcw) for details. + - Bump the minimum supported Rust version to 1.36. - Add `Worker::len()` and `Injector::len()` methods. - Add `std` (enabled by default) feature for forward compatibility. +# Version 0.7.4 + +- Fix deque steal race condition. + # Version 0.7.3 +**Note:** This release has been yanked. See [GHSA-pqqp-xmhj-wgcw](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-pqqp-xmhj-wgcw) for details. + - Stop stealing from the same deque. (#448) - Fix unsoundness issues by adopting `MaybeUninit`. (#458) # Version 0.7.2 +**Note:** This release has been yanked. See [GHSA-pqqp-xmhj-wgcw](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-pqqp-xmhj-wgcw) for details. + - Bump `crossbeam-epoch` to `0.8`. - Bump `crossbeam-utils` to `0.7`. # Version 0.7.1 +**Note:** This release has been yanked. See [GHSA-pqqp-xmhj-wgcw](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-pqqp-xmhj-wgcw) for details. + - Bump the minimum required version of `crossbeam-utils`. # Version 0.7.0 +**Note:** This release has been yanked. See [GHSA-pqqp-xmhj-wgcw](https://github.com/crossbeam-rs/crossbeam/security/advisories/GHSA-pqqp-xmhj-wgcw) for details. + - Make `Worker::pop()` faster in the FIFO case. - Replace `fifo()` nad `lifo()` with `Worker::new_fifo()` and `Worker::new_lifo()`. - Add more batched steal methods. diff --git a/vendor/crossbeam-deque/Cargo.toml b/vendor/crossbeam-deque/Cargo.toml index 3ea5a59f6..4ff10b353 100644 --- a/vendor/crossbeam-deque/Cargo.toml +++ b/vendor/crossbeam-deque/Cargo.toml @@ -11,16 +11,26 @@ [package] edition = "2018" +rust-version = "1.38" name = "crossbeam-deque" -version = "0.8.1" -authors = ["The Crossbeam Project Developers"] +version = "0.8.2" description = "Concurrent work-stealing deque" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque" -documentation = "https://docs.rs/crossbeam-deque" -keywords = ["chase-lev", "lock-free", "scheduler", "scheduling"] -categories = ["algorithms", "concurrency", "data-structures"] +readme = "README.md" +keywords = [ + "chase-lev", + "lock-free", + "scheduler", + "scheduling", +] +categories = [ + "algorithms", + "concurrency", + "data-structures", +] license = "MIT OR Apache-2.0" repository = "https://github.com/crossbeam-rs/crossbeam" + [dependencies.cfg-if] version = "1" @@ -33,9 +43,13 @@ default-features = false version = "0.8" optional = true default-features = false + [dev-dependencies.rand] version = "0.8" [features] default = ["std"] -std = ["crossbeam-epoch/std", "crossbeam-utils/std"] +std = [ + "crossbeam-epoch/std", + "crossbeam-utils/std", +] diff --git a/vendor/crossbeam-deque/README.md b/vendor/crossbeam-deque/README.md index 8ad1a7278..23c8794c2 100644 --- a/vendor/crossbeam-deque/README.md +++ b/vendor/crossbeam-deque/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque#license) https://crates.io/crates/crossbeam-deque) [![Documentation](https://docs.rs/crossbeam-deque/badge.svg)]( https://docs.rs/crossbeam-deque) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( +[![Rust 1.38+](https://img.shields.io/badge/rust-1.38+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) @@ -28,7 +28,7 @@ crossbeam-deque = "0.8" Crossbeam Deque supports stable Rust releases going back at least six months, and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. +version is released. Currently, the minimum supported Rust version is 1.38. ## License diff --git a/vendor/crossbeam-deque/src/deque.rs b/vendor/crossbeam-deque/src/deque.rs index 802a2fef5..bda3bf820 100644 --- a/vendor/crossbeam-deque/src/deque.rs +++ b/vendor/crossbeam-deque/src/deque.rs @@ -3,7 +3,7 @@ use std::cmp; use std::fmt; use std::iter::FromIterator; use std::marker::PhantomData; -use std::mem::{self, MaybeUninit}; +use std::mem::{self, ManuallyDrop, MaybeUninit}; use std::ptr; use std::sync::atomic::{self, AtomicIsize, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; @@ -38,9 +38,8 @@ impl Buffer { fn alloc(cap: usize) -> Buffer { debug_assert_eq!(cap, cap.next_power_of_two()); - let mut v = Vec::with_capacity(cap); + let mut v = ManuallyDrop::new(Vec::with_capacity(cap)); let ptr = v.as_mut_ptr(); - mem::forget(v); Buffer { ptr, cap } } @@ -53,6 +52,8 @@ impl Buffer { /// Returns a pointer to the task at the specified `index`. unsafe fn at(&self, index: isize) -> *mut T { // `self.cap` is always a power of two. + // We do all the loads at `MaybeUninit` because we might realize, after loading, that we + // don't actually have the right to access this memory. self.ptr.offset(index & (self.cap - 1) as isize) } @@ -62,8 +63,8 @@ impl Buffer { /// technically speaking a data race and therefore UB. We should use an atomic store here, but /// that would be more expensive and difficult to implement generically for all types `T`. /// Hence, as a hack, we use a volatile write instead. - unsafe fn write(&self, index: isize, task: T) { - ptr::write_volatile(self.at(index), task) + unsafe fn write(&self, index: isize, task: MaybeUninit) { + ptr::write_volatile(self.at(index).cast::>(), task) } /// Reads a task from the specified `index`. @@ -71,9 +72,9 @@ impl Buffer { /// This method might be concurrently called with another `write` at the same index, which is /// technically speaking a data race and therefore UB. We should use an atomic load here, but /// that would be more expensive and difficult to implement generically for all types `T`. - /// Hence, as a hack, we use a volatile write instead. - unsafe fn read(&self, index: isize) -> T { - ptr::read_volatile(self.at(index)) + /// Hence, as a hack, we use a volatile load instead. + unsafe fn read(&self, index: isize) -> MaybeUninit { + ptr::read_volatile(self.at(index).cast::>()) } } @@ -115,8 +116,8 @@ struct Inner { impl Drop for Inner { fn drop(&mut self) { // Load the back index, front index, and buffer. - let b = self.back.load(Ordering::Relaxed); - let f = self.front.load(Ordering::Relaxed); + let b = *self.back.get_mut(); + let f = *self.front.get_mut(); unsafe { let buffer = self.buffer.load(Ordering::Relaxed, epoch::unprotected()); @@ -406,7 +407,7 @@ impl Worker { // Write `task` into the slot. unsafe { - buffer.write(b, task); + buffer.write(b, MaybeUninit::new(task)); } atomic::fence(Ordering::Release); @@ -461,7 +462,7 @@ impl Worker { unsafe { // Read the popped task. let buffer = self.buffer.get(); - let task = buffer.read(f); + let task = buffer.read(f).assume_init(); // Shrink the buffer if `len - 1` is less than one fourth of the capacity. if buffer.cap > MIN_CAP && len <= buffer.cap as isize / 4 { @@ -509,8 +510,8 @@ impl Worker { ) .is_err() { - // Failed. We didn't pop anything. - mem::forget(task.take()); + // Failed. We didn't pop anything. Reset to `None`. + task.take(); } // Restore the back index to the original task. @@ -524,7 +525,7 @@ impl Worker { } } - task + task.map(|t| unsafe { t.assume_init() }) } } } @@ -661,12 +662,11 @@ impl Stealer { .is_err() { // We didn't steal this task, forget it. - mem::forget(task); return Steal::Retry; } // Return the stolen task. - Steal::Success(task) + Steal::Success(unsafe { task.assume_init() }) } /// Steals a batch of tasks and pushes them into another worker. @@ -821,7 +821,6 @@ impl Stealer { .is_err() { // We didn't steal this task, forget it and break from the loop. - mem::forget(task); batch_size = i; break; } @@ -975,7 +974,6 @@ impl Stealer { .is_err() { // We didn't steal this task, forget it. - mem::forget(task); return Steal::Retry; } @@ -992,7 +990,6 @@ impl Stealer { .is_err() { // We didn't steal this task, forget it. - mem::forget(task); return Steal::Retry; } @@ -1037,7 +1034,6 @@ impl Stealer { .is_err() { // We didn't steal this task, forget it and break from the loop. - mem::forget(tmp); batch_size = i; break; } @@ -1077,7 +1073,7 @@ impl Stealer { dest.inner.back.store(dest_b, Ordering::Release); // Return with success. - Steal::Success(task) + Steal::Success(unsafe { task.assume_init() }) } } @@ -1123,6 +1119,11 @@ struct Slot { } impl Slot { + const UNINIT: Self = Self { + task: UnsafeCell::new(MaybeUninit::uninit()), + state: AtomicUsize::new(0), + }; + /// Waits until a task is written into the slot. fn wait_write(&self) { let backoff = Backoff::new(); @@ -1146,13 +1147,10 @@ struct Block { impl Block { /// Creates an empty block that starts at `start_index`. fn new() -> Block { - // SAFETY: This is safe because: - // [1] `Block::next` (AtomicPtr) may be safely zero initialized. - // [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4]. - // [3] `Slot::task` (UnsafeCell) may be safely zero initialized because it - // holds a MaybeUninit. - // [4] `Slot::state` (AtomicUsize) may be safely zero initialized. - unsafe { MaybeUninit::zeroed().assume_init() } + Self { + next: AtomicPtr::new(ptr::null_mut()), + slots: [Slot::UNINIT; BLOCK_CAP], + } } /// Waits until the next pointer is set. @@ -1535,7 +1533,7 @@ impl Injector { // Read the task. let slot = (*block).slots.get_unchecked(offset + i); slot.wait_write(); - let task = slot.task.get().read().assume_init(); + let task = slot.task.get().read(); // Write it into the destination queue. dest_buffer.write(dest_b.wrapping_add(i as isize), task); @@ -1547,7 +1545,7 @@ impl Injector { // Read the task. let slot = (*block).slots.get_unchecked(offset + i); slot.wait_write(); - let task = slot.task.get().read().assume_init(); + let task = slot.task.get().read(); // Write it into the destination queue. dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task); @@ -1689,7 +1687,7 @@ impl Injector { // Read the task. let slot = (*block).slots.get_unchecked(offset); slot.wait_write(); - let task = slot.task.get().read().assume_init(); + let task = slot.task.get().read(); match dest.flavor { Flavor::Fifo => { @@ -1698,7 +1696,7 @@ impl Injector { // Read the task. let slot = (*block).slots.get_unchecked(offset + i + 1); slot.wait_write(); - let task = slot.task.get().read().assume_init(); + let task = slot.task.get().read(); // Write it into the destination queue. dest_buffer.write(dest_b.wrapping_add(i as isize), task); @@ -1711,7 +1709,7 @@ impl Injector { // Read the task. let slot = (*block).slots.get_unchecked(offset + i + 1); slot.wait_write(); - let task = slot.task.get().read().assume_init(); + let task = slot.task.get().read(); // Write it into the destination queue. dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task); @@ -1744,7 +1742,7 @@ impl Injector { } } - Steal::Success(task) + Steal::Success(task.assume_init()) } } @@ -1820,9 +1818,9 @@ impl Injector { impl Drop for Injector { fn drop(&mut self) { - let mut head = self.head.index.load(Ordering::Relaxed); - let mut tail = self.tail.index.load(Ordering::Relaxed); - let mut block = self.head.block.load(Ordering::Relaxed); + let mut head = *self.head.index.get_mut(); + let mut tail = *self.tail.index.get_mut(); + let mut block = *self.head.block.get_mut(); // Erase the lower bits. head &= !((1 << SHIFT) - 1); @@ -1840,7 +1838,7 @@ impl Drop for Injector { p.as_mut_ptr().drop_in_place(); } else { // Deallocate the block and move to the next one. - let next = (*block).next.load(Ordering::Relaxed); + let next = *(*block).next.get_mut(); drop(Box::from_raw(block)); block = next; } diff --git a/vendor/crossbeam-deque/src/lib.rs b/vendor/crossbeam-deque/src/lib.rs index 16bc728b3..b696b5f96 100644 --- a/vendor/crossbeam-deque/src/lib.rs +++ b/vendor/crossbeam-deque/src/lib.rs @@ -95,6 +95,7 @@ rust_2018_idioms, unreachable_pub )] +#![allow(clippy::question_mark)] // https://github.com/rust-lang/rust-clippy/issues/8281 #![cfg_attr(not(feature = "std"), no_std)] use cfg_if::cfg_if; diff --git a/vendor/crossbeam-deque/tests/fifo.rs b/vendor/crossbeam-deque/tests/fifo.rs index e2365fb91..f98737b58 100644 --- a/vendor/crossbeam-deque/tests/fifo.rs +++ b/vendor/crossbeam-deque/tests/fifo.rs @@ -71,6 +71,9 @@ fn is_empty() { #[test] fn spsc() { + #[cfg(miri)] + const STEPS: usize = 500; + #[cfg(not(miri))] const STEPS: usize = 50_000; let w = Worker::new_fifo(); @@ -100,6 +103,9 @@ fn spsc() { #[test] fn stampede() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let w = Worker::new_fifo(); @@ -141,6 +147,9 @@ fn stampede() { #[test] fn stress() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let w = Worker::new_fifo(); @@ -197,6 +206,7 @@ fn stress() { .unwrap(); } +#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn no_starvation() { const THREADS: usize = 8; @@ -258,8 +268,17 @@ fn no_starvation() { #[test] fn destructors() { + #[cfg(miri)] + const THREADS: usize = 2; + #[cfg(not(miri))] const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; + #[cfg(miri)] + const STEPS: usize = 100; + #[cfg(not(miri))] const STEPS: usize = 1000; struct Elem(usize, Arc>>); @@ -330,7 +349,7 @@ fn destructors() { { let mut v = dropped.lock().unwrap(); assert_eq!(v.len(), rem); - v.sort(); + v.sort_unstable(); for pair in v.windows(2) { assert_eq!(pair[0] + 1, pair[1]); } diff --git a/vendor/crossbeam-deque/tests/injector.rs b/vendor/crossbeam-deque/tests/injector.rs index 3f74d1bfb..f706a8d9c 100644 --- a/vendor/crossbeam-deque/tests/injector.rs +++ b/vendor/crossbeam-deque/tests/injector.rs @@ -46,6 +46,9 @@ fn is_empty() { #[test] fn spsc() { + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 100_000; let q = Injector::new(); @@ -58,6 +61,8 @@ fn spsc() { assert_eq!(i, v); break; } + #[cfg(miri)] + std::hint::spin_loop(); } } @@ -73,6 +78,9 @@ fn spsc() { #[test] fn mpmc() { + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 25_000; const THREADS: usize = 4; @@ -96,6 +104,8 @@ fn mpmc() { v[n].fetch_add(1, SeqCst); break; } + #[cfg(miri)] + std::hint::spin_loop(); } } }); @@ -111,6 +121,9 @@ fn mpmc() { #[test] fn stampede() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let q = Injector::new(); @@ -152,6 +165,9 @@ fn stampede() { #[test] fn stress() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let q = Injector::new(); @@ -208,6 +224,7 @@ fn stress() { .unwrap(); } +#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn no_starvation() { const THREADS: usize = 8; @@ -269,8 +286,17 @@ fn no_starvation() { #[test] fn destructors() { + #[cfg(miri)] + const THREADS: usize = 2; + #[cfg(not(miri))] const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; + #[cfg(miri)] + const STEPS: usize = 100; + #[cfg(not(miri))] const STEPS: usize = 1000; struct Elem(usize, Arc>>); @@ -341,7 +367,7 @@ fn destructors() { { let mut v = dropped.lock().unwrap(); assert_eq!(v.len(), rem); - v.sort(); + v.sort_unstable(); for pair in v.windows(2) { assert_eq!(pair[0] + 1, pair[1]); } diff --git a/vendor/crossbeam-deque/tests/lifo.rs b/vendor/crossbeam-deque/tests/lifo.rs index 3e99e95c5..c1a65cd2e 100644 --- a/vendor/crossbeam-deque/tests/lifo.rs +++ b/vendor/crossbeam-deque/tests/lifo.rs @@ -71,6 +71,9 @@ fn is_empty() { #[test] fn spsc() { + #[cfg(miri)] + const STEPS: usize = 500; + #[cfg(not(miri))] const STEPS: usize = 50_000; let w = Worker::new_lifo(); @@ -84,6 +87,8 @@ fn spsc() { assert_eq!(i, v); break; } + #[cfg(miri)] + std::hint::spin_loop(); } } @@ -100,6 +105,9 @@ fn spsc() { #[test] fn stampede() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let w = Worker::new_lifo(); @@ -141,6 +149,9 @@ fn stampede() { #[test] fn stress() { const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; let w = Worker::new_lifo(); @@ -197,6 +208,7 @@ fn stress() { .unwrap(); } +#[cfg_attr(miri, ignore)] // Miri is too slow #[test] fn no_starvation() { const THREADS: usize = 8; @@ -258,8 +270,17 @@ fn no_starvation() { #[test] fn destructors() { + #[cfg(miri)] + const THREADS: usize = 2; + #[cfg(not(miri))] const THREADS: usize = 8; + #[cfg(miri)] + const COUNT: usize = 500; + #[cfg(not(miri))] const COUNT: usize = 50_000; + #[cfg(miri)] + const STEPS: usize = 100; + #[cfg(not(miri))] const STEPS: usize = 1000; struct Elem(usize, Arc>>); @@ -330,7 +351,7 @@ fn destructors() { { let mut v = dropped.lock().unwrap(); assert_eq!(v.len(), rem); - v.sort(); + v.sort_unstable(); for pair in v.windows(2) { assert_eq!(pair[0] + 1, pair[1]); } diff --git a/vendor/crossbeam-epoch/.cargo-checksum.json b/vendor/crossbeam-epoch/.cargo-checksum.json index beb3eb1dd..d069e3a4b 100644 --- a/vendor/crossbeam-epoch/.cargo-checksum.json +++ b/vendor/crossbeam-epoch/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"709c5824af9170953e84db2552f4e8ae84d115314b59b768c62bdcd13c157e82","Cargo.lock":"cd480e52977de5a2e4182c1620fb5da9134fe82bfc6f696905ec0a1e1bd3d039","Cargo.toml":"1506e2615575ffc45c05dbcc248687740f04de5732b30bdb2d828ef4c4ae809b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"f946b25082979595d3851d90c4e76424be921a779e88e982f8455d44d46057ec","benches/defer.rs":"c330b704d96b2ad1aed29f72c37a99da534adef8cb06a3976d5f93bf567abb20","benches/flush.rs":"0389ac6c473632f0e93c962f223404cc360257f6699b4ec90b9b3be16bb6d74f","benches/pin.rs":"2f649a5153745c7930efdb32a52f9dc522f7b8cf548a251c5e2c82ee25dc3fff","build.rs":"aec5ae4d47d6ab1f281db6b7f7ec80ab3cc05bd0c20059643aee4446fcc0fcbf","examples/sanitize.rs":"a39d1635fa61e643e59192d7a63becc97ff81f03c1f4e03d38cedefb1525026a","no_atomic.rs":"916ed15218bb7b75a4e0d432430e7134efd27ca43ca8a8766e0c90e89febb602","src/atomic.rs":"6452c856fd808e99c8fc09fe7b563ce44342f9992b38c65613933c7c3fc5d84c","src/collector.rs":"e2d9780d8707e49360b3c33f2f829f29f70e6929307e65e23449b8ba6def6358","src/default.rs":"9c4d3951981d47efc748674d64b22eff27ecb2e3ef16369aa423592740ce6033","src/deferred.rs":"8ced786536d8d688381a8aa0b61e6e4d5e4fdd88e892cf82c0c5731e4801aa60","src/epoch.rs":"d31e66d8fe62299928e25867336d96391b26a4fe890a1cae0885dfcf36d6835b","src/guard.rs":"55c56ca1b2fbc067ae21108f0f7de4be91e5b41df2492055b635ed436782dd52","src/internal.rs":"67a6811b8c58e1152fd1dc17e389884025a0d99d79ab03dee26efcd0d6896690","src/lib.rs":"1c0765413dd66d4655e6417a69829ac5c2f4d504f66f77a87fe9c230c05e039d","src/sync/list.rs":"10aa4c59845ab9ff1d8bcb6f594b70bbe23c320fa7a2b125fdf85df88b9d61e2","src/sync/mod.rs":"cbc6334460d73761c3dea7f99ed2ccbf267d5da3bc76c812e94f85c9f4565c6a","src/sync/queue.rs":"06173b2255677d0d39178ceb49876fda2878f491e907c595eb65643dbb43c9ba","tests/loom.rs":"db772f4478966de6ec98774ca4093171dc942da635822a0d2d3257d31188cb9b"},"package":"07db9d94cbd326813772c968ccd25999e5f8ae22f4f8d1b11effa37ef6ce281d"} \ No newline at end of file +{"files":{"CHANGELOG.md":"930bdf6d05b1fae72bb844f6c26e0a35cc83b810a987baaf5d279044d3b3f74d","Cargo.lock":"ce25f4d162a39d180e7369954bc512ab2ab1ab3b04f6f071cb2212bd43b3bbc3","Cargo.toml":"f2a34cbd48fff1346070f503da83c9149db91c7a098a0b486007fd6a39ba6a1b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"d67d0cf57751a019707dd95785345ee181a10ea80237789bc3c19bf28c0d45ca","benches/defer.rs":"c330b704d96b2ad1aed29f72c37a99da534adef8cb06a3976d5f93bf567abb20","benches/flush.rs":"0389ac6c473632f0e93c962f223404cc360257f6699b4ec90b9b3be16bb6d74f","benches/pin.rs":"2f649a5153745c7930efdb32a52f9dc522f7b8cf548a251c5e2c82ee25dc3fff","build.rs":"89e236e4e22dd748720129dcd02edfc08adccf708a7f0b03e41780e5bafb39cc","examples/sanitize.rs":"a39d1635fa61e643e59192d7a63becc97ff81f03c1f4e03d38cedefb1525026a","no_atomic.rs":"f58085b9d0666ccf62e0ae17fb5dae937c0a86fcc55dc0ae04ad8659e696a49c","src/atomic.rs":"1bd4275c1411852024533e8a70959dfedf72029e3253544d1fbb0cc18b6fd519","src/collector.rs":"29e5911f61510247659b0090517bd1a38d11e1ed86e35811603cb599962d9a58","src/default.rs":"62edf5e1f934eb82d8d7f010d6f25366e6851145a6f0a162372202bb63da1f3a","src/deferred.rs":"0c87df5797212778edd3c2d5fcf0cc04e8b9ed100261ecf9522f74a90804a3d5","src/epoch.rs":"d31e66d8fe62299928e25867336d96391b26a4fe890a1cae0885dfcf36d6835b","src/guard.rs":"f4439909152d38c03b6dfb6eeba6c9f07c39962187d461c92a492c27c258670b","src/internal.rs":"ac40ce276f0ed3dfd561926b78f775592eabb90790e177edde41fe50c13b8256","src/lib.rs":"a036d73230d0574011e67be11d275fe46439a1b5fc3295cb242d9179e5e0a220","src/sync/list.rs":"10aa4c59845ab9ff1d8bcb6f594b70bbe23c320fa7a2b125fdf85df88b9d61e2","src/sync/mod.rs":"326e32489d467e974c441120640a8338aa55da55c24b20276075ce9053997326","src/sync/once_lock.rs":"c03dc9c05a817e087dccf8b682f7307501542805533551da3c2bab442bc40743","src/sync/queue.rs":"06173b2255677d0d39178ceb49876fda2878f491e907c595eb65643dbb43c9ba","tests/loom.rs":"db772f4478966de6ec98774ca4093171dc942da635822a0d2d3257d31188cb9b"},"package":"f916dfc5d356b0ed9dae65f1db9fc9770aa2851d2662b988ccf4fe3516e86348"} \ No newline at end of file diff --git a/vendor/crossbeam-epoch/CHANGELOG.md b/vendor/crossbeam-epoch/CHANGELOG.md index 2f70edba7..3aac87b7f 100644 --- a/vendor/crossbeam-epoch/CHANGELOG.md +++ b/vendor/crossbeam-epoch/CHANGELOG.md @@ -1,3 +1,14 @@ +# Version 0.9.11 + +- Removes the dependency on the `once_cell` crate to restore the MSRV. (#913) +- Work around [rust-lang#98302](https://github.com/rust-lang/rust/issues/98302), which causes compile error on windows-gnu when LTO is enabled. (#913) + +# Version 0.9.10 + +- Bump the minimum supported Rust version to 1.38. (#877) +- Mitigate the risk of segmentation faults in buggy downstream implementations. (#879) +- Add `{Atomic, Shared}::try_into_owned` (#701) + # Version 0.9.9 - Replace lazy_static with once_cell. (#817) diff --git a/vendor/crossbeam-epoch/Cargo.lock b/vendor/crossbeam-epoch/Cargo.lock index edb0c7378..3ded5c77e 100644 --- a/vendor/crossbeam-epoch/Cargo.lock +++ b/vendor/crossbeam-epoch/Cargo.lock @@ -31,14 +31,13 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "crossbeam-epoch" -version = "0.9.9" +version = "0.9.11" dependencies = [ "autocfg", "cfg-if", "crossbeam-utils", "loom", "memoffset", - "once_cell", "rand", "rustversion", "scopeguard", @@ -46,26 +45,25 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.9" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ff1f980957787286a554052d03c7aee98d99cc32e09f6d45f0a814133c87978" +checksum = "edbafec5fa1f196ca66527c1b12c2ec4745ca14b50f1ad8f9f6f720b55d11fac" dependencies = [ "cfg-if", "loom", - "once_cell", ] [[package]] name = "generator" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d9279ca822891c1a4dae06d185612cf8fc6acfe5dff37781b41297811b12ee" +checksum = "cc184cace1cea8335047a471cc1da80f18acf8a76f3bab2028d499e328948ec7" dependencies = [ "cc", "libc", "log", "rustversion", - "winapi", + "windows", ] [[package]] @@ -87,9 +85,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.126" +version = "0.2.133" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" +checksum = "c0f80d65747a3e43d1596c7c5492d95d5edddaabd45a7fcdb02b95f644164966" [[package]] name = "log" @@ -133,9 +131,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.12.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" +checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1" [[package]] name = "pin-project-lite" @@ -151,18 +149,18 @@ checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" [[package]] name = "proc-macro2" -version = "1.0.39" +version = "1.0.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" +checksum = "94e2ef8dbfc347b10c094890f778ee2e36ca9bb4262e86dc99cd217e35f3470b" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.18" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] @@ -190,18 +188,18 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "regex" -version = "1.5.6" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" +checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" dependencies = [ "regex-syntax", ] @@ -217,15 +215,15 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.26" +version = "0.6.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" +checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" [[package]] name = "rustversion" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" +checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" [[package]] name = "scoped-tls" @@ -250,15 +248,15 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" +checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" [[package]] name = "syn" -version = "1.0.96" +version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0748dd251e24453cb8717f0354206b91557e4ec8703673a4b30208f2abaf1ebf" +checksum = "e90cde112c4b9690b8cbe810cba9ddd8bc1d7472e2cae317b69e9438c1cba7d2" dependencies = [ "proc-macro2", "quote", @@ -276,9 +274,9 @@ dependencies = [ [[package]] name = "tracing" -version = "0.1.35" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a400e31aa60b9d44a52a8ee0343b5b18566b03a8321e0d321f695cf56e940160" +checksum = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307" dependencies = [ "cfg-if", "pin-project-lite", @@ -288,9 +286,9 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" +checksum = "11c75893af559bc8e10716548bdef5cb2b983f8e637db9d0e15126b61b484ee2" dependencies = [ "proc-macro2", "quote", @@ -299,9 +297,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.27" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709595b8878a4965ce5e87ebf880a7d39c9afc6837721b21a5a816a8117d921" +checksum = "5aeea4303076558a00714b823f9ad67d58a3bbda1df83d8827d21193156e22f7" dependencies = [ "once_cell", "valuable", @@ -320,13 +318,13 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.11" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bc28f93baff38037f64e6f43d34cfa1605f27a49c34e8a04c5e78b0babf2596" +checksum = "60db860322da191b40952ad9affe65ea23e7dd6a5c442c2c42865810c6ab8e6b" dependencies = [ "ansi_term", - "lazy_static", "matchers", + "once_cell", "regex", "sharded-slab", "smallvec", @@ -338,9 +336,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.1" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" +checksum = "dcc811dc4066ac62f84f11307873c4850cb653bfa9b1719cee2bd2204a4bc5dd" [[package]] name = "valuable" @@ -375,3 +373,46 @@ name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbedf6db9096bc2364adce0ae0aa636dcd89f3c3f2cd67947062aaf0ca2a10ec" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8e92753b1c443191654ec532f14c199742964a061be25d77d7a96f09db20bf5" + +[[package]] +name = "windows_i686_gnu" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a711c68811799e017b6038e0922cb27a5e2f43a2ddb609fe0b6f3eeda9de615" + +[[package]] +name = "windows_i686_msvc" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c11bb1a02615db74680b32a68e2d61f553cc24c4eb5b4ca10311740e44172" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c912b12f7454c6620635bbff3450962753834be2a594819bd5e945af18ec64bc" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "504a2476202769977a040c6364301a3f65d0cc9e3fb08600b2bda150a0488316" diff --git a/vendor/crossbeam-epoch/Cargo.toml b/vendor/crossbeam-epoch/Cargo.toml index 9d68295e6..0f8e23864 100644 --- a/vendor/crossbeam-epoch/Cargo.toml +++ b/vendor/crossbeam-epoch/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2018" -rust-version = "1.36" +rust-version = "1.38" name = "crossbeam-epoch" -version = "0.9.9" +version = "0.9.11" description = "Epoch-based garbage collection" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch" readme = "README.md" @@ -41,10 +41,6 @@ default-features = false [dependencies.memoffset] version = "0.6" -[dependencies.once_cell] -version = "1" -optional = true - [dependencies.scopeguard] version = "1.1" default-features = false @@ -69,7 +65,6 @@ nightly = ["crossbeam-utils/nightly"] std = [ "alloc", "crossbeam-utils/std", - "once_cell", ] [target."cfg(crossbeam_loom)".dependencies.loom-crate] diff --git a/vendor/crossbeam-epoch/README.md b/vendor/crossbeam-epoch/README.md index eb33badff..2840ea792 100644 --- a/vendor/crossbeam-epoch/README.md +++ b/vendor/crossbeam-epoch/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch#license) https://crates.io/crates/crossbeam-epoch) [![Documentation](https://docs.rs/crossbeam-epoch/badge.svg)]( https://docs.rs/crossbeam-epoch) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( +[![Rust 1.38+](https://img.shields.io/badge/rust-1.38+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) @@ -35,7 +35,7 @@ crossbeam-epoch = "0.9" Crossbeam Epoch supports stable Rust releases going back at least six months, and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. +version is released. Currently, the minimum supported Rust version is 1.38. ## License diff --git a/vendor/crossbeam-epoch/build.rs b/vendor/crossbeam-epoch/build.rs index bba54d999..b3bd15a5a 100644 --- a/vendor/crossbeam-epoch/build.rs +++ b/vendor/crossbeam-epoch/build.rs @@ -41,17 +41,15 @@ fn main() { } }; - // Note that this is `no_*`, not `has_*`. This allows treating - // `cfg(target_has_atomic = "ptr")` as true when the build script doesn't - // run. This is needed for compatibility with non-cargo build systems that - // don't run the build script. + // Note that this is `no_`*, not `has_*`. This allows treating as the latest + // stable rustc is used when the build script doesn't run. This is useful + // for non-cargo build systems that don't run the build script. if NO_ATOMIC_CAS.contains(&&*target) { println!("cargo:rustc-cfg=crossbeam_no_atomic_cas"); } - if cfg.probe_rustc_version(1, 61) { - // TODO: invert cfg once Rust 1.61 became stable. - println!("cargo:rustc-cfg=crossbeam_const_fn_trait_bound"); + if !cfg.probe_rustc_version(1, 61) { + println!("cargo:rustc-cfg=crossbeam_no_const_fn_trait_bound"); } println!("cargo:rerun-if-changed=no_atomic.rs"); diff --git a/vendor/crossbeam-epoch/no_atomic.rs b/vendor/crossbeam-epoch/no_atomic.rs index f740aaee1..675d9a27e 100644 --- a/vendor/crossbeam-epoch/no_atomic.rs +++ b/vendor/crossbeam-epoch/no_atomic.rs @@ -2,6 +2,8 @@ // It is not intended for manual editing. const NO_ATOMIC_CAS: &[&str] = &[ + "armv4t-none-eabi", + "armv5te-none-eabi", "avr-unknown-gnu-atmega328", "bpfeb-unknown-none", "bpfel-unknown-none", @@ -10,6 +12,7 @@ const NO_ATOMIC_CAS: &[&str] = &[ "riscv32im-unknown-none-elf", "riscv32imc-unknown-none-elf", "thumbv4t-none-eabi", + "thumbv5te-none-eabi", "thumbv6m-none-eabi", ]; @@ -18,7 +21,9 @@ const NO_ATOMIC_64: &[&str] = &[ "arm-linux-androideabi", "armebv7r-none-eabi", "armebv7r-none-eabihf", + "armv4t-none-eabi", "armv4t-unknown-linux-gnueabi", + "armv5te-none-eabi", "armv5te-unknown-linux-gnueabi", "armv5te-unknown-linux-musleabi", "armv5te-unknown-linux-uclibceabi", @@ -55,6 +60,7 @@ const NO_ATOMIC_64: &[&str] = &[ "riscv32imac-unknown-xous-elf", "riscv32imc-unknown-none-elf", "thumbv4t-none-eabi", + "thumbv5te-none-eabi", "thumbv6m-none-eabi", "thumbv7em-none-eabi", "thumbv7em-none-eabihf", diff --git a/vendor/crossbeam-epoch/src/atomic.rs b/vendor/crossbeam-epoch/src/atomic.rs index b0b6a68e7..19bab4729 100644 --- a/vendor/crossbeam-epoch/src/atomic.rs +++ b/vendor/crossbeam-epoch/src/atomic.rs @@ -252,7 +252,7 @@ impl Pointable for [MaybeUninit] { let size = mem::size_of::>() + mem::size_of::>() * len; let align = mem::align_of::>(); let layout = alloc::Layout::from_size_align(size, align).unwrap(); - let ptr = alloc::alloc(layout) as *mut Array; + let ptr = alloc::alloc(layout).cast::>(); if ptr.is_null() { alloc::handle_alloc_error(layout); } @@ -305,6 +305,7 @@ impl Atomic { /// use crossbeam_epoch::Atomic; /// /// let a = Atomic::new(1234); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn new(init: T) -> Atomic { Self::init(init) @@ -320,6 +321,7 @@ impl Atomic { /// use crossbeam_epoch::Atomic; /// /// let a = Atomic::::init(1234); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn init(init: T::Init) -> Atomic { Self::from(Owned::init(init)) @@ -342,7 +344,7 @@ impl Atomic { /// /// let a = Atomic::::null(); /// ``` - #[cfg(all(crossbeam_const_fn_trait_bound, not(crossbeam_loom)))] + #[cfg(all(not(crossbeam_no_const_fn_trait_bound), not(crossbeam_loom)))] pub const fn null() -> Atomic { Self { data: AtomicUsize::new(0), @@ -351,7 +353,7 @@ impl Atomic { } /// Returns a new null atomic pointer. - #[cfg(not(all(crossbeam_const_fn_trait_bound, not(crossbeam_loom))))] + #[cfg(not(all(not(crossbeam_no_const_fn_trait_bound), not(crossbeam_loom))))] pub fn null() -> Atomic { Self { data: AtomicUsize::new(0), @@ -373,6 +375,7 @@ impl Atomic { /// let a = Atomic::new(1234); /// let guard = &epoch::pin(); /// let p = a.load(SeqCst, guard); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn load<'g>(&self, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { unsafe { Shared::from_usize(self.data.load(ord)) } @@ -398,6 +401,7 @@ impl Atomic { /// let a = Atomic::new(1234); /// let guard = &epoch::pin(); /// let p = a.load_consume(guard); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn load_consume<'g>(&self, _: &'g Guard) -> Shared<'g, T> { unsafe { Shared::from_usize(self.data.load_consume()) } @@ -415,8 +419,10 @@ impl Atomic { /// use std::sync::atomic::Ordering::SeqCst; /// /// let a = Atomic::new(1234); + /// # unsafe { drop(a.load(SeqCst, &crossbeam_epoch::pin()).into_owned()); } // avoid leak /// a.store(Shared::null(), SeqCst); /// a.store(Owned::new(1234), SeqCst); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn store>(&self, new: P, ord: Ordering) { self.data.store(new.into_usize(), ord); @@ -437,6 +443,7 @@ impl Atomic { /// let a = Atomic::new(1234); /// let guard = &epoch::pin(); /// let p = a.swap(Shared::null(), SeqCst, guard); + /// # unsafe { drop(p.into_owned()); } // avoid leak /// ``` pub fn swap<'g, P: Pointer>(&self, new: P, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { unsafe { Shared::from_usize(self.data.swap(new.into_usize(), ord)) } @@ -471,6 +478,7 @@ impl Atomic { /// let curr = a.load(SeqCst, guard); /// let res1 = a.compare_exchange(curr, Shared::null(), SeqCst, SeqCst, guard); /// let res2 = a.compare_exchange(curr, Owned::new(5678), SeqCst, SeqCst, guard); + /// # unsafe { drop(curr.into_owned()); } // avoid leak /// ``` pub fn compare_exchange<'g, P>( &self, @@ -526,6 +534,7 @@ impl Atomic { /// /// let mut new = Owned::new(5678); /// let mut ptr = a.load(SeqCst, guard); + /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak /// loop { /// match a.compare_exchange_weak(ptr, new, SeqCst, SeqCst, guard) { /// Ok(p) => { @@ -546,6 +555,7 @@ impl Atomic { /// Err(err) => curr = err.current, /// } /// } + /// # unsafe { drop(curr.into_owned()); } // avoid leak /// ``` pub fn compare_exchange_weak<'g, P>( &self, @@ -608,6 +618,7 @@ impl Atomic { /// /// let res2 = a.fetch_update(SeqCst, SeqCst, guard, |x| None); /// assert!(res2.is_err()); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn fetch_update<'g, F>( &self, @@ -666,6 +677,7 @@ impl Atomic { /// let curr = a.load(SeqCst, guard); /// let res1 = a.compare_and_set(curr, Shared::null(), SeqCst, guard); /// let res2 = a.compare_and_set(curr, Owned::new(5678), SeqCst, guard); + /// # unsafe { drop(curr.into_owned()); } // avoid leak /// ``` // TODO: remove in the next major version. #[allow(deprecated)] @@ -723,6 +735,7 @@ impl Atomic { /// /// let mut new = Owned::new(5678); /// let mut ptr = a.load(SeqCst, guard); + /// # unsafe { drop(a.load(SeqCst, guard).into_owned()); } // avoid leak /// loop { /// match a.compare_and_set_weak(ptr, new, SeqCst, guard) { /// Ok(p) => { @@ -743,6 +756,7 @@ impl Atomic { /// Err(err) => curr = err.current, /// } /// } + /// # unsafe { drop(curr.into_owned()); } // avoid leak /// ``` // TODO: remove in the next major version. #[allow(deprecated)] @@ -877,6 +891,52 @@ impl Atomic { Owned::from_usize(self.data.into_inner()) } } + + /// Takes ownership of the pointee if it is non-null. + /// + /// This consumes the atomic and converts it into [`Owned`]. As [`Atomic`] doesn't have a + /// destructor and doesn't drop the pointee while [`Owned`] does, this is suitable for + /// destructors of data structures. + /// + /// # Safety + /// + /// This method may be called only if the pointer is valid and nobody else is holding a + /// reference to the same object, or the pointer is null. + /// + /// # Examples + /// + /// ```rust + /// # use std::mem; + /// # use crossbeam_epoch::Atomic; + /// struct DataStructure { + /// ptr: Atomic, + /// } + /// + /// impl Drop for DataStructure { + /// fn drop(&mut self) { + /// // By now the DataStructure lives only in our thread and we are sure we don't hold + /// // any Shared or & to it ourselves, but it may be null, so we have to be careful. + /// let old = mem::replace(&mut self.ptr, Atomic::null()); + /// unsafe { + /// if let Some(x) = old.try_into_owned() { + /// drop(x) + /// } + /// } + /// } + /// } + /// ``` + pub unsafe fn try_into_owned(self) -> Option> { + // FIXME: See self.into_owned() + #[cfg(crossbeam_loom)] + let data = self.data.unsync_load(); + #[cfg(not(crossbeam_loom))] + let data = self.data.into_inner(); + if decompose_tag::(data).0 == 0 { + None + } else { + Some(Owned::from_usize(data)) + } + } } impl fmt::Debug for Atomic { @@ -925,6 +985,7 @@ impl From> for Atomic { /// use crossbeam_epoch::{Atomic, Owned}; /// /// let a = Atomic::::from(Owned::new(1234)); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` fn from(owned: Owned) -> Self { let data = owned.data; @@ -1108,6 +1169,7 @@ impl Owned { /// let o = Owned::new(1234); /// let guard = &epoch::pin(); /// let p = o.into_shared(guard); + /// # unsafe { drop(p.into_owned()); } // avoid leak /// ``` #[allow(clippy::needless_lifetimes)] pub fn into_shared<'g>(self, _: &'g Guard) -> Shared<'g, T> { @@ -1291,6 +1353,7 @@ impl<'g, T> Shared<'g, T> { /// let guard = &epoch::pin(); /// let p = a.load(SeqCst, guard); /// assert_eq!(p.as_raw(), raw); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn as_raw(&self) -> *const T { let (raw, _) = decompose_tag::(self.data); @@ -1329,6 +1392,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// assert!(a.load(SeqCst, guard).is_null()); /// a.store(Owned::new(1234), SeqCst); /// assert!(!a.load(SeqCst, guard).is_null()); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn is_null(&self) -> bool { let (raw, _) = decompose_tag::(self.data); @@ -1365,6 +1429,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// unsafe { /// assert_eq!(p.deref(), &1234); /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub unsafe fn deref(&self) -> &'g T { let (raw, _) = decompose_tag::(self.data); @@ -1406,6 +1471,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// unsafe { /// assert_eq!(p.deref(), &vec![1, 2, 3, 4, 5]); /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub unsafe fn deref_mut(&mut self) -> &'g mut T { let (raw, _) = decompose_tag::(self.data); @@ -1442,6 +1508,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// unsafe { /// assert_eq!(p.as_ref(), Some(&1234)); /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub unsafe fn as_ref(&self) -> Option<&'g T> { let (raw, _) = decompose_tag::(self.data); @@ -1481,6 +1548,36 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { Owned::from_usize(self.data) } + /// Takes ownership of the pointee if it is not null. + /// + /// # Safety + /// + /// This method may be called only if the pointer is valid and nobody else is holding a + /// reference to the same object, or if the pointer is null. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_epoch::{self as epoch, Atomic}; + /// use std::sync::atomic::Ordering::SeqCst; + /// + /// let a = Atomic::new(1234); + /// unsafe { + /// let guard = &epoch::unprotected(); + /// let p = a.load(SeqCst, guard); + /// if let Some(x) = p.try_into_owned() { + /// drop(x); + /// } + /// } + /// ``` + pub unsafe fn try_into_owned(self) -> Option> { + if self.is_null() { + None + } else { + Some(Owned::from_usize(self.data)) + } + } + /// Returns the tag stored within the pointer. /// /// # Examples @@ -1493,6 +1590,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// let guard = &epoch::pin(); /// let p = a.load(SeqCst, guard); /// assert_eq!(p.tag(), 2); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn tag(&self) -> usize { let (_, tag) = decompose_tag::(self.data); @@ -1516,6 +1614,7 @@ impl<'g, T: ?Sized + Pointable> Shared<'g, T> { /// assert_eq!(p1.tag(), 0); /// assert_eq!(p2.tag(), 2); /// assert_eq!(p1.as_raw(), p2.as_raw()); + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn with_tag(&self, tag: usize) -> Shared<'g, T> { unsafe { Self::from_usize(compose_tag::(self.data, tag)) } @@ -1536,6 +1635,7 @@ impl From<*const T> for Shared<'_, T> { /// /// let p = Shared::from(Box::into_raw(Box::new(1234)) as *const _); /// assert!(!p.is_null()); + /// # unsafe { drop(p.into_owned()); } // avoid leak /// ``` fn from(raw: *const T) -> Self { let raw = raw as usize; @@ -1612,7 +1712,7 @@ mod tests { #[test] fn array_init() { let owned = Owned::<[MaybeUninit]>::init(10); - let arr: &[MaybeUninit] = &*owned; + let arr: &[MaybeUninit] = &owned; assert_eq!(arr.len(), 10); } } diff --git a/vendor/crossbeam-epoch/src/collector.rs b/vendor/crossbeam-epoch/src/collector.rs index 099a2ffc6..5b0851184 100644 --- a/vendor/crossbeam-epoch/src/collector.rs +++ b/vendor/crossbeam-epoch/src/collector.rs @@ -111,7 +111,7 @@ impl fmt::Debug for LocalHandle { #[cfg(all(test, not(crossbeam_loom)))] mod tests { - use std::mem; + use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicUsize, Ordering}; use crossbeam_utils::thread; @@ -402,15 +402,13 @@ mod tests { v.push(i as i32); } - let ptr = v.as_mut_ptr() as usize; let len = v.len(); + let ptr = ManuallyDrop::new(v).as_mut_ptr() as usize; guard.defer_unchecked(move || { drop(Vec::from_raw_parts(ptr as *const i32 as *mut i32, len, len)); DESTROYS.fetch_add(len, Ordering::Relaxed); }); guard.flush(); - - mem::forget(v); } while DESTROYS.load(Ordering::Relaxed) < COUNT { diff --git a/vendor/crossbeam-epoch/src/default.rs b/vendor/crossbeam-epoch/src/default.rs index c2b4852a4..b42c1c7a7 100644 --- a/vendor/crossbeam-epoch/src/default.rs +++ b/vendor/crossbeam-epoch/src/default.rs @@ -8,22 +8,30 @@ use crate::collector::{Collector, LocalHandle}; use crate::guard::Guard; use crate::primitive::thread_local; #[cfg(not(crossbeam_loom))] -use once_cell::sync::Lazy; +use crate::sync::once_lock::OnceLock; -/// The global data for the default garbage collector. -#[cfg(not(crossbeam_loom))] -static COLLECTOR: Lazy = Lazy::new(Collector::new); -// FIXME: loom does not currently provide the equivalent of Lazy: -// https://github.com/tokio-rs/loom/issues/263 -#[cfg(crossbeam_loom)] -loom::lazy_static! { - /// The global data for the default garbage collector. - static ref COLLECTOR: Collector = Collector::new(); +fn collector() -> &'static Collector { + #[cfg(not(crossbeam_loom))] + { + /// The global data for the default garbage collector. + static COLLECTOR: OnceLock = OnceLock::new(); + COLLECTOR.get_or_init(Collector::new) + } + // FIXME: loom does not currently provide the equivalent of Lazy: + // https://github.com/tokio-rs/loom/issues/263 + #[cfg(crossbeam_loom)] + { + loom::lazy_static! { + /// The global data for the default garbage collector. + static ref COLLECTOR: Collector = Collector::new(); + } + &COLLECTOR + } } thread_local! { /// The per-thread participant for the default garbage collector. - static HANDLE: LocalHandle = COLLECTOR.register(); + static HANDLE: LocalHandle = collector().register(); } /// Pins the current thread. @@ -40,7 +48,7 @@ pub fn is_pinned() -> bool { /// Returns the default global collector. pub fn default_collector() -> &'static Collector { - &COLLECTOR + collector() } #[inline] @@ -50,7 +58,7 @@ where { HANDLE .try_with(|h| f(h)) - .unwrap_or_else(|_| f(&COLLECTOR.register())) + .unwrap_or_else(|_| f(&collector().register())) } #[cfg(all(test, not(crossbeam_loom)))] diff --git a/vendor/crossbeam-epoch/src/deferred.rs b/vendor/crossbeam-epoch/src/deferred.rs index c33d51502..2f3d79fdf 100644 --- a/vendor/crossbeam-epoch/src/deferred.rs +++ b/vendor/crossbeam-epoch/src/deferred.rs @@ -29,6 +29,15 @@ impl fmt::Debug for Deferred { } impl Deferred { + pub(crate) const NO_OP: Self = { + fn no_op_call(_raw: *mut u8) {} + Self { + call: no_op_call, + data: MaybeUninit::uninit(), + _marker: PhantomData, + } + }; + /// Constructs a new `Deferred` from a `FnOnce()`. pub(crate) fn new(f: F) -> Self { let size = mem::size_of::(); @@ -37,10 +46,10 @@ impl Deferred { unsafe { if size <= mem::size_of::() && align <= mem::align_of::() { let mut data = MaybeUninit::::uninit(); - ptr::write(data.as_mut_ptr() as *mut F, f); + ptr::write(data.as_mut_ptr().cast::(), f); unsafe fn call(raw: *mut u8) { - let f: F = ptr::read(raw as *mut F); + let f: F = ptr::read(raw.cast::()); f(); } @@ -52,12 +61,12 @@ impl Deferred { } else { let b: Box = Box::new(f); let mut data = MaybeUninit::::uninit(); - ptr::write(data.as_mut_ptr() as *mut Box, b); + ptr::write(data.as_mut_ptr().cast::>(), b); unsafe fn call(raw: *mut u8) { // It's safe to cast `raw` from `*mut u8` to `*mut Box`, because `raw` is // originally derived from `*mut Box`. - let b: Box = ptr::read(raw as *mut Box); + let b: Box = ptr::read(raw.cast::>()); (*b)(); } @@ -74,7 +83,7 @@ impl Deferred { #[inline] pub(crate) fn call(mut self) { let call = self.call; - unsafe { call(self.data.as_mut_ptr() as *mut u8) }; + unsafe { call(self.data.as_mut_ptr().cast::()) }; } } diff --git a/vendor/crossbeam-epoch/src/guard.rs b/vendor/crossbeam-epoch/src/guard.rs index 6db3750b0..ba7fe1b11 100644 --- a/vendor/crossbeam-epoch/src/guard.rs +++ b/vendor/crossbeam-epoch/src/guard.rs @@ -46,6 +46,7 @@ use crate::internal::Local; /// if let Some(num) = unsafe { p.as_ref() } { /// println!("The number is {}.", num); /// } +/// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` /// /// # Multiple guards @@ -184,6 +185,7 @@ impl Guard { /// }); /// } /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub unsafe fn defer_unchecked(&self, f: F) where @@ -263,6 +265,7 @@ impl Guard { /// guard.defer_destroy(p); /// } /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub unsafe fn defer_destroy(&self, ptr: Shared<'_, T>) { self.defer_unchecked(move || ptr.into_owned()); @@ -320,6 +323,7 @@ impl Guard { /// let p = a.load(SeqCst, &guard); /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn repin(&mut self) { if let Some(local) = unsafe { self.local.as_ref() } { @@ -356,6 +360,7 @@ impl Guard { /// let p = a.load(SeqCst, &guard); /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); /// } + /// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` pub fn repin_after(&mut self, f: F) -> R where @@ -451,6 +456,7 @@ impl fmt::Debug for Guard { /// /// // Dropping `dummy` doesn't affect the current thread - it's just a noop. /// } +/// # unsafe { drop(a.into_owned()); } // avoid leak /// ``` /// /// The most common use of this function is when constructing or destructing a data structure. diff --git a/vendor/crossbeam-epoch/src/internal.rs b/vendor/crossbeam-epoch/src/internal.rs index de208b13e..00c66a40a 100644 --- a/vendor/crossbeam-epoch/src/internal.rs +++ b/vendor/crossbeam-epoch/src/internal.rs @@ -55,9 +55,10 @@ use crate::sync::list::{Entry, IsElement, IterError, List}; use crate::sync::queue::Queue; /// Maximum number of objects a bag can contain. -#[cfg(not(crossbeam_sanitize))] -const MAX_OBJECTS: usize = 62; -#[cfg(crossbeam_sanitize)] +#[cfg(not(any(crossbeam_sanitize, miri)))] +const MAX_OBJECTS: usize = 64; +// Makes it more likely to trigger any potential data races. +#[cfg(any(crossbeam_sanitize, miri))] const MAX_OBJECTS: usize = 4; /// A bag of deferred functions. @@ -106,87 +107,11 @@ impl Bag { } impl Default for Bag { - #[rustfmt::skip] fn default() -> Self { - // TODO: [no_op; MAX_OBJECTS] syntax blocked by https://github.com/rust-lang/rust/issues/49147 - #[cfg(not(crossbeam_sanitize))] - return Bag { + Bag { len: 0, - deferreds: [ - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - ], - }; - #[cfg(crossbeam_sanitize)] - return Bag { - len: 0, - deferreds: [ - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - Deferred::new(no_op_func), - ], - }; + deferreds: [Deferred::NO_OP; MAX_OBJECTS], + } } } @@ -194,7 +119,7 @@ impl Drop for Bag { fn drop(&mut self) { // Call all deferred functions. for deferred in &mut self.deferreds[..self.len] { - let no_op = Deferred::new(no_op_func); + let no_op = Deferred::NO_OP; let owned_deferred = mem::replace(deferred, no_op); owned_deferred.call(); } @@ -210,8 +135,6 @@ impl fmt::Debug for Bag { } } -fn no_op_func() {} - /// A pair of an epoch and a bag. #[derive(Default, Debug)] struct SealedBag { @@ -375,13 +298,14 @@ pub(crate) struct Local { // Make sure `Local` is less than or equal to 2048 bytes. // https://github.com/crossbeam-rs/crossbeam/issues/551 -#[cfg(not(crossbeam_sanitize))] // `crossbeam_sanitize` reduces the size of `Local` +#[cfg(not(any(crossbeam_sanitize, miri)))] // `crossbeam_sanitize` and `miri` reduce the size of `Local` #[test] fn local_size() { - assert!( - core::mem::size_of::() <= 2048, - "An allocation of `Local` should be <= 2048 bytes." - ); + // TODO: https://github.com/crossbeam-rs/crossbeam/issues/869 + // assert!( + // core::mem::size_of::() <= 2048, + // "An allocation of `Local` should be <= 2048 bytes." + // ); } impl Local { @@ -468,7 +392,10 @@ impl Local { // Now we must store `new_epoch` into `self.epoch` and execute a `SeqCst` fence. // The fence makes sure that any future loads from `Atomic`s will not happen before // this store. - if cfg!(any(target_arch = "x86", target_arch = "x86_64")) { + if cfg!(all( + any(target_arch = "x86", target_arch = "x86_64"), + not(miri) + )) { // HACK(stjepang): On x86 architectures there are two different ways of executing // a `SeqCst` fence. // diff --git a/vendor/crossbeam-epoch/src/lib.rs b/vendor/crossbeam-epoch/src/lib.rs index 4cf982b6b..b432c1f40 100644 --- a/vendor/crossbeam-epoch/src/lib.rs +++ b/vendor/crossbeam-epoch/src/lib.rs @@ -107,7 +107,7 @@ mod primitive { // https://github.com/tokio-rs/loom#handling-loom-api-differences impl UnsafeCell { #[inline] - pub(crate) fn new(data: T) -> UnsafeCell { + pub(crate) const fn new(data: T) -> UnsafeCell { UnsafeCell(::core::cell::UnsafeCell::new(data)) } diff --git a/vendor/crossbeam-epoch/src/sync/mod.rs b/vendor/crossbeam-epoch/src/sync/mod.rs index 5c06e7643..08981be25 100644 --- a/vendor/crossbeam-epoch/src/sync/mod.rs +++ b/vendor/crossbeam-epoch/src/sync/mod.rs @@ -1,4 +1,7 @@ //! Synchronization primitives. pub(crate) mod list; +#[cfg(feature = "std")] +#[cfg(not(crossbeam_loom))] +pub(crate) mod once_lock; pub(crate) mod queue; diff --git a/vendor/crossbeam-epoch/src/sync/once_lock.rs b/vendor/crossbeam-epoch/src/sync/once_lock.rs new file mode 100644 index 000000000..c1fefc96c --- /dev/null +++ b/vendor/crossbeam-epoch/src/sync/once_lock.rs @@ -0,0 +1,103 @@ +// Based on unstable std::sync::OnceLock. +// +// Source: https://github.com/rust-lang/rust/blob/8e9c93df464b7ada3fc7a1c8ccddd9dcb24ee0a0/library/std/src/sync/once_lock.rs + +use core::cell::UnsafeCell; +use core::mem::MaybeUninit; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Once; + +pub(crate) struct OnceLock { + once: Once, + // Once::is_completed requires Rust 1.43, so use this to track of whether they have been initialized. + is_initialized: AtomicBool, + value: UnsafeCell>, + // Unlike std::sync::OnceLock, we don't need PhantomData here because + // we don't use #[may_dangle]. +} + +unsafe impl Sync for OnceLock {} +unsafe impl Send for OnceLock {} + +impl OnceLock { + /// Creates a new empty cell. + #[must_use] + pub(crate) const fn new() -> Self { + Self { + once: Once::new(), + is_initialized: AtomicBool::new(false), + value: UnsafeCell::new(MaybeUninit::uninit()), + } + } + + /// Gets the contents of the cell, initializing it with `f` if the cell + /// was empty. + /// + /// Many threads may call `get_or_init` concurrently with different + /// initializing functions, but it is guaranteed that only one function + /// will be executed. + /// + /// # Panics + /// + /// If `f` panics, the panic is propagated to the caller, and the cell + /// remains uninitialized. + /// + /// It is an error to reentrantly initialize the cell from `f`. The + /// exact outcome is unspecified. Current implementation deadlocks, but + /// this may be changed to a panic in the future. + pub(crate) fn get_or_init(&self, f: F) -> &T + where + F: FnOnce() -> T, + { + // Fast path check + if self.is_initialized() { + // SAFETY: The inner value has been initialized + return unsafe { self.get_unchecked() }; + } + self.initialize(f); + + debug_assert!(self.is_initialized()); + + // SAFETY: The inner value has been initialized + unsafe { self.get_unchecked() } + } + + #[inline] + fn is_initialized(&self) -> bool { + self.is_initialized.load(Ordering::Acquire) + } + + #[cold] + fn initialize(&self, f: F) + where + F: FnOnce() -> T, + { + let slot = self.value.get().cast::(); + let is_initialized = &self.is_initialized; + + self.once.call_once(|| { + let value = f(); + unsafe { + slot.write(value); + } + is_initialized.store(true, Ordering::Release); + }); + } + + /// # Safety + /// + /// The value must be initialized + unsafe fn get_unchecked(&self) -> &T { + debug_assert!(self.is_initialized()); + &*self.value.get().cast::() + } +} + +impl Drop for OnceLock { + fn drop(&mut self) { + if self.is_initialized() { + // SAFETY: The inner value has been initialized + unsafe { self.value.get().cast::().drop_in_place() }; + } + } +} diff --git a/vendor/crossbeam-queue/.cargo-checksum.json b/vendor/crossbeam-queue/.cargo-checksum.json deleted file mode 100644 index 8dcd3f367..000000000 --- a/vendor/crossbeam-queue/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"5f8fe6dc4bfa5616834c0f60a6b0280a9dc96d282d4a14e1a77b1bd60453887f","Cargo.toml":"336728ea0b0befab0c66ff758c47ef8c1f49b4912d2f450ae8ab24611cf78790","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"2d4f1cc484ab54dfb9597bf121b3e8ef5416bb56ae52541976016a4776129447","build.rs":"ee1eaeee830c08c770bb84b40e6400af52c8db464945df0b82c8a4a4b4c681ec","no_atomic.rs":"71b5f78fd701ce604aa766dd3d825fa5bed774282aae4d6c31d7acb01b1b242f","src/array_queue.rs":"ea383caa1b70cbe09716caed20016b851118e24fa8508b2ce2498402ae5369f8","src/lib.rs":"effccc001c5168217291e435ae79f4889495cb943a6720d1e73e65b64831e4ed","src/seg_queue.rs":"be0ceb6d67a084eb511582e38c24c7d90bc89c2111778216cf05e11622d7fc4c","tests/array_queue.rs":"3ea9d2ca8c1e1f4d82f2ccd94872696baa4ffc80aca939ea2c5af737be53f817","tests/seg_queue.rs":"3b44ccad949578d2f4e5dee2687cfe6ef1fd52930ae19ed66c12bafa62cf32c2"},"package":"1f25d8400f4a7a5778f0e4e52384a48cbd9b5c495d110786187fc750075277a2"} \ No newline at end of file diff --git a/vendor/crossbeam-queue/CHANGELOG.md b/vendor/crossbeam-queue/CHANGELOG.md deleted file mode 100644 index 1d8b04ff6..000000000 --- a/vendor/crossbeam-queue/CHANGELOG.md +++ /dev/null @@ -1,54 +0,0 @@ -# Version 0.3.5 - -- Add `ArrayQueue::force_push`. (#789) - -# Version 0.3.4 - -- Implement `IntoIterator` for `ArrayQueue` and `SegQueue`. (#772) - -# Version 0.3.3 - -- Fix stacked borrows violation in `ArrayQueue` when `-Zmiri-tag-raw-pointers` is enabled. (#763) - -# Version 0.3.2 - -- Support targets that do not have atomic CAS on stable Rust. (#698) - -# Version 0.3.1 - -- Make `SegQueue::new` const fn. (#584) -- Change license to "MIT OR Apache-2.0". - -# Version 0.3.0 - -- Bump the minimum supported Rust version to 1.36. -- Remove `PushError` and `PopError`. - -# Version 0.2.3 - -- Fix bug in release (yanking 0.2.2) - -# Version 0.2.2 - -- Fix unsoundness issues by adopting `MaybeUninit`. (#458) - -# Version 0.2.1 - -- Add `no_std` support. - -# Version 0.2.0 - -- Bump the minimum required version to 1.28. -- Bump `crossbeam-utils` to `0.7`. - -# Version 0.1.2 - -- Update `crossbeam-utils` to `0.6.5`. - -# Version 0.1.1 - -- Update `crossbeam-utils` to `0.6.4`. - -# Version 0.1.0 - -- Initial version with `ArrayQueue` and `SegQueue`. diff --git a/vendor/crossbeam-queue/Cargo.toml b/vendor/crossbeam-queue/Cargo.toml deleted file mode 100644 index c8093dc19..000000000 --- a/vendor/crossbeam-queue/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2018" -rust-version = "1.36" -name = "crossbeam-queue" -version = "0.3.5" -description = "Concurrent queues" -homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-queue" -keywords = [ - "queue", - "mpmc", - "lock-free", - "producer", - "consumer", -] -categories = [ - "concurrency", - "data-structures", - "no-std", -] -license = "MIT OR Apache-2.0" -repository = "https://github.com/crossbeam-rs/crossbeam" - -[dependencies.cfg-if] -version = "1" - -[dependencies.crossbeam-utils] -version = "0.8.5" -default-features = false - -[dev-dependencies.rand] -version = "0.8" - -[features] -alloc = [] -default = ["std"] -nightly = ["crossbeam-utils/nightly"] -std = [ - "alloc", - "crossbeam-utils/std", -] diff --git a/vendor/crossbeam-queue/LICENSE-APACHE b/vendor/crossbeam-queue/LICENSE-APACHE deleted file mode 100644 index 16fe87b06..000000000 --- a/vendor/crossbeam-queue/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/crossbeam-queue/LICENSE-MIT b/vendor/crossbeam-queue/LICENSE-MIT deleted file mode 100644 index 068d491fd..000000000 --- a/vendor/crossbeam-queue/LICENSE-MIT +++ /dev/null @@ -1,27 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2019 The Crossbeam Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/crossbeam-queue/README.md b/vendor/crossbeam-queue/README.md deleted file mode 100644 index 2f30b3937..000000000 --- a/vendor/crossbeam-queue/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# Crossbeam Queue - -[![Build Status](https://github.com/crossbeam-rs/crossbeam/workflows/CI/badge.svg)]( -https://github.com/crossbeam-rs/crossbeam/actions) -[![License](https://img.shields.io/badge/license-MIT_OR_Apache--2.0-blue.svg)]( -https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-queue#license) -[![Cargo](https://img.shields.io/crates/v/crossbeam-queue.svg)]( -https://crates.io/crates/crossbeam-queue) -[![Documentation](https://docs.rs/crossbeam-queue/badge.svg)]( -https://docs.rs/crossbeam-queue) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( -https://www.rust-lang.org) -[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) - -This crate provides concurrent queues that can be shared among threads: - -* [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. -* [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. - -Everything in this crate can be used in `no_std` environments, provided that `alloc` feature is -enabled. - -[`ArrayQueue`]: https://docs.rs/crossbeam-queue/*/crossbeam_queue/struct.ArrayQueue.html -[`SegQueue`]: https://docs.rs/crossbeam-queue/*/crossbeam_queue/struct.SegQueue.html - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -crossbeam-queue = "0.3" -``` - -## Compatibility - -Crossbeam Queue supports stable Rust releases going back at least six months, -and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. - -## License - -Licensed under either of - - * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) - -at your option. - -#### Contribution - -Unless you explicitly state otherwise, any contribution intentionally submitted -for inclusion in the work by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff --git a/vendor/crossbeam-queue/build.rs b/vendor/crossbeam-queue/build.rs deleted file mode 100644 index 587e0580b..000000000 --- a/vendor/crossbeam-queue/build.rs +++ /dev/null @@ -1,41 +0,0 @@ -// The rustc-cfg listed below are considered public API, but it is *unstable* -// and outside of the normal semver guarantees: -// -// - `crossbeam_no_atomic_cas` -// Assume the target does *not* support atomic CAS operations. -// This is usually detected automatically by the build script, but you may -// need to enable it manually when building for custom targets or using -// non-cargo build systems that don't run the build script. -// -// With the exceptions mentioned above, the rustc-cfg emitted by the build -// script are *not* public API. - -#![warn(rust_2018_idioms)] - -use std::env; - -include!("no_atomic.rs"); - -fn main() { - let target = match env::var("TARGET") { - Ok(target) => target, - Err(e) => { - println!( - "cargo:warning={}: unable to get TARGET environment variable: {}", - env!("CARGO_PKG_NAME"), - e - ); - return; - } - }; - - // Note that this is `no_*`, not `has_*`. This allows treating - // `cfg(target_has_atomic = "ptr")` as true when the build script doesn't - // run. This is needed for compatibility with non-cargo build systems that - // don't run the build script. - if NO_ATOMIC_CAS.contains(&&*target) { - println!("cargo:rustc-cfg=crossbeam_no_atomic_cas"); - } - - println!("cargo:rerun-if-changed=no_atomic.rs"); -} diff --git a/vendor/crossbeam-queue/no_atomic.rs b/vendor/crossbeam-queue/no_atomic.rs deleted file mode 100644 index 390019ebd..000000000 --- a/vendor/crossbeam-queue/no_atomic.rs +++ /dev/null @@ -1,73 +0,0 @@ -// This file is @generated by no_atomic.sh. -// It is not intended for manual editing. - -const NO_ATOMIC_CAS: &[&str] = &[ - "avr-unknown-gnu-atmega328", - "bpfeb-unknown-none", - "bpfel-unknown-none", - "msp430-none-elf", - "riscv32i-unknown-none-elf", - "riscv32im-unknown-none-elf", - "riscv32imc-unknown-none-elf", - "thumbv4t-none-eabi", - "thumbv6m-none-eabi", -]; - -#[allow(dead_code)] // Only crossbeam-utils uses this. -const NO_ATOMIC_64: &[&str] = &[ - "arm-linux-androideabi", - "armebv7r-none-eabi", - "armebv7r-none-eabihf", - "armv4t-unknown-linux-gnueabi", - "armv5te-unknown-linux-gnueabi", - "armv5te-unknown-linux-musleabi", - "armv5te-unknown-linux-uclibceabi", - "armv6k-nintendo-3ds", - "armv7r-none-eabi", - "armv7r-none-eabihf", - "avr-unknown-gnu-atmega328", - "hexagon-unknown-linux-musl", - "m68k-unknown-linux-gnu", - "mips-unknown-linux-gnu", - "mips-unknown-linux-musl", - "mips-unknown-linux-uclibc", - "mipsel-sony-psp", - "mipsel-unknown-linux-gnu", - "mipsel-unknown-linux-musl", - "mipsel-unknown-linux-uclibc", - "mipsel-unknown-none", - "mipsisa32r6-unknown-linux-gnu", - "mipsisa32r6el-unknown-linux-gnu", - "msp430-none-elf", - "powerpc-unknown-freebsd", - "powerpc-unknown-linux-gnu", - "powerpc-unknown-linux-gnuspe", - "powerpc-unknown-linux-musl", - "powerpc-unknown-netbsd", - "powerpc-unknown-openbsd", - "powerpc-wrs-vxworks", - "powerpc-wrs-vxworks-spe", - "riscv32gc-unknown-linux-gnu", - "riscv32gc-unknown-linux-musl", - "riscv32i-unknown-none-elf", - "riscv32im-unknown-none-elf", - "riscv32imac-unknown-none-elf", - "riscv32imc-unknown-none-elf", - "thumbv4t-none-eabi", - "thumbv6m-none-eabi", - "thumbv7em-none-eabi", - "thumbv7em-none-eabihf", - "thumbv7m-none-eabi", - "thumbv8m.base-none-eabi", - "thumbv8m.main-none-eabi", - "thumbv8m.main-none-eabihf", -]; - -#[allow(dead_code)] // Only crossbeam-utils uses this. -const NO_ATOMIC: &[&str] = &[ - "avr-unknown-gnu-atmega328", - "msp430-none-elf", - "riscv32i-unknown-none-elf", - "riscv32im-unknown-none-elf", - "riscv32imc-unknown-none-elf", -]; diff --git a/vendor/crossbeam-queue/src/array_queue.rs b/vendor/crossbeam-queue/src/array_queue.rs deleted file mode 100644 index c34f589e7..000000000 --- a/vendor/crossbeam-queue/src/array_queue.rs +++ /dev/null @@ -1,522 +0,0 @@ -//! The implementation is based on Dmitry Vyukov's bounded MPMC queue. -//! -//! Source: -//! - - -use alloc::boxed::Box; -use core::cell::UnsafeCell; -use core::fmt; -use core::mem::MaybeUninit; -use core::sync::atomic::{self, AtomicUsize, Ordering}; - -use crossbeam_utils::{Backoff, CachePadded}; - -/// A slot in a queue. -struct Slot { - /// The current stamp. - /// - /// If the stamp equals the tail, this node will be next written to. If it equals head + 1, - /// this node will be next read from. - stamp: AtomicUsize, - - /// The value in this slot. - value: UnsafeCell>, -} - -/// A bounded multi-producer multi-consumer queue. -/// -/// This queue allocates a fixed-capacity buffer on construction, which is used to store pushed -/// elements. The queue cannot hold more elements than the buffer allows. Attempting to push an -/// element into a full queue will fail. Alternatively, [`force_push`] makes it possible for -/// this queue to be used as a ring-buffer. Having a buffer allocated upfront makes this queue -/// a bit faster than [`SegQueue`]. -/// -/// [`force_push`]: ArrayQueue::force_push -/// [`SegQueue`]: super::SegQueue -/// -/// # Examples -/// -/// ``` -/// use crossbeam_queue::ArrayQueue; -/// -/// let q = ArrayQueue::new(2); -/// -/// assert_eq!(q.push('a'), Ok(())); -/// assert_eq!(q.push('b'), Ok(())); -/// assert_eq!(q.push('c'), Err('c')); -/// assert_eq!(q.pop(), Some('a')); -/// ``` -pub struct ArrayQueue { - /// The head of the queue. - /// - /// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a - /// single `usize`. The lower bits represent the index, while the upper bits represent the lap. - /// - /// Elements are popped from the head of the queue. - head: CachePadded, - - /// The tail of the queue. - /// - /// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a - /// single `usize`. The lower bits represent the index, while the upper bits represent the lap. - /// - /// Elements are pushed into the tail of the queue. - tail: CachePadded, - - /// The buffer holding slots. - buffer: Box<[Slot]>, - - /// The queue capacity. - cap: usize, - - /// A stamp with the value of `{ lap: 1, index: 0 }`. - one_lap: usize, -} - -unsafe impl Sync for ArrayQueue {} -unsafe impl Send for ArrayQueue {} - -impl ArrayQueue { - /// Creates a new bounded queue with the given capacity. - /// - /// # Panics - /// - /// Panics if the capacity is zero. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::::new(100); - /// ``` - pub fn new(cap: usize) -> ArrayQueue { - assert!(cap > 0, "capacity must be non-zero"); - - // Head is initialized to `{ lap: 0, index: 0 }`. - // Tail is initialized to `{ lap: 0, index: 0 }`. - let head = 0; - let tail = 0; - - // Allocate a buffer of `cap` slots initialized - // with stamps. - let buffer: Box<[Slot]> = (0..cap) - .map(|i| { - // Set the stamp to `{ lap: 0, index: i }`. - Slot { - stamp: AtomicUsize::new(i), - value: UnsafeCell::new(MaybeUninit::uninit()), - } - }) - .collect(); - - // One lap is the smallest power of two greater than `cap`. - let one_lap = (cap + 1).next_power_of_two(); - - ArrayQueue { - buffer, - cap, - one_lap, - head: CachePadded::new(AtomicUsize::new(head)), - tail: CachePadded::new(AtomicUsize::new(tail)), - } - } - - fn push_or_else(&self, mut value: T, f: F) -> Result<(), T> - where - F: Fn(T, usize, usize, &Slot) -> Result, - { - let backoff = Backoff::new(); - let mut tail = self.tail.load(Ordering::Relaxed); - - loop { - // Deconstruct the tail. - let index = tail & (self.one_lap - 1); - let lap = tail & !(self.one_lap - 1); - - let new_tail = if index + 1 < self.cap { - // Same lap, incremented index. - // Set to `{ lap: lap, index: index + 1 }`. - tail + 1 - } else { - // One lap forward, index wraps around to zero. - // Set to `{ lap: lap.wrapping_add(1), index: 0 }`. - lap.wrapping_add(self.one_lap) - }; - - // Inspect the corresponding slot. - debug_assert!(index < self.buffer.len()); - let slot = unsafe { self.buffer.get_unchecked(index) }; - let stamp = slot.stamp.load(Ordering::Acquire); - - // If the tail and the stamp match, we may attempt to push. - if tail == stamp { - // Try moving the tail. - match self.tail.compare_exchange_weak( - tail, - new_tail, - Ordering::SeqCst, - Ordering::Relaxed, - ) { - Ok(_) => { - // Write the value into the slot and update the stamp. - unsafe { - slot.value.get().write(MaybeUninit::new(value)); - } - slot.stamp.store(tail + 1, Ordering::Release); - return Ok(()); - } - Err(t) => { - tail = t; - backoff.spin(); - } - } - } else if stamp.wrapping_add(self.one_lap) == tail + 1 { - atomic::fence(Ordering::SeqCst); - value = f(value, tail, new_tail, slot)?; - backoff.spin(); - tail = self.tail.load(Ordering::Relaxed); - } else { - // Snooze because we need to wait for the stamp to get updated. - backoff.snooze(); - tail = self.tail.load(Ordering::Relaxed); - } - } - } - - /// Attempts to push an element into the queue. - /// - /// If the queue is full, the element is returned back as an error. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(1); - /// - /// assert_eq!(q.push(10), Ok(())); - /// assert_eq!(q.push(20), Err(20)); - /// ``` - pub fn push(&self, value: T) -> Result<(), T> { - self.push_or_else(value, |v, tail, _, _| { - let head = self.head.load(Ordering::Relaxed); - - // If the head lags one lap behind the tail as well... - if head.wrapping_add(self.one_lap) == tail { - // ...then the queue is full. - Err(v) - } else { - Ok(v) - } - }) - } - - /// Pushes an element into the queue, replacing the oldest element if necessary. - /// - /// If the queue is full, the oldest element is replaced and returned, - /// otherwise `None` is returned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(2); - /// - /// assert_eq!(q.force_push(10), None); - /// assert_eq!(q.force_push(20), None); - /// assert_eq!(q.force_push(30), Some(10)); - /// assert_eq!(q.pop(), Some(20)); - /// ``` - pub fn force_push(&self, value: T) -> Option { - self.push_or_else(value, |v, tail, new_tail, slot| { - let head = tail.wrapping_sub(self.one_lap); - let new_head = new_tail.wrapping_sub(self.one_lap); - - // Try moving the head. - if self - .head - .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Relaxed) - .is_ok() - { - // Move the tail. - self.tail.store(new_tail, Ordering::SeqCst); - - // Swap the previous value. - let old = unsafe { slot.value.get().replace(MaybeUninit::new(v)).assume_init() }; - - // Update the stamp. - slot.stamp.store(tail + 1, Ordering::Release); - - Err(old) - } else { - Ok(v) - } - }) - .err() - } - - /// Attempts to pop an element from the queue. - /// - /// If the queue is empty, `None` is returned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(1); - /// assert_eq!(q.push(10), Ok(())); - /// - /// assert_eq!(q.pop(), Some(10)); - /// assert!(q.pop().is_none()); - /// ``` - pub fn pop(&self) -> Option { - let backoff = Backoff::new(); - let mut head = self.head.load(Ordering::Relaxed); - - loop { - // Deconstruct the head. - let index = head & (self.one_lap - 1); - let lap = head & !(self.one_lap - 1); - - // Inspect the corresponding slot. - debug_assert!(index < self.buffer.len()); - let slot = unsafe { self.buffer.get_unchecked(index) }; - let stamp = slot.stamp.load(Ordering::Acquire); - - // If the the stamp is ahead of the head by 1, we may attempt to pop. - if head + 1 == stamp { - let new = if index + 1 < self.cap { - // Same lap, incremented index. - // Set to `{ lap: lap, index: index + 1 }`. - head + 1 - } else { - // One lap forward, index wraps around to zero. - // Set to `{ lap: lap.wrapping_add(1), index: 0 }`. - lap.wrapping_add(self.one_lap) - }; - - // Try moving the head. - match self.head.compare_exchange_weak( - head, - new, - Ordering::SeqCst, - Ordering::Relaxed, - ) { - Ok(_) => { - // Read the value from the slot and update the stamp. - let msg = unsafe { slot.value.get().read().assume_init() }; - slot.stamp - .store(head.wrapping_add(self.one_lap), Ordering::Release); - return Some(msg); - } - Err(h) => { - head = h; - backoff.spin(); - } - } - } else if stamp == head { - atomic::fence(Ordering::SeqCst); - let tail = self.tail.load(Ordering::Relaxed); - - // If the tail equals the head, that means the channel is empty. - if tail == head { - return None; - } - - backoff.spin(); - head = self.head.load(Ordering::Relaxed); - } else { - // Snooze because we need to wait for the stamp to get updated. - backoff.snooze(); - head = self.head.load(Ordering::Relaxed); - } - } - } - - /// Returns the capacity of the queue. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::::new(100); - /// - /// assert_eq!(q.capacity(), 100); - /// ``` - pub fn capacity(&self) -> usize { - self.cap - } - - /// Returns `true` if the queue is empty. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(100); - /// - /// assert!(q.is_empty()); - /// q.push(1).unwrap(); - /// assert!(!q.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { - let head = self.head.load(Ordering::SeqCst); - let tail = self.tail.load(Ordering::SeqCst); - - // Is the tail lagging one lap behind head? - // Is the tail equal to the head? - // - // Note: If the head changes just before we load the tail, that means there was a moment - // when the channel was not empty, so it is safe to just return `false`. - tail == head - } - - /// Returns `true` if the queue is full. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(1); - /// - /// assert!(!q.is_full()); - /// q.push(1).unwrap(); - /// assert!(q.is_full()); - /// ``` - pub fn is_full(&self) -> bool { - let tail = self.tail.load(Ordering::SeqCst); - let head = self.head.load(Ordering::SeqCst); - - // Is the head lagging one lap behind tail? - // - // Note: If the tail changes just before we load the head, that means there was a moment - // when the queue was not full, so it is safe to just return `false`. - head.wrapping_add(self.one_lap) == tail - } - - /// Returns the number of elements in the queue. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::ArrayQueue; - /// - /// let q = ArrayQueue::new(100); - /// assert_eq!(q.len(), 0); - /// - /// q.push(10).unwrap(); - /// assert_eq!(q.len(), 1); - /// - /// q.push(20).unwrap(); - /// assert_eq!(q.len(), 2); - /// ``` - pub fn len(&self) -> usize { - loop { - // Load the tail, then load the head. - let tail = self.tail.load(Ordering::SeqCst); - let head = self.head.load(Ordering::SeqCst); - - // If the tail didn't change, we've got consistent values to work with. - if self.tail.load(Ordering::SeqCst) == tail { - let hix = head & (self.one_lap - 1); - let tix = tail & (self.one_lap - 1); - - return if hix < tix { - tix - hix - } else if hix > tix { - self.cap - hix + tix - } else if tail == head { - 0 - } else { - self.cap - }; - } - } - } -} - -impl Drop for ArrayQueue { - fn drop(&mut self) { - // Get the index of the head. - let hix = self.head.load(Ordering::Relaxed) & (self.one_lap - 1); - - // Loop over all slots that hold a message and drop them. - for i in 0..self.len() { - // Compute the index of the next slot holding a message. - let index = if hix + i < self.cap { - hix + i - } else { - hix + i - self.cap - }; - - unsafe { - debug_assert!(index < self.buffer.len()); - let slot = self.buffer.get_unchecked_mut(index); - let value = &mut *slot.value.get(); - value.as_mut_ptr().drop_in_place(); - } - } - } -} - -impl fmt::Debug for ArrayQueue { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.pad("ArrayQueue { .. }") - } -} - -impl IntoIterator for ArrayQueue { - type Item = T; - - type IntoIter = IntoIter; - - fn into_iter(self) -> Self::IntoIter { - IntoIter { value: self } - } -} - -#[derive(Debug)] -pub struct IntoIter { - value: ArrayQueue, -} - -impl Iterator for IntoIter { - type Item = T; - - fn next(&mut self) -> Option { - let value = &mut self.value; - let head = *value.head.get_mut(); - if value.head.get_mut() != value.tail.get_mut() { - let index = head & (value.one_lap - 1); - let lap = head & !(value.one_lap - 1); - // SAFETY: We have mutable access to this, so we can read without - // worrying about concurrency. Furthermore, we know this is - // initialized because it is the value pointed at by `value.head` - // and this is a non-empty queue. - let val = unsafe { - debug_assert!(index < value.buffer.len()); - let slot = value.buffer.get_unchecked_mut(index); - slot.value.get().read().assume_init() - }; - let new = if index + 1 < value.cap { - // Same lap, incremented index. - // Set to `{ lap: lap, index: index + 1 }`. - head + 1 - } else { - // One lap forward, index wraps around to zero. - // Set to `{ lap: lap.wrapping_add(1), index: 0 }`. - lap.wrapping_add(value.one_lap) - }; - *value.head.get_mut() = new; - Option::Some(val) - } else { - Option::None - } - } -} diff --git a/vendor/crossbeam-queue/src/lib.rs b/vendor/crossbeam-queue/src/lib.rs deleted file mode 100644 index 846d7c2e1..000000000 --- a/vendor/crossbeam-queue/src/lib.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! Concurrent queues. -//! -//! This crate provides concurrent queues that can be shared among threads: -//! -//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. -//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. - -#![doc(test( - no_crate_inject, - attr( - deny(warnings, rust_2018_idioms), - allow(dead_code, unused_assignments, unused_variables) - ) -))] -#![warn( - missing_docs, - missing_debug_implementations, - rust_2018_idioms, - unreachable_pub -)] -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(not(crossbeam_no_atomic_cas))] -cfg_if::cfg_if! { - if #[cfg(feature = "alloc")] { - extern crate alloc; - - mod array_queue; - mod seg_queue; - - pub use self::array_queue::ArrayQueue; - pub use self::seg_queue::SegQueue; - } -} diff --git a/vendor/crossbeam-queue/src/seg_queue.rs b/vendor/crossbeam-queue/src/seg_queue.rs deleted file mode 100644 index 1767775d1..000000000 --- a/vendor/crossbeam-queue/src/seg_queue.rs +++ /dev/null @@ -1,545 +0,0 @@ -use alloc::boxed::Box; -use core::cell::UnsafeCell; -use core::fmt; -use core::marker::PhantomData; -use core::mem::MaybeUninit; -use core::ptr; -use core::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering}; - -use crossbeam_utils::{Backoff, CachePadded}; - -// Bits indicating the state of a slot: -// * If a value has been written into the slot, `WRITE` is set. -// * If a value has been read from the slot, `READ` is set. -// * If the block is being destroyed, `DESTROY` is set. -const WRITE: usize = 1; -const READ: usize = 2; -const DESTROY: usize = 4; - -// Each block covers one "lap" of indices. -const LAP: usize = 32; -// The maximum number of values a block can hold. -const BLOCK_CAP: usize = LAP - 1; -// How many lower bits are reserved for metadata. -const SHIFT: usize = 1; -// Indicates that the block is not the last one. -const HAS_NEXT: usize = 1; - -/// A slot in a block. -struct Slot { - /// The value. - value: UnsafeCell>, - - /// The state of the slot. - state: AtomicUsize, -} - -impl Slot { - /// Waits until a value is written into the slot. - fn wait_write(&self) { - let backoff = Backoff::new(); - while self.state.load(Ordering::Acquire) & WRITE == 0 { - backoff.snooze(); - } - } -} - -/// A block in a linked list. -/// -/// Each block in the list can hold up to `BLOCK_CAP` values. -struct Block { - /// The next block in the linked list. - next: AtomicPtr>, - - /// Slots for values. - slots: [Slot; BLOCK_CAP], -} - -impl Block { - /// Creates an empty block that starts at `start_index`. - fn new() -> Block { - // SAFETY: This is safe because: - // [1] `Block::next` (AtomicPtr) may be safely zero initialized. - // [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4]. - // [3] `Slot::value` (UnsafeCell) may be safely zero initialized because it - // holds a MaybeUninit. - // [4] `Slot::state` (AtomicUsize) may be safely zero initialized. - unsafe { MaybeUninit::zeroed().assume_init() } - } - - /// Waits until the next pointer is set. - fn wait_next(&self) -> *mut Block { - let backoff = Backoff::new(); - loop { - let next = self.next.load(Ordering::Acquire); - if !next.is_null() { - return next; - } - backoff.snooze(); - } - } - - /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block. - unsafe fn destroy(this: *mut Block, start: usize) { - // It is not necessary to set the `DESTROY` bit in the last slot because that slot has - // begun destruction of the block. - for i in start..BLOCK_CAP - 1 { - let slot = (*this).slots.get_unchecked(i); - - // Mark the `DESTROY` bit if a thread is still using the slot. - if slot.state.load(Ordering::Acquire) & READ == 0 - && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0 - { - // If a thread is still using the slot, it will continue destruction of the block. - return; - } - } - - // No thread is using the block, now it is safe to destroy it. - drop(Box::from_raw(this)); - } -} - -/// A position in a queue. -struct Position { - /// The index in the queue. - index: AtomicUsize, - - /// The block in the linked list. - block: AtomicPtr>, -} - -/// An unbounded multi-producer multi-consumer queue. -/// -/// This queue is implemented as a linked list of segments, where each segment is a small buffer -/// that can hold a handful of elements. There is no limit to how many elements can be in the queue -/// at a time. However, since segments need to be dynamically allocated as elements get pushed, -/// this queue is somewhat slower than [`ArrayQueue`]. -/// -/// [`ArrayQueue`]: super::ArrayQueue -/// -/// # Examples -/// -/// ``` -/// use crossbeam_queue::SegQueue; -/// -/// let q = SegQueue::new(); -/// -/// q.push('a'); -/// q.push('b'); -/// -/// assert_eq!(q.pop(), Some('a')); -/// assert_eq!(q.pop(), Some('b')); -/// assert!(q.pop().is_none()); -/// ``` -pub struct SegQueue { - /// The head of the queue. - head: CachePadded>, - - /// The tail of the queue. - tail: CachePadded>, - - /// Indicates that dropping a `SegQueue` may drop values of type `T`. - _marker: PhantomData, -} - -unsafe impl Send for SegQueue {} -unsafe impl Sync for SegQueue {} - -impl SegQueue { - /// Creates a new unbounded queue. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::SegQueue; - /// - /// let q = SegQueue::::new(); - /// ``` - pub const fn new() -> SegQueue { - SegQueue { - head: CachePadded::new(Position { - block: AtomicPtr::new(ptr::null_mut()), - index: AtomicUsize::new(0), - }), - tail: CachePadded::new(Position { - block: AtomicPtr::new(ptr::null_mut()), - index: AtomicUsize::new(0), - }), - _marker: PhantomData, - } - } - - /// Pushes an element into the queue. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::SegQueue; - /// - /// let q = SegQueue::new(); - /// - /// q.push(10); - /// q.push(20); - /// ``` - pub fn push(&self, value: T) { - let backoff = Backoff::new(); - let mut tail = self.tail.index.load(Ordering::Acquire); - let mut block = self.tail.block.load(Ordering::Acquire); - let mut next_block = None; - - loop { - // Calculate the offset of the index into the block. - let offset = (tail >> SHIFT) % LAP; - - // If we reached the end of the block, wait until the next one is installed. - if offset == BLOCK_CAP { - backoff.snooze(); - tail = self.tail.index.load(Ordering::Acquire); - block = self.tail.block.load(Ordering::Acquire); - continue; - } - - // If we're going to have to install the next block, allocate it in advance in order to - // make the wait for other threads as short as possible. - if offset + 1 == BLOCK_CAP && next_block.is_none() { - next_block = Some(Box::new(Block::::new())); - } - - // If this is the first push operation, we need to allocate the first block. - if block.is_null() { - let new = Box::into_raw(Box::new(Block::::new())); - - if self - .tail - .block - .compare_exchange(block, new, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - self.head.block.store(new, Ordering::Release); - block = new; - } else { - next_block = unsafe { Some(Box::from_raw(new)) }; - tail = self.tail.index.load(Ordering::Acquire); - block = self.tail.block.load(Ordering::Acquire); - continue; - } - } - - let new_tail = tail + (1 << SHIFT); - - // Try advancing the tail forward. - match self.tail.index.compare_exchange_weak( - tail, - new_tail, - Ordering::SeqCst, - Ordering::Acquire, - ) { - Ok(_) => unsafe { - // If we've reached the end of the block, install the next one. - if offset + 1 == BLOCK_CAP { - let next_block = Box::into_raw(next_block.unwrap()); - let next_index = new_tail.wrapping_add(1 << SHIFT); - - self.tail.block.store(next_block, Ordering::Release); - self.tail.index.store(next_index, Ordering::Release); - (*block).next.store(next_block, Ordering::Release); - } - - // Write the value into the slot. - let slot = (*block).slots.get_unchecked(offset); - slot.value.get().write(MaybeUninit::new(value)); - slot.state.fetch_or(WRITE, Ordering::Release); - - return; - }, - Err(t) => { - tail = t; - block = self.tail.block.load(Ordering::Acquire); - backoff.spin(); - } - } - } - } - - /// Pops an element from the queue. - /// - /// If the queue is empty, `None` is returned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::SegQueue; - /// - /// let q = SegQueue::new(); - /// - /// q.push(10); - /// assert_eq!(q.pop(), Some(10)); - /// assert!(q.pop().is_none()); - /// ``` - pub fn pop(&self) -> Option { - let backoff = Backoff::new(); - let mut head = self.head.index.load(Ordering::Acquire); - let mut block = self.head.block.load(Ordering::Acquire); - - loop { - // Calculate the offset of the index into the block. - let offset = (head >> SHIFT) % LAP; - - // If we reached the end of the block, wait until the next one is installed. - if offset == BLOCK_CAP { - backoff.snooze(); - head = self.head.index.load(Ordering::Acquire); - block = self.head.block.load(Ordering::Acquire); - continue; - } - - let mut new_head = head + (1 << SHIFT); - - if new_head & HAS_NEXT == 0 { - atomic::fence(Ordering::SeqCst); - let tail = self.tail.index.load(Ordering::Relaxed); - - // If the tail equals the head, that means the queue is empty. - if head >> SHIFT == tail >> SHIFT { - return None; - } - - // If head and tail are not in the same block, set `HAS_NEXT` in head. - if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP { - new_head |= HAS_NEXT; - } - } - - // The block can be null here only if the first push operation is in progress. In that - // case, just wait until it gets initialized. - if block.is_null() { - backoff.snooze(); - head = self.head.index.load(Ordering::Acquire); - block = self.head.block.load(Ordering::Acquire); - continue; - } - - // Try moving the head index forward. - match self.head.index.compare_exchange_weak( - head, - new_head, - Ordering::SeqCst, - Ordering::Acquire, - ) { - Ok(_) => unsafe { - // If we've reached the end of the block, move to the next one. - if offset + 1 == BLOCK_CAP { - let next = (*block).wait_next(); - let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT); - if !(*next).next.load(Ordering::Relaxed).is_null() { - next_index |= HAS_NEXT; - } - - self.head.block.store(next, Ordering::Release); - self.head.index.store(next_index, Ordering::Release); - } - - // Read the value. - let slot = (*block).slots.get_unchecked(offset); - slot.wait_write(); - let value = slot.value.get().read().assume_init(); - - // Destroy the block if we've reached the end, or if another thread wanted to - // destroy but couldn't because we were busy reading from the slot. - if offset + 1 == BLOCK_CAP { - Block::destroy(block, 0); - } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 { - Block::destroy(block, offset + 1); - } - - return Some(value); - }, - Err(h) => { - head = h; - block = self.head.block.load(Ordering::Acquire); - backoff.spin(); - } - } - } - } - - /// Returns `true` if the queue is empty. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::SegQueue; - /// - /// let q = SegQueue::new(); - /// - /// assert!(q.is_empty()); - /// q.push(1); - /// assert!(!q.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { - let head = self.head.index.load(Ordering::SeqCst); - let tail = self.tail.index.load(Ordering::SeqCst); - head >> SHIFT == tail >> SHIFT - } - - /// Returns the number of elements in the queue. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_queue::SegQueue; - /// - /// let q = SegQueue::new(); - /// assert_eq!(q.len(), 0); - /// - /// q.push(10); - /// assert_eq!(q.len(), 1); - /// - /// q.push(20); - /// assert_eq!(q.len(), 2); - /// ``` - pub fn len(&self) -> usize { - loop { - // Load the tail index, then load the head index. - let mut tail = self.tail.index.load(Ordering::SeqCst); - let mut head = self.head.index.load(Ordering::SeqCst); - - // If the tail index didn't change, we've got consistent indices to work with. - if self.tail.index.load(Ordering::SeqCst) == tail { - // Erase the lower bits. - tail &= !((1 << SHIFT) - 1); - head &= !((1 << SHIFT) - 1); - - // Fix up indices if they fall onto block ends. - if (tail >> SHIFT) & (LAP - 1) == LAP - 1 { - tail = tail.wrapping_add(1 << SHIFT); - } - if (head >> SHIFT) & (LAP - 1) == LAP - 1 { - head = head.wrapping_add(1 << SHIFT); - } - - // Rotate indices so that head falls into the first block. - let lap = (head >> SHIFT) / LAP; - tail = tail.wrapping_sub((lap * LAP) << SHIFT); - head = head.wrapping_sub((lap * LAP) << SHIFT); - - // Remove the lower bits. - tail >>= SHIFT; - head >>= SHIFT; - - // Return the difference minus the number of blocks between tail and head. - return tail - head - tail / LAP; - } - } - } -} - -impl Drop for SegQueue { - fn drop(&mut self) { - let mut head = self.head.index.load(Ordering::Relaxed); - let mut tail = self.tail.index.load(Ordering::Relaxed); - let mut block = self.head.block.load(Ordering::Relaxed); - - // Erase the lower bits. - head &= !((1 << SHIFT) - 1); - tail &= !((1 << SHIFT) - 1); - - unsafe { - // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks. - while head != tail { - let offset = (head >> SHIFT) % LAP; - - if offset < BLOCK_CAP { - // Drop the value in the slot. - let slot = (*block).slots.get_unchecked(offset); - let p = &mut *slot.value.get(); - p.as_mut_ptr().drop_in_place(); - } else { - // Deallocate the block and move to the next one. - let next = (*block).next.load(Ordering::Relaxed); - drop(Box::from_raw(block)); - block = next; - } - - head = head.wrapping_add(1 << SHIFT); - } - - // Deallocate the last remaining block. - if !block.is_null() { - drop(Box::from_raw(block)); - } - } - } -} - -impl fmt::Debug for SegQueue { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.pad("SegQueue { .. }") - } -} - -impl Default for SegQueue { - fn default() -> SegQueue { - SegQueue::new() - } -} - -impl IntoIterator for SegQueue { - type Item = T; - - type IntoIter = IntoIter; - - fn into_iter(self) -> Self::IntoIter { - IntoIter { value: self } - } -} - -#[derive(Debug)] -pub struct IntoIter { - value: SegQueue, -} - -impl Iterator for IntoIter { - type Item = T; - - fn next(&mut self) -> Option { - let value = &mut self.value; - let head = *value.head.index.get_mut(); - let tail = *value.tail.index.get_mut(); - if head >> SHIFT == tail >> SHIFT { - None - } else { - let block = *value.head.block.get_mut(); - let offset = (head >> SHIFT) % LAP; - - // SAFETY: We have mutable access to this, so we can read without - // worrying about concurrency. Furthermore, we know this is - // initialized because it is the value pointed at by `value.head` - // and this is a non-empty queue. - let item = unsafe { - let slot = (*block).slots.get_unchecked(offset); - let p = &mut *slot.value.get(); - p.as_mut_ptr().read() - }; - if offset + 1 == BLOCK_CAP { - // Deallocate the block and move to the next one. - // SAFETY: The block is initialized because we've been reading - // from it this entire time. We can drop it b/c everything has - // been read out of it, so nothing is pointing to it anymore. - unsafe { - let next = *(*block).next.get_mut(); - drop(Box::from_raw(block)); - *value.head.block.get_mut() = next; - } - // The last value in a block is empty, so skip it - *value.head.index.get_mut() = head.wrapping_add(2 << SHIFT); - // Double-check that we're pointing to the first item in a block. - debug_assert_eq!((*value.head.index.get_mut() >> SHIFT) % LAP, 0); - } else { - *value.head.index.get_mut() = head.wrapping_add(1 << SHIFT); - } - Some(item) - } - } -} diff --git a/vendor/crossbeam-queue/tests/array_queue.rs b/vendor/crossbeam-queue/tests/array_queue.rs deleted file mode 100644 index 9a64eac03..000000000 --- a/vendor/crossbeam-queue/tests/array_queue.rs +++ /dev/null @@ -1,359 +0,0 @@ -use std::sync::atomic::{AtomicUsize, Ordering}; - -use crossbeam_queue::ArrayQueue; -use crossbeam_utils::thread::scope; -use rand::{thread_rng, Rng}; - -#[test] -fn smoke() { - let q = ArrayQueue::new(1); - - q.push(7).unwrap(); - assert_eq!(q.pop(), Some(7)); - - q.push(8).unwrap(); - assert_eq!(q.pop(), Some(8)); - assert!(q.pop().is_none()); -} - -#[test] -fn capacity() { - for i in 1..10 { - let q = ArrayQueue::::new(i); - assert_eq!(q.capacity(), i); - } -} - -#[test] -#[should_panic(expected = "capacity must be non-zero")] -fn zero_capacity() { - let _ = ArrayQueue::::new(0); -} - -#[test] -fn len_empty_full() { - let q = ArrayQueue::new(2); - - assert_eq!(q.len(), 0); - assert!(q.is_empty()); - assert!(!q.is_full()); - - q.push(()).unwrap(); - - assert_eq!(q.len(), 1); - assert!(!q.is_empty()); - assert!(!q.is_full()); - - q.push(()).unwrap(); - - assert_eq!(q.len(), 2); - assert!(!q.is_empty()); - assert!(q.is_full()); - - q.pop().unwrap(); - - assert_eq!(q.len(), 1); - assert!(!q.is_empty()); - assert!(!q.is_full()); -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn len() { - const COUNT: usize = 25_000; - const CAP: usize = 1000; - - let q = ArrayQueue::new(CAP); - assert_eq!(q.len(), 0); - - for _ in 0..CAP / 10 { - for i in 0..50 { - q.push(i).unwrap(); - assert_eq!(q.len(), i + 1); - } - - for i in 0..50 { - q.pop().unwrap(); - assert_eq!(q.len(), 50 - i - 1); - } - } - assert_eq!(q.len(), 0); - - for i in 0..CAP { - q.push(i).unwrap(); - assert_eq!(q.len(), i + 1); - } - - for _ in 0..CAP { - q.pop().unwrap(); - } - assert_eq!(q.len(), 0); - - scope(|scope| { - scope.spawn(|_| { - for i in 0..COUNT { - loop { - if let Some(x) = q.pop() { - assert_eq!(x, i); - break; - } - } - let len = q.len(); - assert!(len <= CAP); - } - }); - - scope.spawn(|_| { - for i in 0..COUNT { - while q.push(i).is_err() {} - let len = q.len(); - assert!(len <= CAP); - } - }); - }) - .unwrap(); - assert_eq!(q.len(), 0); -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn spsc() { - const COUNT: usize = 100_000; - - let q = ArrayQueue::new(3); - - scope(|scope| { - scope.spawn(|_| { - for i in 0..COUNT { - loop { - if let Some(x) = q.pop() { - assert_eq!(x, i); - break; - } - } - } - assert!(q.pop().is_none()); - }); - - scope.spawn(|_| { - for i in 0..COUNT { - while q.push(i).is_err() {} - } - }); - }) - .unwrap(); -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn spsc_ring_buffer() { - const COUNT: usize = 100_000; - - let t = AtomicUsize::new(1); - let q = ArrayQueue::::new(3); - let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); - - scope(|scope| { - scope.spawn(|_| loop { - match t.load(Ordering::SeqCst) { - 0 if q.is_empty() => break, - - _ => { - while let Some(n) = q.pop() { - v[n].fetch_add(1, Ordering::SeqCst); - } - } - } - }); - - scope.spawn(|_| { - for i in 0..COUNT { - if let Some(n) = q.force_push(i) { - v[n].fetch_add(1, Ordering::SeqCst); - } - } - - t.fetch_sub(1, Ordering::SeqCst); - }); - }) - .unwrap(); - - for c in v { - assert_eq!(c.load(Ordering::SeqCst), 1); - } -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn mpmc() { - const COUNT: usize = 25_000; - const THREADS: usize = 4; - - let q = ArrayQueue::::new(3); - let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); - - scope(|scope| { - for _ in 0..THREADS { - scope.spawn(|_| { - for _ in 0..COUNT { - let n = loop { - if let Some(x) = q.pop() { - break x; - } - }; - v[n].fetch_add(1, Ordering::SeqCst); - } - }); - } - for _ in 0..THREADS { - scope.spawn(|_| { - for i in 0..COUNT { - while q.push(i).is_err() {} - } - }); - } - }) - .unwrap(); - - for c in v { - assert_eq!(c.load(Ordering::SeqCst), THREADS); - } -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn mpmc_ring_buffer() { - const COUNT: usize = 25_000; - const THREADS: usize = 4; - - let t = AtomicUsize::new(THREADS); - let q = ArrayQueue::::new(3); - let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); - - scope(|scope| { - for _ in 0..THREADS { - scope.spawn(|_| loop { - match t.load(Ordering::SeqCst) { - 0 if q.is_empty() => break, - - _ => { - while let Some(n) = q.pop() { - v[n].fetch_add(1, Ordering::SeqCst); - } - } - } - }); - } - - for _ in 0..THREADS { - scope.spawn(|_| { - for i in 0..COUNT { - if let Some(n) = q.force_push(i) { - v[n].fetch_add(1, Ordering::SeqCst); - } - } - - t.fetch_sub(1, Ordering::SeqCst); - }); - } - }) - .unwrap(); - - for c in v { - assert_eq!(c.load(Ordering::SeqCst), THREADS); - } -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn drops() { - const RUNS: usize = 100; - - static DROPS: AtomicUsize = AtomicUsize::new(0); - - #[derive(Debug, PartialEq)] - struct DropCounter; - - impl Drop for DropCounter { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::SeqCst); - } - } - - let mut rng = thread_rng(); - - for _ in 0..RUNS { - let steps = rng.gen_range(0..10_000); - let additional = rng.gen_range(0..50); - - DROPS.store(0, Ordering::SeqCst); - let q = ArrayQueue::new(50); - - scope(|scope| { - scope.spawn(|_| { - for _ in 0..steps { - while q.pop().is_none() {} - } - }); - - scope.spawn(|_| { - for _ in 0..steps { - while q.push(DropCounter).is_err() { - DROPS.fetch_sub(1, Ordering::SeqCst); - } - } - }); - }) - .unwrap(); - - for _ in 0..additional { - q.push(DropCounter).unwrap(); - } - - assert_eq!(DROPS.load(Ordering::SeqCst), steps); - drop(q); - assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional); - } -} - -#[test] -fn linearizable() { - #[cfg(miri)] - const COUNT: usize = 500; - #[cfg(not(miri))] - const COUNT: usize = 25_000; - const THREADS: usize = 4; - - let q = ArrayQueue::new(THREADS); - - scope(|scope| { - for _ in 0..THREADS / 2 { - scope.spawn(|_| { - for _ in 0..COUNT { - while q.push(0).is_err() {} - q.pop().unwrap(); - } - }); - - scope.spawn(|_| { - for _ in 0..COUNT { - if q.force_push(0).is_none() { - q.pop().unwrap(); - } - } - }); - } - }) - .unwrap(); -} - -#[test] -fn into_iter() { - let q = ArrayQueue::new(100); - for i in 0..100 { - q.push(i).unwrap(); - } - for (i, j) in q.into_iter().enumerate() { - assert_eq!(i, j); - } -} diff --git a/vendor/crossbeam-queue/tests/seg_queue.rs b/vendor/crossbeam-queue/tests/seg_queue.rs deleted file mode 100644 index f1304ed4a..000000000 --- a/vendor/crossbeam-queue/tests/seg_queue.rs +++ /dev/null @@ -1,190 +0,0 @@ -use std::sync::atomic::{AtomicUsize, Ordering}; - -use crossbeam_queue::SegQueue; -use crossbeam_utils::thread::scope; -use rand::{thread_rng, Rng}; - -#[test] -fn smoke() { - let q = SegQueue::new(); - q.push(7); - assert_eq!(q.pop(), Some(7)); - - q.push(8); - assert_eq!(q.pop(), Some(8)); - assert!(q.pop().is_none()); -} - -#[test] -fn len_empty_full() { - let q = SegQueue::new(); - - assert_eq!(q.len(), 0); - assert!(q.is_empty()); - - q.push(()); - - assert_eq!(q.len(), 1); - assert!(!q.is_empty()); - - q.pop().unwrap(); - - assert_eq!(q.len(), 0); - assert!(q.is_empty()); -} - -#[test] -fn len() { - let q = SegQueue::new(); - - assert_eq!(q.len(), 0); - - for i in 0..50 { - q.push(i); - assert_eq!(q.len(), i + 1); - } - - for i in 0..50 { - q.pop().unwrap(); - assert_eq!(q.len(), 50 - i - 1); - } - - assert_eq!(q.len(), 0); -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn spsc() { - const COUNT: usize = 100_000; - - let q = SegQueue::new(); - - scope(|scope| { - scope.spawn(|_| { - for i in 0..COUNT { - loop { - if let Some(x) = q.pop() { - assert_eq!(x, i); - break; - } - } - } - assert!(q.pop().is_none()); - }); - scope.spawn(|_| { - for i in 0..COUNT { - q.push(i); - } - }); - }) - .unwrap(); -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn mpmc() { - const COUNT: usize = 25_000; - const THREADS: usize = 4; - - let q = SegQueue::::new(); - let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); - - scope(|scope| { - for _ in 0..THREADS { - scope.spawn(|_| { - for _ in 0..COUNT { - let n = loop { - if let Some(x) = q.pop() { - break x; - } - }; - v[n].fetch_add(1, Ordering::SeqCst); - } - }); - } - for _ in 0..THREADS { - scope.spawn(|_| { - for i in 0..COUNT { - q.push(i); - } - }); - } - }) - .unwrap(); - - for c in v { - assert_eq!(c.load(Ordering::SeqCst), THREADS); - } -} - -#[cfg_attr(miri, ignore)] // Miri is too slow -#[test] -fn drops() { - const RUNS: usize = 100; - - static DROPS: AtomicUsize = AtomicUsize::new(0); - - #[derive(Debug, PartialEq)] - struct DropCounter; - - impl Drop for DropCounter { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::SeqCst); - } - } - - let mut rng = thread_rng(); - - for _ in 0..RUNS { - let steps = rng.gen_range(0..10_000); - let additional = rng.gen_range(0..1000); - - DROPS.store(0, Ordering::SeqCst); - let q = SegQueue::new(); - - scope(|scope| { - scope.spawn(|_| { - for _ in 0..steps { - while q.pop().is_none() {} - } - }); - - scope.spawn(|_| { - for _ in 0..steps { - q.push(DropCounter); - } - }); - }) - .unwrap(); - - for _ in 0..additional { - q.push(DropCounter); - } - - assert_eq!(DROPS.load(Ordering::SeqCst), steps); - drop(q); - assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional); - } -} - -#[test] -fn into_iter() { - let q = SegQueue::new(); - for i in 0..100 { - q.push(i); - } - for (i, j) in q.into_iter().enumerate() { - assert_eq!(i, j); - } -} - -#[test] -fn into_iter_drop() { - let q = SegQueue::new(); - for i in 0..100 { - q.push(i); - } - for (i, j) in q.into_iter().enumerate().take(50) { - assert_eq!(i, j); - } -} diff --git a/vendor/crossbeam-utils/.cargo-checksum.json b/vendor/crossbeam-utils/.cargo-checksum.json index f78acc358..9c73bbda3 100644 --- a/vendor/crossbeam-utils/.cargo-checksum.json +++ b/vendor/crossbeam-utils/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"c2cdac68fbf3795e9c3cb0bbeace5f87736d0745fefbd3db9c07f568dc70d1d1","Cargo.toml":"fc5b0f0f821aa944d4341dc97e7c3b4d4bf658483ba359b5bf2e53d8ad945ac9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"dfa9fbed47c344c134a63c84b7c0e4651baeac1554b7b3266d0e38643743fc33","benches/atomic_cell.rs":"c927eb3cd1e5ecc4b91adbc3bde98af15ffab4086190792ba64d5cde0e24df3d","build.rs":"7e74dc72343ff57e83d0a84a9fbdd9ff1645894165909999b4c3d2fba94bc96c","no_atomic.rs":"916ed15218bb7b75a4e0d432430e7134efd27ca43ca8a8766e0c90e89febb602","src/atomic/atomic_cell.rs":"f1b407b62b981de47968236eabb932384722c4dd7b7f08f52c59943aefd0b113","src/atomic/consume.rs":"7a7736fcd64f6473dfea7653559ffc5e1a2a234df43835f8aa8734862145ac15","src/atomic/mod.rs":"94193895fa03cece415e8d7be700b73a9a8a7015774ca821253438607f9b0736","src/atomic/seq_lock.rs":"27182e6b87a9db73c5f6831759f8625f9fcdec3c2828204c444aef04f427735a","src/atomic/seq_lock_wide.rs":"9888dd03116bb89ca36d4ab8d5a0b5032107a2983a7eb8024454263b09080088","src/backoff.rs":"7cc7754e15f69b52e92a70d4f49d1bc274693455a0933a2d7eb0605806566af3","src/cache_padded.rs":"6a512698115ad0d5a5b163dbd7a83247e1f1c146c4a30f3fc74b952e3b767b59","src/lib.rs":"6f1bcf157abe06ad8458a53e865bf8efab9fad4a9424790147cee8fefb3795d8","src/sync/mod.rs":"59986f559a8f170a4b3247ab2eea2460b09809d87c8110ed88e4e7103d3519dc","src/sync/parker.rs":"3f997f5b41fec286ccedcf3d36f801d741387badb574820b8e3456117ecd9154","src/sync/sharded_lock.rs":"78433f55ee3defeea348d65abc78e03d63d6a304e09c568b27b403e9ad205771","src/sync/wait_group.rs":"32e946a7581c55f8aa9904527b92b177c538fa0cf7cbcfa1d1f25990582cb6ea","src/thread.rs":"21cf9b3e965529e5c0a6ff8fc1ec846bfe0006c41deb238a149be8d07384e955","tests/atomic_cell.rs":"bf8bc869c922a1cbf929c3b741bae0cae98f2157f572b5a4eb2873d20a407c22","tests/cache_padded.rs":"1bfaff8354c8184e1ee1f902881ca9400b60effb273b0d3f752801a483d2b66d","tests/parker.rs":"6def4721287d9d70b1cfd63ebb34e1c83fbb3376edbad2bc8aac6ef69dd99d20","tests/sharded_lock.rs":"314adeb8a651a28935f7a49c9a261b8fa1fd82bf6a16c865a5aced6216d7e40b","tests/thread.rs":"9a7d7d3028c552fd834c68598b04a1cc252a816bc20ab62cec060d6cd09cab10","tests/wait_group.rs":"ad8f0cdfed31f9594a2e0737234d418f8b924d784a4db8d7e469deab8c95f5f8"},"package":"7d82ee10ce34d7bc12c2122495e7593a9c41347ecdd64185af4ecf72cb1a7f83"} \ No newline at end of file +{"files":{"CHANGELOG.md":"65d3e11edf9498bdbc930c8c3878b7d3a90c1a0b1698597dc4a396a547fa0948","Cargo.toml":"1e4259a5a47271e8ae040b91e17652b5a4e0e7e45c3f22de5008db276f3a50bf","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"2a19af38a52dd965c2d66bb39f90a85b430b51ee9ccb29e9e1978ee7091e5087","benches/atomic_cell.rs":"c927eb3cd1e5ecc4b91adbc3bde98af15ffab4086190792ba64d5cde0e24df3d","build.rs":"4859f9c926c230023e861bf01c4b225b460035faf8cf6240108530efedbb747f","no_atomic.rs":"f58085b9d0666ccf62e0ae17fb5dae937c0a86fcc55dc0ae04ad8659e696a49c","src/atomic/atomic_cell.rs":"0fc99463e633144c5d59d39c35b5477da1f1b90f5448cadc37454b7f4b97707e","src/atomic/consume.rs":"7a7736fcd64f6473dfea7653559ffc5e1a2a234df43835f8aa8734862145ac15","src/atomic/mod.rs":"94193895fa03cece415e8d7be700b73a9a8a7015774ca821253438607f9b0736","src/atomic/seq_lock.rs":"27182e6b87a9db73c5f6831759f8625f9fcdec3c2828204c444aef04f427735a","src/atomic/seq_lock_wide.rs":"9888dd03116bb89ca36d4ab8d5a0b5032107a2983a7eb8024454263b09080088","src/backoff.rs":"8fd5e3dcccc05860680e49c8498de8096bee9140bcfee8723d97117106a020d0","src/cache_padded.rs":"8bb8925e2df44224ffa29f31a2f9c08d88d8bd3df6c1ce47003598225055fdb5","src/lib.rs":"6f1bcf157abe06ad8458a53e865bf8efab9fad4a9424790147cee8fefb3795d8","src/sync/mod.rs":"eca73c04f821859b8434d2b93db87d160dc6a3f65498ca201cd40d732ca4c134","src/sync/once_lock.rs":"c03dc9c05a817e087dccf8b682f7307501542805533551da3c2bab442bc40743","src/sync/parker.rs":"91f3a7d4ee8d9e06b6558d180e8a0df08ff5c6cef612b4ce4790f9f75cb34f84","src/sync/sharded_lock.rs":"6391b3b99b194b8e0888446c2dec340e4fb095753bcf0c1a80bc654f9c8be0e3","src/sync/wait_group.rs":"3e339aab014f50e214fea535c841755113ea058153378ed54e50a4acb403c937","src/thread.rs":"21cf9b3e965529e5c0a6ff8fc1ec846bfe0006c41deb238a149be8d07384e955","tests/atomic_cell.rs":"bf8bc869c922a1cbf929c3b741bae0cae98f2157f572b5a4eb2873d20a407c22","tests/cache_padded.rs":"1bfaff8354c8184e1ee1f902881ca9400b60effb273b0d3f752801a483d2b66d","tests/parker.rs":"6def4721287d9d70b1cfd63ebb34e1c83fbb3376edbad2bc8aac6ef69dd99d20","tests/sharded_lock.rs":"314adeb8a651a28935f7a49c9a261b8fa1fd82bf6a16c865a5aced6216d7e40b","tests/thread.rs":"9a7d7d3028c552fd834c68598b04a1cc252a816bc20ab62cec060d6cd09cab10","tests/wait_group.rs":"02661c2a820a5abe8b0c8fe15a6650aead707b57cdda0610d1b09a2680ed6969"},"package":"edbafec5fa1f196ca66527c1b12c2ec4745ca14b50f1ad8f9f6f720b55d11fac"} \ No newline at end of file diff --git a/vendor/crossbeam-utils/CHANGELOG.md b/vendor/crossbeam-utils/CHANGELOG.md index 8decb6cbd..3a93e4659 100644 --- a/vendor/crossbeam-utils/CHANGELOG.md +++ b/vendor/crossbeam-utils/CHANGELOG.md @@ -1,3 +1,12 @@ +# Version 0.8.12 + +- Removes the dependency on the `once_cell` crate to restore the MSRV. (#913) +- Work around [rust-lang#98302](https://github.com/rust-lang/rust/issues/98302), which causes compile error on windows-gnu when LTO is enabled. (#913) + +# Version 0.8.11 + +- Bump the minimum supported Rust version to 1.38. (#877) + # Version 0.8.10 - Fix unsoundness of `AtomicCell` on types containing niches. (#834) diff --git a/vendor/crossbeam-utils/Cargo.toml b/vendor/crossbeam-utils/Cargo.toml index fa958df28..5cb2b0a84 100644 --- a/vendor/crossbeam-utils/Cargo.toml +++ b/vendor/crossbeam-utils/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2018" -rust-version = "1.36" +rust-version = "1.38" name = "crossbeam-utils" -version = "0.8.10" +version = "0.8.12" description = "Utilities for concurrent programming" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils" readme = "README.md" @@ -35,10 +35,6 @@ repository = "https://github.com/crossbeam-rs/crossbeam" [dependencies.cfg-if] version = "1" -[dependencies.once_cell] -version = "1" -optional = true - [dev-dependencies.rand] version = "0.8" @@ -48,7 +44,7 @@ version = "1" [features] default = ["std"] nightly = [] -std = ["once_cell"] +std = [] [target."cfg(crossbeam_loom)".dependencies.loom] version = "0.5" diff --git a/vendor/crossbeam-utils/README.md b/vendor/crossbeam-utils/README.md index 6e9a8e49a..c06ea601a 100644 --- a/vendor/crossbeam-utils/README.md +++ b/vendor/crossbeam-utils/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils#license) https://crates.io/crates/crossbeam-utils) [![Documentation](https://docs.rs/crossbeam-utils/badge.svg)]( https://docs.rs/crossbeam-utils) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( +[![Rust 1.38+](https://img.shields.io/badge/rust-1.38+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) @@ -55,7 +55,7 @@ crossbeam-utils = "0.8" Crossbeam Utils supports stable Rust releases going back at least six months, and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. +version is released. Currently, the minimum supported Rust version is 1.38. ## License diff --git a/vendor/crossbeam-utils/build.rs b/vendor/crossbeam-utils/build.rs index a7557fd59..dd6604792 100644 --- a/vendor/crossbeam-utils/build.rs +++ b/vendor/crossbeam-utils/build.rs @@ -41,10 +41,9 @@ fn main() { } }; - // Note that this is `no_*`, not `has_*`. This allows treating - // `cfg(target_has_atomic = "ptr")` as true when the build script doesn't - // run. This is needed for compatibility with non-cargo build systems that - // don't run the build script. + // Note that this is `no_`*, not `has_*`. This allows treating as the latest + // stable rustc is used when the build script doesn't run. This is useful + // for non-cargo build systems that don't run the build script. if NO_ATOMIC_CAS.contains(&&*target) { println!("cargo:rustc-cfg=crossbeam_no_atomic_cas"); } diff --git a/vendor/crossbeam-utils/no_atomic.rs b/vendor/crossbeam-utils/no_atomic.rs index f740aaee1..675d9a27e 100644 --- a/vendor/crossbeam-utils/no_atomic.rs +++ b/vendor/crossbeam-utils/no_atomic.rs @@ -2,6 +2,8 @@ // It is not intended for manual editing. const NO_ATOMIC_CAS: &[&str] = &[ + "armv4t-none-eabi", + "armv5te-none-eabi", "avr-unknown-gnu-atmega328", "bpfeb-unknown-none", "bpfel-unknown-none", @@ -10,6 +12,7 @@ const NO_ATOMIC_CAS: &[&str] = &[ "riscv32im-unknown-none-elf", "riscv32imc-unknown-none-elf", "thumbv4t-none-eabi", + "thumbv5te-none-eabi", "thumbv6m-none-eabi", ]; @@ -18,7 +21,9 @@ const NO_ATOMIC_64: &[&str] = &[ "arm-linux-androideabi", "armebv7r-none-eabi", "armebv7r-none-eabihf", + "armv4t-none-eabi", "armv4t-unknown-linux-gnueabi", + "armv5te-none-eabi", "armv5te-unknown-linux-gnueabi", "armv5te-unknown-linux-musleabi", "armv5te-unknown-linux-uclibceabi", @@ -55,6 +60,7 @@ const NO_ATOMIC_64: &[&str] = &[ "riscv32imac-unknown-xous-elf", "riscv32imc-unknown-none-elf", "thumbv4t-none-eabi", + "thumbv5te-none-eabi", "thumbv6m-none-eabi", "thumbv7em-none-eabi", "thumbv7em-none-eabihf", diff --git a/vendor/crossbeam-utils/src/atomic/atomic_cell.rs b/vendor/crossbeam-utils/src/atomic/atomic_cell.rs index 9fed45d4c..7941c5c87 100644 --- a/vendor/crossbeam-utils/src/atomic/atomic_cell.rs +++ b/vendor/crossbeam-utils/src/atomic/atomic_cell.rs @@ -180,7 +180,7 @@ impl AtomicCell { /// ``` #[inline] pub fn as_ptr(&self) -> *mut T { - self.value.get() as *mut T + self.value.get().cast::() } } @@ -902,12 +902,7 @@ fn lock(addr: usize) -> &'static SeqLock { const LEN: usize = 97; #[allow(clippy::declare_interior_mutable_const)] const L: SeqLock = SeqLock::new(); - static LOCKS: [SeqLock; LEN] = [ - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, - ]; + static LOCKS: [SeqLock; LEN] = [L; LEN]; // If the modulus is a constant number, the compiler will use crazy math to transform this into // a sequence of cheap arithmetic operations rather than using the slow modulo instruction. @@ -973,7 +968,7 @@ macro_rules! atomic { /// Returns `true` if operations on `AtomicCell` are lock-free. const fn atomic_is_lock_free() -> bool { - // HACK(taiki-e): This is equivalent to `atomic! { T, _a, true, false }`, but can be used in const fn even in Rust 1.36. + // HACK(taiki-e): This is equivalent to `atomic! { T, _a, true, false }`, but can be used in const fn even in our MSRV (Rust 1.38). let is_lock_free = can_transmute::() | can_transmute::() | can_transmute::() @@ -1009,10 +1004,11 @@ where // discard the data when a data race is detected. The proper solution would be to // do atomic reads and atomic writes, but we can't atomically read and write all // kinds of data since `AtomicU8` is not available on stable Rust yet. - let val = ptr::read_volatile(src); + // Load as `MaybeUninit` because we may load a value that is not valid as `T`. + let val = ptr::read_volatile(src.cast::>()); if lock.validate_read(stamp) { - return val; + return val.assume_init(); } } @@ -1072,6 +1068,7 @@ unsafe fn atomic_swap(dst: *mut T, val: T) -> T { /// /// This operation uses the `AcqRel` ordering. If possible, an atomic instructions is used, and a /// global lock otherwise. +#[allow(clippy::let_unit_value)] unsafe fn atomic_compare_exchange_weak(dst: *mut T, mut current: T, new: T) -> Result where T: Copy + Eq, diff --git a/vendor/crossbeam-utils/src/backoff.rs b/vendor/crossbeam-utils/src/backoff.rs index 1012f06b2..9e256aaf2 100644 --- a/vendor/crossbeam-utils/src/backoff.rs +++ b/vendor/crossbeam-utils/src/backoff.rs @@ -201,6 +201,7 @@ impl Backoff { /// assert_eq!(ready.load(SeqCst), false); /// spin_wait(&ready); /// assert_eq!(ready.load(SeqCst), true); + /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` /// /// [`AtomicBool`]: std::sync::atomic::AtomicBool @@ -269,6 +270,7 @@ impl Backoff { /// assert_eq!(ready.load(SeqCst), false); /// blocking_wait(&ready); /// assert_eq!(ready.load(SeqCst), true); + /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` /// /// [`AtomicBool`]: std::sync::atomic::AtomicBool diff --git a/vendor/crossbeam-utils/src/cache_padded.rs b/vendor/crossbeam-utils/src/cache_padded.rs index 822e831d1..b5d5d33c9 100644 --- a/vendor/crossbeam-utils/src/cache_padded.rs +++ b/vendor/crossbeam-utils/src/cache_padded.rs @@ -39,9 +39,9 @@ use core::ops::{Deref, DerefMut}; /// let addr1 = &*array[0] as *const i8 as usize; /// let addr2 = &*array[1] as *const i8 as usize; /// -/// assert!(addr2 - addr1 >= 64); -/// assert_eq!(addr1 % 64, 0); -/// assert_eq!(addr2 % 64, 0); +/// assert!(addr2 - addr1 >= 32); +/// assert_eq!(addr1 % 32, 0); +/// assert_eq!(addr2 % 32, 0); /// ``` /// /// When building a concurrent queue with a head and a tail index, it is wise to place them in diff --git a/vendor/crossbeam-utils/src/sync/mod.rs b/vendor/crossbeam-utils/src/sync/mod.rs index eeb740c2c..f9eec71fb 100644 --- a/vendor/crossbeam-utils/src/sync/mod.rs +++ b/vendor/crossbeam-utils/src/sync/mod.rs @@ -4,6 +4,8 @@ //! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads. //! * [`WaitGroup`], for synchronizing the beginning or end of some computation. +#[cfg(not(crossbeam_loom))] +mod once_lock; mod parker; #[cfg(not(crossbeam_loom))] mod sharded_lock; diff --git a/vendor/crossbeam-utils/src/sync/once_lock.rs b/vendor/crossbeam-utils/src/sync/once_lock.rs new file mode 100644 index 000000000..c1fefc96c --- /dev/null +++ b/vendor/crossbeam-utils/src/sync/once_lock.rs @@ -0,0 +1,103 @@ +// Based on unstable std::sync::OnceLock. +// +// Source: https://github.com/rust-lang/rust/blob/8e9c93df464b7ada3fc7a1c8ccddd9dcb24ee0a0/library/std/src/sync/once_lock.rs + +use core::cell::UnsafeCell; +use core::mem::MaybeUninit; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Once; + +pub(crate) struct OnceLock { + once: Once, + // Once::is_completed requires Rust 1.43, so use this to track of whether they have been initialized. + is_initialized: AtomicBool, + value: UnsafeCell>, + // Unlike std::sync::OnceLock, we don't need PhantomData here because + // we don't use #[may_dangle]. +} + +unsafe impl Sync for OnceLock {} +unsafe impl Send for OnceLock {} + +impl OnceLock { + /// Creates a new empty cell. + #[must_use] + pub(crate) const fn new() -> Self { + Self { + once: Once::new(), + is_initialized: AtomicBool::new(false), + value: UnsafeCell::new(MaybeUninit::uninit()), + } + } + + /// Gets the contents of the cell, initializing it with `f` if the cell + /// was empty. + /// + /// Many threads may call `get_or_init` concurrently with different + /// initializing functions, but it is guaranteed that only one function + /// will be executed. + /// + /// # Panics + /// + /// If `f` panics, the panic is propagated to the caller, and the cell + /// remains uninitialized. + /// + /// It is an error to reentrantly initialize the cell from `f`. The + /// exact outcome is unspecified. Current implementation deadlocks, but + /// this may be changed to a panic in the future. + pub(crate) fn get_or_init(&self, f: F) -> &T + where + F: FnOnce() -> T, + { + // Fast path check + if self.is_initialized() { + // SAFETY: The inner value has been initialized + return unsafe { self.get_unchecked() }; + } + self.initialize(f); + + debug_assert!(self.is_initialized()); + + // SAFETY: The inner value has been initialized + unsafe { self.get_unchecked() } + } + + #[inline] + fn is_initialized(&self) -> bool { + self.is_initialized.load(Ordering::Acquire) + } + + #[cold] + fn initialize(&self, f: F) + where + F: FnOnce() -> T, + { + let slot = self.value.get().cast::(); + let is_initialized = &self.is_initialized; + + self.once.call_once(|| { + let value = f(); + unsafe { + slot.write(value); + } + is_initialized.store(true, Ordering::Release); + }); + } + + /// # Safety + /// + /// The value must be initialized + unsafe fn get_unchecked(&self) -> &T { + debug_assert!(self.is_initialized()); + &*self.value.get().cast::() + } +} + +impl Drop for OnceLock { + fn drop(&mut self) { + if self.is_initialized() { + // SAFETY: The inner value has been initialized + unsafe { self.value.get().cast::().drop_in_place() }; + } + } +} diff --git a/vendor/crossbeam-utils/src/sync/parker.rs b/vendor/crossbeam-utils/src/sync/parker.rs index 531f5a5fc..e791c4485 100644 --- a/vendor/crossbeam-utils/src/sync/parker.rs +++ b/vendor/crossbeam-utils/src/sync/parker.rs @@ -44,6 +44,7 @@ use std::time::{Duration, Instant}; /// /// // Wakes up when `u.unpark()` provides the token. /// p.park(); +/// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` /// /// [`park`]: Parker::park @@ -241,6 +242,7 @@ impl Unparker { /// /// // Wakes up when `u.unpark()` provides the token. /// p.park(); + /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` /// /// [`park`]: Parker::park @@ -262,7 +264,7 @@ impl Unparker { /// # let _ = unsafe { Unparker::from_raw(raw) }; /// ``` pub fn into_raw(this: Unparker) -> *const () { - Arc::into_raw(this.inner) as *const () + Arc::into_raw(this.inner).cast::<()>() } /// Converts a raw pointer into an `Unparker`. @@ -284,7 +286,7 @@ impl Unparker { /// ``` pub unsafe fn from_raw(ptr: *const ()) -> Unparker { Unparker { - inner: Arc::from_raw(ptr as *const Inner), + inner: Arc::from_raw(ptr.cast::()), } } } diff --git a/vendor/crossbeam-utils/src/sync/sharded_lock.rs b/vendor/crossbeam-utils/src/sync/sharded_lock.rs index 692653447..b43c55ea4 100644 --- a/vendor/crossbeam-utils/src/sync/sharded_lock.rs +++ b/vendor/crossbeam-utils/src/sync/sharded_lock.rs @@ -9,8 +9,8 @@ use std::sync::{LockResult, PoisonError, TryLockError, TryLockResult}; use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::thread::{self, ThreadId}; +use crate::sync::once_lock::OnceLock; use crate::CachePadded; -use once_cell::sync::Lazy; /// The number of shards per sharded lock. Must be a power of two. const NUM_SHARDS: usize = 8; @@ -583,13 +583,17 @@ struct ThreadIndices { next_index: usize, } -static THREAD_INDICES: Lazy> = Lazy::new(|| { - Mutex::new(ThreadIndices { - mapping: HashMap::new(), - free_list: Vec::new(), - next_index: 0, - }) -}); +fn thread_indices() -> &'static Mutex { + static THREAD_INDICES: OnceLock> = OnceLock::new(); + fn init() -> Mutex { + Mutex::new(ThreadIndices { + mapping: HashMap::new(), + free_list: Vec::new(), + next_index: 0, + }) + } + THREAD_INDICES.get_or_init(init) +} /// A registration of a thread with an index. /// @@ -601,7 +605,7 @@ struct Registration { impl Drop for Registration { fn drop(&mut self) { - let mut indices = THREAD_INDICES.lock().unwrap(); + let mut indices = thread_indices().lock().unwrap(); indices.mapping.remove(&self.thread_id); indices.free_list.push(self.index); } @@ -610,7 +614,7 @@ impl Drop for Registration { thread_local! { static REGISTRATION: Registration = { let thread_id = thread::current().id(); - let mut indices = THREAD_INDICES.lock().unwrap(); + let mut indices = thread_indices().lock().unwrap(); let index = match indices.free_list.pop() { Some(i) => i, diff --git a/vendor/crossbeam-utils/src/sync/wait_group.rs b/vendor/crossbeam-utils/src/sync/wait_group.rs index 4206ee42b..19d607415 100644 --- a/vendor/crossbeam-utils/src/sync/wait_group.rs +++ b/vendor/crossbeam-utils/src/sync/wait_group.rs @@ -1,6 +1,3 @@ -// Necessary for using `Mutex` for conditional variables -#![allow(clippy::mutex_atomic)] - use crate::primitive::sync::{Arc, Condvar, Mutex}; use std::fmt; @@ -42,6 +39,7 @@ use std::fmt; /// /// // Block until all threads have finished their work. /// wg.wait(); +/// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` /// /// [`Barrier`]: std::sync::Barrier @@ -100,6 +98,7 @@ impl WaitGroup { /// /// // Block until both threads have reached `wait()`. /// wg.wait(); + /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371 /// ``` pub fn wait(self) { if *self.inner.count.lock().unwrap() == 1 { diff --git a/vendor/crossbeam-utils/tests/wait_group.rs b/vendor/crossbeam-utils/tests/wait_group.rs index b6c2a2437..0ec4a729c 100644 --- a/vendor/crossbeam-utils/tests/wait_group.rs +++ b/vendor/crossbeam-utils/tests/wait_group.rs @@ -36,6 +36,7 @@ fn wait() { } #[test] +#[cfg_attr(miri, ignore)] // this test makes timing assumptions, but Miri is so slow it violates them fn wait_and_drop() { let wg = WaitGroup::new(); let (tx, rx) = mpsc::channel(); @@ -51,8 +52,8 @@ fn wait_and_drop() { }); } - // At this point, all spawned threads should be sleeping, so we shouldn't get anything from the - // channel. + // At this point, all spawned threads should be in `thread::sleep`, so we shouldn't get anything + // from the channel. assert!(rx.try_recv().is_err()); wg.wait(); diff --git a/vendor/crossbeam/.cargo-checksum.json b/vendor/crossbeam/.cargo-checksum.json deleted file mode 100644 index 0bd859983..000000000 --- a/vendor/crossbeam/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"e8dcdd4c84fced11ce3e9be9246dd511e9d09b0b36497c6e569ed0427b57424a","Cargo.toml":"a1452bb8649a66814e473799942aa624243bab0e5257a5b11ce994253b41ecb4","LICENSE-APACHE":"6f712474a3e3be1386d2d0c29449850ea788da64d35cff0fc8799acf741e9ecd","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"d1d81cf88e580608f27bf4d2bb7f6f2d01c2c1f1d26be86ec1daa7aa455e9f62","no_atomic.rs":"a2621c1b029c614fb0ab8e3f5cda2e839df88d90d26133181c1b901965f7eec4","src/lib.rs":"e896ef1e4326db5202cebdd57dd606f96113d5a8700e746bfe8909978ac84a7f","tests/subcrates.rs":"69cbe766a855ad6278cc969a61ba871eba3594afb5c2d3c647dff5b794e160ab"},"package":"4ae5588f6b3c3cb05239e90bd110f257254aecd01e4635400391aeae07497845"} \ No newline at end of file diff --git a/vendor/crossbeam/CHANGELOG.md b/vendor/crossbeam/CHANGELOG.md deleted file mode 100644 index f756fbb73..000000000 --- a/vendor/crossbeam/CHANGELOG.md +++ /dev/null @@ -1,93 +0,0 @@ -# Version 0.8.1 - -- Support targets that do not have atomic CAS on stable Rust (#698) - -# Version 0.8.0 - -- Bump the minimum supported Rust version to 1.36. -- Bump `crossbeam-channel` to `0.5`. -- Bump `crossbeam-deque` to `0.8`. -- Bump `crossbeam-epoch` to `0.9`. -- Bump `crossbeam-queue` to `0.3`. -- Bump `crossbeam-utils` to `0.8`. - -# Version 0.7.3 - -- Fix breakage with nightly feature due to rust-lang/rust#65214. -- Bump `crossbeam-channel` to `0.4`. -- Bump `crossbeam-epoch` to `0.8`. -- Bump `crossbeam-queue` to `0.2`. -- Bump `crossbeam-utils` to `0.7`. - -# Version 0.7.2 - -- Bump `crossbeam-channel` to `0.3.9`. -- Bump `crossbeam-epoch` to `0.7.2`. -- Bump `crossbeam-utils` to `0.6.6`. - -# Version 0.7.1 - -- Bump `crossbeam-utils` to `0.6.5`. - -# Version 0.7.0 - -- Remove `ArcCell`, `MsQueue`, and `TreiberStack`. -- Change the interface of `ShardedLock` to match `RwLock`. -- Add `SegQueue::len()`. -- Rename `SegQueue::try_pop()` to `SegQueue::pop()`. -- Change the return type of `SegQueue::pop()` to `Result`. -- Introduce `ArrayQueue`. -- Update dependencies. - -# Version 0.6.0 - -- Update dependencies. - -# Version 0.5.0 - -- Update `crossbeam-channel` to 0.3. -- Update `crossbeam-utils` to 0.6. -- Add `AtomicCell`, `SharedLock`, and `WaitGroup`. - -# Version 0.4.1 - -- Fix a double-free bug in `MsQueue` and `SegQueue`. - -# Version 0.4 - -- Switch to the new implementation of epoch-based reclamation in - [`crossbeam-epoch`](https://github.com/crossbeam-rs/crossbeam-epoch), fixing numerous bugs in the - old implementation. Its API is changed in a backward-incompatible way. -- Switch to the new implementation of `CachePadded` and scoped thread in - [`crossbeam-utils`](https://github.com/crossbeam-rs/crossbeam-utils). The scoped thread API is - changed in a backward-incompatible way. -- Switch to the new implementation of Chase-Lev deque in - [`crossbeam-deque`](https://github.com/crossbeam-rs/crossbeam-deque). Its API is changed in a - backward-incompatible way. -- Export channel implemented in - [`crossbeam-channel`](https://github.com/crossbeam-rs/crossbeam-channel). -- Remove `AtomicOption`. -- Implement `Default` and `From` traits. - -# Version 0.3 - -- Introduced `ScopedThreadBuilder` with the ability to name threads and set stack size -- `Worker` methods in the Chase-Lev deque don't require mutable access anymore -- Fixed a bug when unblocking `pop()` in `MsQueue` -- Implemented `Drop` for `MsQueue`, `SegQueue`, and `TreiberStack` -- Implemented `Default` for `TreiberStack` -- Added `is_empty` to `SegQueue` -- Renamed `mem::epoch` to `epoch` -- Other bug fixes - -# Version 0.2 - -- Changed existing non-blocking `pop` methods to `try_pop` -- Added blocking `pop` support to Michael-Scott queue -- Added Chase-Lev work-stealing deque - -# Version 0.1 - -- Added [epoch-based memory management](http://aturon.github.io/blog/2015/08/27/epoch/) -- Added Michael-Scott queue -- Added Segmented array queue diff --git a/vendor/crossbeam/Cargo.toml b/vendor/crossbeam/Cargo.toml deleted file mode 100644 index 71710f835..000000000 --- a/vendor/crossbeam/Cargo.toml +++ /dev/null @@ -1,59 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -edition = "2018" -name = "crossbeam" -version = "0.8.1" -authors = ["The Crossbeam Project Developers"] -exclude = ["/.github", "/ci"] -description = "Tools for concurrent programming" -homepage = "https://github.com/crossbeam-rs/crossbeam" -documentation = "https://docs.rs/crossbeam" -keywords = ["atomic", "garbage", "non-blocking", "lock-free", "rcu"] -categories = ["concurrency", "memory-management", "data-structures", "no-std"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/crossbeam-rs/crossbeam" -[dependencies.cfg-if] -version = "1" - -[dependencies.crossbeam-channel] -version = "0.5" -optional = true -default-features = false - -[dependencies.crossbeam-deque] -version = "0.8" -optional = true -default-features = false - -[dependencies.crossbeam-epoch] -version = "0.9.5" -optional = true -default-features = false - -[dependencies.crossbeam-queue] -version = "0.3.2" -optional = true -default-features = false - -[dependencies.crossbeam-utils] -version = "0.8.5" -default-features = false -[dev-dependencies.rand] -version = "0.8" - -[features] -alloc = ["crossbeam-epoch/alloc", "crossbeam-queue/alloc"] -default = ["std"] -nightly = ["crossbeam-epoch/nightly", "crossbeam-utils/nightly", "crossbeam-queue/nightly"] -std = ["alloc", "crossbeam-channel/std", "crossbeam-deque/std", "crossbeam-epoch/std", "crossbeam-queue/std", "crossbeam-utils/std"] diff --git a/vendor/crossbeam/LICENSE-APACHE b/vendor/crossbeam/LICENSE-APACHE deleted file mode 100644 index bb9abdd7f..000000000 --- a/vendor/crossbeam/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2019 The Crossbeam Project Developers - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/crossbeam/LICENSE-MIT b/vendor/crossbeam/LICENSE-MIT deleted file mode 100644 index 068d491fd..000000000 --- a/vendor/crossbeam/LICENSE-MIT +++ /dev/null @@ -1,27 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2019 The Crossbeam Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/crossbeam/README.md b/vendor/crossbeam/README.md deleted file mode 100644 index 1ed435c0a..000000000 --- a/vendor/crossbeam/README.md +++ /dev/null @@ -1,158 +0,0 @@ -# Crossbeam - -[![Build Status](https://github.com/crossbeam-rs/crossbeam/workflows/CI/badge.svg)]( -https://github.com/crossbeam-rs/crossbeam/actions) -[![License](https://img.shields.io/badge/license-MIT_OR_Apache--2.0-blue.svg)]( -https://github.com/crossbeam-rs/crossbeam#license) -[![Cargo](https://img.shields.io/crates/v/crossbeam.svg)]( -https://crates.io/crates/crossbeam) -[![Documentation](https://docs.rs/crossbeam/badge.svg)]( -https://docs.rs/crossbeam) -[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)]( -https://www.rust-lang.org) -[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ) - -This crate provides a set of tools for concurrent programming: - -#### Atomics - -* [`AtomicCell`], a thread-safe mutable memory location.(no_std) -* [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.(no_std) - -#### Data structures - -* [`deque`], work-stealing deques for building task schedulers. -* [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction.(alloc) -* [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand.(alloc) - -#### Memory management - -* [`epoch`], an epoch-based garbage collector.(alloc) - -#### Thread synchronization - -* [`channel`], multi-producer multi-consumer channels for message passing. -* [`Parker`], a thread parking primitive. -* [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads. -* [`WaitGroup`], for synchronizing the beginning or end of some computation. - -#### Utilities - -* [`Backoff`], for exponential backoff in spin loops.(no_std) -* [`CachePadded`], for padding and aligning a value to the length of a cache line.(no_std) -* [`scope`], for spawning threads that borrow local variables from the stack. - -*Features marked with (no_std) can be used in `no_std` environments.*
-*Features marked with (alloc) can be used in `no_std` environments, but only if `alloc` -feature is enabled.* - -[`AtomicCell`]: https://docs.rs/crossbeam/*/crossbeam/atomic/struct.AtomicCell.html -[`AtomicConsume`]: https://docs.rs/crossbeam/*/crossbeam/atomic/trait.AtomicConsume.html -[`deque`]: https://docs.rs/crossbeam/*/crossbeam/deque/index.html -[`ArrayQueue`]: https://docs.rs/crossbeam/*/crossbeam/queue/struct.ArrayQueue.html -[`SegQueue`]: https://docs.rs/crossbeam/*/crossbeam/queue/struct.SegQueue.html -[`channel`]: https://docs.rs/crossbeam/*/crossbeam/channel/index.html -[`Parker`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.Parker.html -[`ShardedLock`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.ShardedLock.html -[`WaitGroup`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.WaitGroup.html -[`epoch`]: https://docs.rs/crossbeam/*/crossbeam/epoch/index.html -[`Backoff`]: https://docs.rs/crossbeam/*/crossbeam/utils/struct.Backoff.html -[`CachePadded`]: https://docs.rs/crossbeam/*/crossbeam/utils/struct.CachePadded.html -[`scope`]: https://docs.rs/crossbeam/*/crossbeam/fn.scope.html - -## Crates - -The main `crossbeam` crate just [re-exports](src/lib.rs) tools from -smaller subcrates: - -* [`crossbeam-channel`](crossbeam-channel) - provides multi-producer multi-consumer channels for message passing. -* [`crossbeam-deque`](crossbeam-deque) - provides work-stealing deques, which are primarily intended for building task schedulers. -* [`crossbeam-epoch`](crossbeam-epoch) - provides epoch-based garbage collection for building concurrent data structures. -* [`crossbeam-queue`](crossbeam-queue) - provides concurrent queues that can be shared among threads. -* [`crossbeam-utils`](crossbeam-utils) - provides atomics, synchronization primitives, scoped threads, and other utilities. - -There is one more experimental subcrate that is not yet included in `crossbeam`: - -* [`crossbeam-skiplist`](crossbeam-skiplist) - provides concurrent maps and sets based on lock-free skip lists. - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -crossbeam = "0.8" -``` - -## Compatibility - -Crossbeam supports stable Rust releases going back at least six months, -and every time the minimum supported Rust version is increased, a new minor -version is released. Currently, the minimum supported Rust version is 1.36. - -## Contributing - -Crossbeam welcomes contribution from everyone in the form of suggestions, bug reports, -pull requests, and feedback. 💛 - -If you need ideas for contribution, there are several ways to get started: - -* Found a bug or have a feature request? - [Submit an issue](https://github.com/crossbeam-rs/crossbeam/issues/new)! -* Issues and PRs labeled with - [feedback wanted](https://github.com/crossbeam-rs/crossbeam/issues?utf8=%E2%9C%93&q=is%3Aopen+sort%3Aupdated-desc+label%3A%22feedback+wanted%22+) - need feedback from users and contributors. -* Issues labeled with - [good first issue](https://github.com/crossbeam-rs/crossbeam/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22) - are relatively easy starter issues. - -#### RFCs - -We also have the [RFCs](https://github.com/crossbeam-rs/rfcs) repository for more -high-level discussion, which is the place where we brainstorm ideas and propose -substantial changes to Crossbeam. - -You are welcome to participate in any open -[issues](https://github.com/crossbeam-rs/rfcs/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) -or -[pull requests](https://github.com/crossbeam-rs/rfcs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc). - -#### Learning resources - -If you'd like to learn more about concurrency and non-blocking data structures, there's a -list of learning resources in our [wiki](https://github.com/crossbeam-rs/rfcs/wiki), -which includes relevant blog posts, papers, videos, and other similar projects. - -Another good place to visit is [merged RFCs](https://github.com/crossbeam-rs/rfcs/tree/master/text). -They contain elaborate descriptions and rationale for features we've introduced to -Crossbeam, but keep in mind that some of the written information is now out of date. - -#### Conduct - -The Crossbeam project adheres to the -[Rust Code of Conduct](https://github.com/rust-lang/rust/blob/master/CODE_OF_CONDUCT.md). -This describes the minimum behavior expected from all contributors. - -## License - -Licensed under either of - - * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) - -at your option. - -Some Crossbeam subcrates have additional licensing notices. -Take a look at other readme files in this repository for more information. - -#### Contribution - -Unless you explicitly state otherwise, any contribution intentionally submitted -for inclusion in the work by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff --git a/vendor/crossbeam/no_atomic.rs b/vendor/crossbeam/no_atomic.rs deleted file mode 100644 index 522b3b8ac..000000000 --- a/vendor/crossbeam/no_atomic.rs +++ /dev/null @@ -1,59 +0,0 @@ -// This file is @generated by no_atomic.sh. -// It is not intended for manual editing. - -const NO_ATOMIC_CAS: &[&str] = &[ - "avr-unknown-gnu-atmega328", - "msp430-none-elf", - "riscv32i-unknown-none-elf", - "riscv32imc-unknown-none-elf", - "thumbv4t-none-eabi", - "thumbv6m-none-eabi", -]; -#[allow(dead_code)] -const NO_ATOMIC_64: &[&str] = &[ - "arm-linux-androideabi", - "armebv7r-none-eabi", - "armebv7r-none-eabihf", - "armv4t-unknown-linux-gnueabi", - "armv5te-unknown-linux-gnueabi", - "armv5te-unknown-linux-musleabi", - "armv5te-unknown-linux-uclibceabi", - "armv7r-none-eabi", - "armv7r-none-eabihf", - "hexagon-unknown-linux-musl", - "mips-unknown-linux-gnu", - "mips-unknown-linux-musl", - "mips-unknown-linux-uclibc", - "mipsel-unknown-linux-gnu", - "mipsel-unknown-linux-musl", - "mipsel-unknown-linux-uclibc", - "mipsel-unknown-none", - "mipsisa32r6-unknown-linux-gnu", - "mipsisa32r6el-unknown-linux-gnu", - "powerpc-unknown-linux-gnu", - "powerpc-unknown-linux-gnuspe", - "powerpc-unknown-linux-musl", - "powerpc-unknown-netbsd", - "powerpc-unknown-openbsd", - "powerpc-wrs-vxworks", - "powerpc-wrs-vxworks-spe", - "riscv32gc-unknown-linux-gnu", - "riscv32gc-unknown-linux-musl", - "riscv32imac-unknown-none-elf", - "thumbv7em-none-eabi", - "thumbv7em-none-eabihf", - "thumbv7m-none-eabi", - "thumbv8m.base-none-eabi", - "thumbv8m.main-none-eabi", - "thumbv8m.main-none-eabihf", - "mipsel-sony-psp", - "thumbv4t-none-eabi", - "thumbv6m-none-eabi", -]; -#[allow(dead_code)] -const NO_ATOMIC: &[&str] = &[ - "avr-unknown-gnu-atmega328", - "msp430-none-elf", - "riscv32i-unknown-none-elf", - "riscv32imc-unknown-none-elf", -]; diff --git a/vendor/crossbeam/src/lib.rs b/vendor/crossbeam/src/lib.rs deleted file mode 100644 index 9bc3ec111..000000000 --- a/vendor/crossbeam/src/lib.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Tools for concurrent programming. -//! -//! ## Atomics -//! -//! * [`AtomicCell`], a thread-safe mutable memory location. -//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering. -//! -//! ## Data structures -//! -//! * [`deque`], work-stealing deques for building task schedulers. -//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. -//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. -//! -//! ## Memory management -//! -//! * [`epoch`], an epoch-based garbage collector. -//! -//! ## Thread synchronization -//! -//! * [`channel`], multi-producer multi-consumer channels for message passing. -//! * [`Parker`], a thread parking primitive. -//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads. -//! * [`WaitGroup`], for synchronizing the beginning or end of some computation. -//! -//! ## Utilities -//! -//! * [`Backoff`], for exponential backoff in spin loops. -//! * [`CachePadded`], for padding and aligning a value to the length of a cache line. -//! * [`scope`], for spawning threads that borrow local variables from the stack. -//! -//! [`AtomicCell`]: atomic::AtomicCell -//! [`AtomicConsume`]: atomic::AtomicConsume -//! [`ArrayQueue`]: queue::ArrayQueue -//! [`SegQueue`]: queue::SegQueue -//! [`Parker`]: sync::Parker -//! [`ShardedLock`]: sync::ShardedLock -//! [`WaitGroup`]: sync::WaitGroup -//! [`Backoff`]: utils::Backoff -//! [`CachePadded`]: utils::CachePadded - -#![doc(test( - no_crate_inject, - attr( - deny(warnings, rust_2018_idioms), - allow(dead_code, unused_assignments, unused_variables) - ) -))] -#![warn( - missing_docs, - missing_debug_implementations, - rust_2018_idioms, - unreachable_pub -)] -#![cfg_attr(not(feature = "std"), no_std)] - -pub use crossbeam_utils::atomic; - -pub mod utils { - //! Miscellaneous utilities. - //! - //! * [`Backoff`], for exponential backoff in spin loops. - //! * [`CachePadded`], for padding and aligning a value to the length of a cache line. - - pub use crossbeam_utils::Backoff; - pub use crossbeam_utils::CachePadded; -} - -use cfg_if::cfg_if; - -cfg_if! { - if #[cfg(feature = "alloc")] { - #[doc(inline)] - pub use crossbeam_epoch as epoch; - - #[doc(inline)] - pub use crossbeam_queue as queue; - } -} - -cfg_if! { - if #[cfg(feature = "std")] { - #[doc(inline)] - pub use crossbeam_deque as deque; - - #[doc(inline)] - pub use crossbeam_channel as channel; - pub use crossbeam_channel::select; - - pub use crossbeam_utils::sync; - - #[cfg(not(crossbeam_loom))] - pub use crossbeam_utils::thread; - #[cfg(not(crossbeam_loom))] - pub use crossbeam_utils::thread::scope; - } -} diff --git a/vendor/crossbeam/tests/subcrates.rs b/vendor/crossbeam/tests/subcrates.rs deleted file mode 100644 index 21b99fb0e..000000000 --- a/vendor/crossbeam/tests/subcrates.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Makes sure subcrates are properly re-exported. - -use crossbeam::select; - -#[test] -fn channel() { - let (s, r) = crossbeam::channel::bounded(1); - - select! { - send(s, 0) -> res => res.unwrap(), - recv(r) -> res => assert!(res.is_ok()), - } -} - -#[test] -fn deque() { - let w = crossbeam::deque::Worker::new_fifo(); - w.push(1); - let _ = w.pop(); -} - -#[test] -fn epoch() { - crossbeam::epoch::pin(); -} - -#[test] -fn queue() { - let a = crossbeam::queue::ArrayQueue::new(10); - let _ = a.push(1); - let _ = a.pop(); -} - -#[test] -fn utils() { - crossbeam::utils::CachePadded::new(7); - - crossbeam::scope(|scope| { - scope.spawn(|_| ()); - }) - .unwrap(); - - crossbeam::thread::scope(|scope| { - scope.spawn(|_| ()); - }) - .unwrap(); -} diff --git a/vendor/dashmap/.cargo-checksum.json b/vendor/dashmap/.cargo-checksum.json index 7d0daa971..4197ac76b 100644 --- a/vendor/dashmap/.cargo-checksum.json +++ b/vendor/dashmap/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"8f8a0060b2a6f95a4ba3f009e49a4f0a4c26ea5ba7fb02388ca5466d97c6ccfe","LICENSE":"16692e8cee4aa06e3913787497eba2d47c42002014136f5da67be6ee640e28a3","README.md":"e1114aed5dfbd2892f2d81881c46f8e17b9b4774344ad3feb55bd2c1a41384fd","rust-toolchain":"06dc4c395690e7d6ff8b92d8d265a8cf1c02cbca414e15352072e378fcb4171a","src/iter.rs":"dec9cc68374a0a176b5840e37da4e83d0493d7dca6f776dc926bf511c84e70db","src/iter_set.rs":"5327da951dc93d30b293aeb7a805666ee4b8e6364881348ab5d86b23c29a0e13","src/lib.rs":"ad0b2651810d4d286f11ce4effb800920eb4100ae6676f6141126e5488358007","src/lock.rs":"22b1013ee3cbd1598c26403552faf8e5b44fe98a8ff4c8812da15d57bdeee4b3","src/mapref/entry.rs":"ddcf788856330a4384ce987bb84ff36b494675b3b1f2460ae48376ac664491df","src/mapref/mod.rs":"15bd45cfc642a9e3e77bbfbf2d9fad9c5fac0ff6904214a3c501e262242ec8b0","src/mapref/multiple.rs":"17a87879229d78f75d71817d100aa0a210d764d6b66e4a05b17a3e092d17e306","src/mapref/one.rs":"ea46339e08c5033cf419c195e922e1ba6f606fc71c15ee31d1b3c38cfedfedcf","src/rayon/map.rs":"07315c9dd35437fd5e504a07fcbcd77f9ea19c892c32c1d60f27db5a6a26345b","src/rayon/set.rs":"21fe2ca8c58c8ff1bc753f5e2eb6131afd598211eea375f2ac7190cd0f9abcba","src/read_only.rs":"c846f8117800dbbb122bc0552021c5ac4ccfbf464bebe37f4b65e40b19baf260","src/serde.rs":"57bbf2b255de966cc9c54011429495cc5308a1f76906846b29e015f860b79559","src/set.rs":"80271aa0d8a32845afdef5a35f18e5cac6f0f5ab8d2a6b11b02cd123152c91d4","src/setref/mod.rs":"cc39e406a333dc6c04398f4b1336fb400e3a8360c387466d8a91f5d7f4ed40a7","src/setref/multiple.rs":"2270749e83f80dbb4761448f0629ecd02b0b4268f76834236d1167844e6d5e37","src/setref/one.rs":"69738583f2a160f3907e540277ccd88e0036406b3ead66b3d4015ddd938d6937","src/t.rs":"9b40ebfba22369813bf159ed60fa70e742ae72bfaec6aee91a716cba91cb8f0d","src/table.rs":"536a3b5775cbdbe436357c231e54e4e2ee4a5e1849872aa92335271b148845b4","src/try_result.rs":"81d1dd396f70b0aa2a6e1969851b706cbfdfb09c802ac9d33dcace882aa28dd1","src/util.rs":"7a8096a713cf04e60d6c9e38cd366314ed74472abab4bb8a3a9ed081a0e0301b"},"package":"3495912c9c1ccf2e18976439f4443f3fee0fd61f424ff99fde6a66b15ecb448f"} \ No newline at end of file +{"files":{"Cargo.toml":"8181631e0224f428c3c213850ce536d9d27c82b46e3eadcd0137f78470086fc2","LICENSE":"16692e8cee4aa06e3913787497eba2d47c42002014136f5da67be6ee640e28a3","README.md":"e1114aed5dfbd2892f2d81881c46f8e17b9b4774344ad3feb55bd2c1a41384fd","rust-toolchain":"06dc4c395690e7d6ff8b92d8d265a8cf1c02cbca414e15352072e378fcb4171a","src/iter.rs":"dec9cc68374a0a176b5840e37da4e83d0493d7dca6f776dc926bf511c84e70db","src/iter_set.rs":"5327da951dc93d30b293aeb7a805666ee4b8e6364881348ab5d86b23c29a0e13","src/lib.rs":"24935d49696b2d05a83287c6a5f08d59bc206a535bfa0f8893bfeff3cfd14ea8","src/lock.rs":"22b1013ee3cbd1598c26403552faf8e5b44fe98a8ff4c8812da15d57bdeee4b3","src/mapref/entry.rs":"ddcf788856330a4384ce987bb84ff36b494675b3b1f2460ae48376ac664491df","src/mapref/mod.rs":"15bd45cfc642a9e3e77bbfbf2d9fad9c5fac0ff6904214a3c501e262242ec8b0","src/mapref/multiple.rs":"17a87879229d78f75d71817d100aa0a210d764d6b66e4a05b17a3e092d17e306","src/mapref/one.rs":"ea46339e08c5033cf419c195e922e1ba6f606fc71c15ee31d1b3c38cfedfedcf","src/rayon/map.rs":"2df5ac8241d92e1811852abd65c5b3124a14d886ae4e3a8a5cbdfdb3d7dde929","src/rayon/read_only.rs":"99dc0083f6840f59b2090bc9c5f9767a44088832e63935cb8f6bc7eca8b86102","src/rayon/set.rs":"21fe2ca8c58c8ff1bc753f5e2eb6131afd598211eea375f2ac7190cd0f9abcba","src/read_only.rs":"d872ec78201ddc272aeeabdbeaccb26e069704b85aa2f6a4d56bd0c5defe7a2b","src/serde.rs":"57bbf2b255de966cc9c54011429495cc5308a1f76906846b29e015f860b79559","src/set.rs":"80271aa0d8a32845afdef5a35f18e5cac6f0f5ab8d2a6b11b02cd123152c91d4","src/setref/mod.rs":"cc39e406a333dc6c04398f4b1336fb400e3a8360c387466d8a91f5d7f4ed40a7","src/setref/multiple.rs":"2270749e83f80dbb4761448f0629ecd02b0b4268f76834236d1167844e6d5e37","src/setref/one.rs":"69738583f2a160f3907e540277ccd88e0036406b3ead66b3d4015ddd938d6937","src/t.rs":"9b40ebfba22369813bf159ed60fa70e742ae72bfaec6aee91a716cba91cb8f0d","src/try_result.rs":"81d1dd396f70b0aa2a6e1969851b706cbfdfb09c802ac9d33dcace882aa28dd1","src/util.rs":"7a8096a713cf04e60d6c9e38cd366314ed74472abab4bb8a3a9ed081a0e0301b"},"package":"907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"} \ No newline at end of file diff --git a/vendor/dashmap/Cargo.toml b/vendor/dashmap/Cargo.toml index a03feb0ce..ce76bd9a7 100644 --- a/vendor/dashmap/Cargo.toml +++ b/vendor/dashmap/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" rust-version = "1.59" name = "dashmap" -version = "5.3.4" +version = "5.4.0" authors = ["Acrimon "] description = "Blazing fast concurrent HashMap for Rust." homepage = "https://github.com/xacrimon/dashmap" @@ -29,21 +29,24 @@ features = ["rayon", "raw-api", "serde"] version = "1.0.0" [dependencies.hashbrown] -version = "0.12.0" +version = "0.12.3" default-features = false [dependencies.lock_api] -version = "0.4.7" +version = "0.4.8" + +[dependencies.once_cell] +version = "1.13.1" [dependencies.parking_lot_core] version = "0.9.3" [dependencies.rayon] -version = "1.5.2" +version = "1.5.3" optional = true [dependencies.serde] -version = "1.0.136" +version = "1.0.144" features = ["derive"] optional = true diff --git a/vendor/dashmap/src/lib.rs b/vendor/dashmap/src/lib.rs index 627b51381..bf112d570 100644 --- a/vendor/dashmap/src/lib.rs +++ b/vendor/dashmap/src/lib.rs @@ -16,6 +16,7 @@ mod util; #[cfg(feature = "rayon")] pub mod rayon { pub mod map; + pub mod read_only; pub mod set; } @@ -35,6 +36,7 @@ use iter::{Iter, IterMut, OwningIter}; use mapref::entry::{Entry, OccupiedEntry, VacantEntry}; use mapref::multiple::RefMulti; use mapref::one::{Ref, RefMut}; +use once_cell::sync::OnceCell; pub use read_only::ReadOnlyView; pub use set::DashSet; use std::collections::hash_map::RandomState; @@ -51,8 +53,19 @@ cfg_if! { pub(crate) type HashMap = hashbrown::HashMap, S>; +// Temporary reimplementation of [`std::collections::TryReserveError`] +// util [`std::collections::TryReserveError`] stabilises. +// We cannot easily create `std::collections` error type from `hashbrown` error type +// without access to `TryReserveError::kind` method. +#[non_exhaustive] +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct TryReserveError {} + fn default_shard_amount() -> usize { - (std::thread::available_parallelism().map_or(1, usize::from) * 4).next_power_of_two() + static DEFAULT_SHARD_AMOUNT: OnceCell = OnceCell::new(); + *DEFAULT_SHARD_AMOUNT.get_or_init(|| { + (std::thread::available_parallelism().map_or(1, usize::from) * 4).next_power_of_two() + }) } fn ncb(shard_amount: usize) -> usize { @@ -65,7 +78,7 @@ fn ncb(shard_amount: usize) -> usize { /// with some slight changes to handle concurrency. /// /// DashMap tries to be very simple to use and to be a direct replacement for `RwLock>`. -/// To accomplish these all methods take `&self` instead modifying methods taking `&mut self`. +/// To accomplish this, all methods take `&self` instead of modifying methods taking `&mut self`. /// This allows you to put a DashMap in an `Arc` and share it between threads while being able to modify it. /// /// Documentation mentioning locking behaviour acts in the reference frame of the calling thread. @@ -216,7 +229,7 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap { /// Creates a new DashMap with a specified hasher and shard amount /// - /// shard_amount should greater than 0 and be a power of two. + /// shard_amount should be greater than 0 and a power of two. /// If a shard_amount which is not a power of two is provided, the function will panic. /// /// # Examples @@ -797,6 +810,24 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap { pub fn try_entry(&'a self, key: K) -> Option> { self._try_entry(key) } + + /// Advanced entry API that tries to mimic `std::collections::HashMap::try_reserve`. + /// Tries to reserve capacity for at least `shard * additional` + /// and may reserve more space to avoid frequent reallocations. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error is returned. + // TODO: return std::collections::TryReserveError once std::collections::TryReserveErrorKind stabilises. + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + for shard in self.shards.iter() { + shard + .write() + .try_reserve(additional) + .map_err(|_| TryReserveError {})?; + } + Ok(()) + } } impl<'a, K: 'a + Eq + Hash, V: 'a, S: 'a + BuildHasher + Clone> Map<'a, K, V, S> @@ -1367,4 +1398,26 @@ mod tests { assert!(result2.is_locked()); } } + + #[test] + fn test_try_reserve() { + let mut map: DashMap = DashMap::new(); + // DashMap is empty and doesn't allocate memory + assert_eq!(map.capacity(), 0); + + map.try_reserve(10).unwrap(); + + // And now map can hold at least 10 elements + assert!(map.capacity() >= 10); + } + + #[test] + fn test_try_reserve_errors() { + let mut map: DashMap = DashMap::new(); + + match map.try_reserve(usize::MAX) { + Err(_) => {} + _ => panic!("should have raised CapacityOverflow error"), + } + } } diff --git a/vendor/dashmap/src/rayon/map.rs b/vendor/dashmap/src/rayon/map.rs index c0947cf6b..4fc0c43aa 100644 --- a/vendor/dashmap/src/rayon/map.rs +++ b/vendor/dashmap/src/rayon/map.rs @@ -80,7 +80,7 @@ where } pub struct OwningIter { - shards: Box<[RwLock>]>, + pub(super) shards: Box<[RwLock>]>, } impl ParallelIterator for OwningIter @@ -125,7 +125,7 @@ where } pub struct Iter<'a, K, V, S = RandomState> { - shards: &'a [RwLock>], + pub(super) shards: &'a [RwLock>], } impl<'a, K, V, S> ParallelIterator for Iter<'a, K, V, S> diff --git a/vendor/dashmap/src/rayon/read_only.rs b/vendor/dashmap/src/rayon/read_only.rs new file mode 100644 index 000000000..a11448cee --- /dev/null +++ b/vendor/dashmap/src/rayon/read_only.rs @@ -0,0 +1,96 @@ +use crate::mapref::multiple::RefMulti; +use crate::rayon::map::Iter; +use crate::ReadOnlyView; +use core::hash::{BuildHasher, Hash}; +use rayon::iter::IntoParallelIterator; + +impl IntoParallelIterator for ReadOnlyView +where + K: Send + Eq + Hash, + V: Send, + S: Send + Clone + BuildHasher, +{ + type Iter = super::map::OwningIter; + type Item = (K, V); + + fn into_par_iter(self) -> Self::Iter { + super::map::OwningIter { + shards: self.map.shards, + } + } +} + +// This impl also enables `IntoParallelRefIterator::par_iter` +impl<'a, K, V, S> IntoParallelIterator for &'a ReadOnlyView +where + K: Send + Sync + Eq + Hash, + V: Send + Sync, + S: Send + Sync + Clone + BuildHasher, +{ + type Iter = Iter<'a, K, V, S>; + type Item = RefMulti<'a, K, V, S>; + + fn into_par_iter(self) -> Self::Iter { + Iter { + shards: &self.map.shards, + } + } +} + +#[cfg(test)] +mod tests { + use crate::DashMap; + use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; + + fn construct_sample_map() -> DashMap { + let map = DashMap::new(); + + map.insert(1, "one".to_string()); + + map.insert(10, "ten".to_string()); + + map.insert(27, "twenty seven".to_string()); + + map.insert(45, "forty five".to_string()); + + map + } + + #[test] + fn test_par_iter() { + let map = construct_sample_map(); + + let view = map.clone().into_read_only(); + + view.par_iter().for_each(|entry| { + let key = *entry.key(); + + assert!(view.contains_key(&key)); + + let map_entry = map.get(&key).unwrap(); + + assert_eq!(view.get(&key).unwrap(), map_entry.value()); + + let key_value: (&i32, &String) = view.get_key_value(&key).unwrap(); + + assert_eq!(key_value.0, map_entry.key()); + + assert_eq!(key_value.1, map_entry.value()); + }); + } + + #[test] + fn test_into_par_iter() { + let map = construct_sample_map(); + + let view = map.clone().into_read_only(); + + view.into_par_iter().for_each(|(key, value)| { + let map_entry = map.get(&key).unwrap(); + + assert_eq!(&key, map_entry.key()); + + assert_eq!(&value, map_entry.value()); + }); + } +} diff --git a/vendor/dashmap/src/read_only.rs b/vendor/dashmap/src/read_only.rs index c43947b2e..14582245b 100644 --- a/vendor/dashmap/src/read_only.rs +++ b/vendor/dashmap/src/read_only.rs @@ -7,7 +7,7 @@ use std::collections::hash_map::RandomState; /// A read-only view into a `DashMap`. Allows to obtain raw references to the stored values. pub struct ReadOnlyView { - map: DashMap, + pub(crate) map: DashMap, } impl Clone for ReadOnlyView { diff --git a/vendor/dashmap/src/table.rs b/vendor/dashmap/src/table.rs deleted file mode 100644 index 03acd76e2..000000000 --- a/vendor/dashmap/src/table.rs +++ /dev/null @@ -1,81 +0,0 @@ -use super::u128::AtomicU128; -use std::borrow::Borrow; -use std::cell::UnsafeCell; -use std::hash::{BuildHasher, Hash, Hasher}; -use std::mem::MaybeUninit; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; - -const TOMBSTONE_BIT: u64 = 1 << 63; -const ALLOCATED_BIT: u64 = 1 << 62; -const POINTER_MASK: u64 = 0x3FFFFFFFFFFFFFFF; - -fn hash(hasher: &S, key: &K) -> u64 -where - S: BuildHasher, - K: Hash, -{ - let mut hasher = hasher.build_hasher(); - key.hash(&mut hasher); - hasher.finish() -} - -struct Slot { - data: AtomicU64, - pair: UnsafeCell>, -} - -pub struct Table { - hash: Arc, - slots: Box<[Slot]>, - mask: usize, -} - -impl Table -where - K: Eq + Hash, - S: BuildHasher, -{ - pub fn new(hasher: Arc, capacity: usize) -> Self { - debug_assert!(capacity.is_power_of_two()); - let slots = (0..capacity) - .map(|_| Slot { - data: AtomicU64::new(0), - pair: UnsafeCell::new(MaybeUninit::uninit()), - }) - .collect::>(); - - Table { - hash: hasher, - slots: slots.into_boxed_slice(), - mask: capacity - 1, - } - } - - pub fn get(&self, key: &Q) -> Option<*mut (K, V)> - where - K: Borrow, - Q: Eq + Hash, - { - let hash = hash(&*self.hash, key); - let mut idx = hash as usize & self.mask; - let mut i = 0; - - loop { - let slot = &self.slots[idx]; - let data = slot.data.load(Ordering::Relaxed); - let ptr = (data & POINTER_MASK) as *mut (K, V); - if !ptr.is_null() { - let stored = unsafe { (*ptr).0.borrow() }; - if stored == key { - return Some(ptr); - } - } else if data & TOMBSTONE_BIT != TOMBSTONE_BIT || i > self.mask { - return None; - } - - idx = (idx + 1) & self.mask; - i += 1; - } - } -} diff --git a/vendor/digest-0.8.1/.cargo-checksum.json b/vendor/digest-0.8.1/.cargo-checksum.json deleted file mode 100644 index ed59510b2..000000000 --- a/vendor/digest-0.8.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"bfdc024e55a5d9f2f415045e9083abb13159e0276c3eb3dbdca290c69f8b4824","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"9e0dfd2dd4173a530e238cb6adb37aa78c34c6bc7444e0e10c1ab5d8881f63ba","src/dev.rs":"5890305be2cd3d221d1c2ce295b911cc57017dc341966ba434def4a072f8bf1c","src/digest.rs":"73f564cb8084e61baf850948443bacdea81727dfbff5abeb520c0e5bb690da7a","src/dyn_digest.rs":"abfa9a30ed2dc71ad2042501961146c87fe3cbf9254b5b203fe24920d0e246b8","src/errors.rs":"2584007e98d691160313cc27e6237db9bd886e9774137b59a1289a20054e9375","src/lib.rs":"71d838697e87561de4b6b2fda94df44639a525d4469316d4ad21f0f0075a130d"},"package":"f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5"} \ No newline at end of file diff --git a/vendor/digest-0.8.1/Cargo.toml b/vendor/digest-0.8.1/Cargo.toml deleted file mode 100644 index d36300769..000000000 --- a/vendor/digest-0.8.1/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "digest" -version = "0.8.1" -authors = ["RustCrypto Developers"] -description = "Traits for cryptographic hash functions" -documentation = "https://docs.rs/digest" -keywords = ["digest", "crypto", "hash"] -categories = ["cryptography", "no-std"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/RustCrypto/traits" -[package.metadata.docs.rs] -features = ["std"] -[dependencies.blobby] -version = "0.1" -optional = true - -[dependencies.generic-array] -version = "0.12" - -[features] -dev = ["blobby"] -std = [] -[badges.travis-ci] -repository = "RustCrypto/traits" diff --git a/vendor/digest-0.8.1/LICENSE-APACHE b/vendor/digest-0.8.1/LICENSE-APACHE deleted file mode 100644 index 78173fa2e..000000000 --- a/vendor/digest-0.8.1/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/digest-0.8.1/LICENSE-MIT b/vendor/digest-0.8.1/LICENSE-MIT deleted file mode 100644 index 8dcb85b30..000000000 --- a/vendor/digest-0.8.1/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2017 Artyom Pavlov - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/digest-0.8.1/src/dev.rs b/vendor/digest-0.8.1/src/dev.rs deleted file mode 100644 index e9950ee79..000000000 --- a/vendor/digest-0.8.1/src/dev.rs +++ /dev/null @@ -1,218 +0,0 @@ -use super::{Input, VariableOutput, ExtendableOutput, Reset, XofReader}; -use core::fmt::Debug; - -#[macro_export] -macro_rules! new_test { - ($name:ident, $test_name:expr, $hasher:ty, $test_func:ident) => { - #[test] - fn $name() { - use digest::blobby::Blob2Iterator; - let data = include_bytes!(concat!("data/", $test_name, ".blb")); - - for (i, row) in Blob2Iterator::new(data).unwrap().enumerate() { - let input = row[0]; - let output = row[1]; - if let Some(desc) = $test_func::<$hasher>(input, output) { - panic!("\n\ - Failed test №{}: {}\n\ - input:\t{:?}\n\ - output:\t{:?}\n", - i, desc, input, output, - ); - } - } - } - } -} - -// module to separate Digest from other traits -mod foo { - use super::super::Digest; - use core::fmt::Debug; - - pub fn digest_test(input: &[u8], output: &[u8]) -> Option<&'static str> - where D: Digest + Debug + Clone - { - let mut hasher = D::new(); - // Test that it works when accepting the message all at once - hasher.input(input); - let mut hasher2 = hasher.clone(); - if hasher.result().as_slice() != output { - return Some("whole message"); - } - - // Test if reset works correctly - hasher2.reset(); - hasher2.input(input); - if hasher2.result().as_slice() != output { - return Some("whole message after reset"); - } - - // Test that it works when accepting the message in pieces - let mut hasher = D::new(); - let len = input.len(); - let mut left = len; - while left > 0 { - let take = (left + 1) / 2; - hasher.input(&input[len - left..take + len - left]); - left = left - take; - } - if hasher.result().as_slice() != output { - return Some("message in pieces"); - } - - // Test processing byte-by-byte - let mut hasher = D::new(); - for chunk in input.chunks(1) { - hasher.input(chunk) - } - if hasher.result().as_slice() != output { - return Some("message byte-by-byte"); - } - None - } - - - pub fn one_million_a(expected: &[u8]) - where D: Digest + Debug + Clone - { - let mut sh = D::new(); - for _ in 0..50_000 { - sh.input(&[b'a'; 10]); - } - sh.input(&[b'a'; 500_000][..]); - let out = sh.result(); - assert_eq!(out[..], expected[..]); - } -} - -pub use self::foo::{digest_test, one_million_a}; - -pub fn xof_test(input: &[u8], output: &[u8]) - -> Option<&'static str> - where D: Input + ExtendableOutput + Default + Debug + Reset + Clone -{ - let mut hasher = D::default(); - let mut buf = [0u8; 1024]; - // Test that it works when accepting the message all at once - hasher.input(input); - - let mut hasher2 = hasher.clone(); - { - let out = &mut buf[..output.len()]; - hasher.xof_result().read(out); - - if out != output { return Some("whole message"); } - } - - // Test if hasher resets correctly - hasher2.reset(); - hasher2.input(input); - - { - let out = &mut buf[..output.len()]; - hasher2.xof_result().read(out); - - if out != output { return Some("whole message after reset"); } - } - - // Test if hasher accepts message in pieces correctly - let mut hasher = D::default(); - let len = input.len(); - let mut left = len; - while left > 0 { - let take = (left + 1) / 2; - hasher.input(&input[len - left..take + len - left]); - left = left - take; - } - - { - let out = &mut buf[..output.len()]; - hasher.xof_result().read(out); - if out != output { return Some("message in pieces"); } - } - - // Test reading from reader byte by byte - let mut hasher = D::default(); - hasher.input(input); - - let mut reader = hasher.xof_result(); - let out = &mut buf[..output.len()]; - for chunk in out.chunks_mut(1) { - reader.read(chunk); - } - - if out != output { return Some("message in pieces"); } - None -} - -pub fn variable_test(input: &[u8], output: &[u8]) - -> Option<&'static str> - where D: Input + VariableOutput + Reset + Debug + Clone -{ - let mut hasher = D::new(output.len()).unwrap(); - let mut buf = [0u8; 128]; - let buf = &mut buf[..output.len()]; - // Test that it works when accepting the message all at once - hasher.input(input); - let mut hasher2 = hasher.clone(); - hasher.variable_result(|res| buf.copy_from_slice(res)); - if buf != output { return Some("whole message"); } - - // Test if reset works correctly - hasher2.reset(); - hasher2.input(input); - hasher2.variable_result(|res| buf.copy_from_slice(res)); - if buf != output { return Some("whole message after reset"); } - - // Test that it works when accepting the message in pieces - let mut hasher = D::new(output.len()).unwrap(); - let len = input.len(); - let mut left = len; - while left > 0 { - let take = (left + 1) / 2; - hasher.input(&input[len - left..take + len - left]); - left = left - take; - } - hasher.variable_result(|res| buf.copy_from_slice(res)); - if buf != output { return Some("message in pieces"); } - - // Test processing byte-by-byte - let mut hasher = D::new(output.len()).unwrap(); - for chunk in input.chunks(1) { - hasher.input(chunk) - } - hasher.variable_result(|res| buf.copy_from_slice(res)); - if buf != output { return Some("message byte-by-byte"); } - None -} - - -#[macro_export] -macro_rules! bench { - ($name:ident, $engine:path, $bs:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut d = <$engine>::default(); - let data = [0; $bs]; - - b.iter(|| { - d.input(&data[..]); - }); - - b.bytes = $bs; - } - }; - - ($engine:path) => { - extern crate test; - - use test::Bencher; - use digest::Digest; - - bench!(bench1_10, $engine, 10); - bench!(bench2_100, $engine, 100); - bench!(bench3_1000, $engine, 1000); - bench!(bench4_10000, $engine, 10000); - } -} diff --git a/vendor/digest-0.8.1/src/digest.rs b/vendor/digest-0.8.1/src/digest.rs deleted file mode 100644 index 50128e13e..000000000 --- a/vendor/digest-0.8.1/src/digest.rs +++ /dev/null @@ -1,86 +0,0 @@ -use super::{Input, FixedOutput, Reset}; -use generic_array::{GenericArray, ArrayLength}; -use generic_array::typenum::Unsigned; - -/// The `Digest` trait specifies an interface common for digest functions. -/// -/// It's a convenience wrapper around `Input`, `FixedOutput`, `Reset`, `Clone`, -/// and `Default` traits. It also provides additional convenience methods. -pub trait Digest { - type OutputSize: ArrayLength; - /// Create new hasher instance - fn new() -> Self; - - /// Digest input data. - /// - /// This method can be called repeatedly for use with streaming messages. - fn input>(&mut self, data: B); - - /// Digest input data in a chained manner. - fn chain>(self, data: B) -> Self where Self: Sized; - - /// Retrieve result and consume hasher instance. - fn result(self) -> GenericArray; - - /// Retrieve result and reset hasher instance. - /// - /// This method sometimes can be more efficient compared to hasher - /// re-creation. - fn result_reset(&mut self) -> GenericArray; - - /// Reset hasher instance to its initial state. - fn reset(&mut self); - - /// Get output size of the hasher - fn output_size() -> usize; - - /// Convenience function to compute hash of the `data`. It will handle - /// hasher creation, data feeding and finalization. - /// - /// Example: - /// - /// ```rust,ignore - /// println!("{:x}", sha2::Sha256::digest(b"Hello world")); - /// ``` - fn digest(data: &[u8]) -> GenericArray; -} - -impl Digest for D { - type OutputSize = ::OutputSize; - - fn new() -> Self { - Self::default() - } - - fn input>(&mut self, data: B) { - Input::input(self, data); - } - - fn chain>(self, data: B) -> Self where Self: Sized { - Input::chain(self, data) - } - - fn result(self) -> GenericArray { - self.fixed_result() - } - - fn result_reset(&mut self) -> GenericArray { - let res = self.clone().fixed_result(); - self.reset(); - res - } - - fn reset(&mut self) { - ::reset(self) - } - - fn output_size() -> usize { - Self::OutputSize::to_usize() - } - - fn digest(data: &[u8]) -> GenericArray { - let mut hasher = Self::default(); - Input::input(&mut hasher, data); - hasher.fixed_result() - } -} diff --git a/vendor/digest-0.8.1/src/dyn_digest.rs b/vendor/digest-0.8.1/src/dyn_digest.rs deleted file mode 100644 index 2af43a8e3..000000000 --- a/vendor/digest-0.8.1/src/dyn_digest.rs +++ /dev/null @@ -1,63 +0,0 @@ -#![cfg(feature = "std")] -use std::boxed::Box; - -use super::{Input, FixedOutput, Reset}; -use generic_array::typenum::Unsigned; - -/// The `DynDigest` trait is a modification of `Digest` trait suitable -/// for trait objects. -pub trait DynDigest { - /// Digest input data. - /// - /// This method can be called repeatedly for use with streaming messages. - fn input(&mut self, data: &[u8]); - - /// Retrieve result and reset hasher instance - fn result_reset(&mut self) -> Box<[u8]>; - - /// Retrieve result and consume boxed hasher instance - fn result(self: Box) -> Box<[u8]>; - - /// Reset hasher instance to its initial state. - fn reset(&mut self); - - /// Get output size of the hasher - fn output_size(&self) -> usize; - - /// Clone hasher state into a boxed trait object - fn box_clone(&self) -> Box; -} - -impl DynDigest for D { - fn input(&mut self, data: &[u8]) { - Input::input(self, data); - } - - fn result_reset(&mut self) -> Box<[u8]> { - let res = self.clone().fixed_result().to_vec().into_boxed_slice(); - Reset::reset(self); - res - } - - fn result(self: Box) -> Box<[u8]> { - self.fixed_result().to_vec().into_boxed_slice() - } - - fn reset(&mut self) { - Reset::reset(self); - } - - fn output_size(&self) -> usize { - ::OutputSize::to_usize() - } - - fn box_clone(&self) -> Box { - Box::new(self.clone()) - } -} - -impl Clone for Box { - fn clone(&self) -> Self { - self.box_clone() - } -} diff --git a/vendor/digest-0.8.1/src/errors.rs b/vendor/digest-0.8.1/src/errors.rs deleted file mode 100644 index aa026a21a..000000000 --- a/vendor/digest-0.8.1/src/errors.rs +++ /dev/null @@ -1,20 +0,0 @@ -use core::fmt; -#[cfg(feature = "std")] -use std::error; - -/// The error type for variable hasher initialization -#[derive(Clone, Copy, Debug, Default)] -pub struct InvalidOutputSize; - -impl fmt::Display for InvalidOutputSize { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("invalid output size") - } -} - -#[cfg(feature = "std")] -impl error::Error for InvalidOutputSize { - fn description(&self) -> &str { - "invalid output size" - } -} diff --git a/vendor/digest-0.8.1/src/lib.rs b/vendor/digest-0.8.1/src/lib.rs deleted file mode 100644 index f03c50107..000000000 --- a/vendor/digest-0.8.1/src/lib.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! This crate provides traits which describe functionality of cryptographic hash -//! functions. -//! -//! Traits in this repository can be separated into two levels: -//! - Low level traits: `Input`, `BlockInput`, `Reset`, `FixedOutput`, -//! `VariableOutput`, `ExtendableOutput`. These traits atomically describe -//! available functionality of hash function implementations. -//! - Convenience trait: `Digest`, `DynDigest`. They are wrappers around -//! low level traits for most common hash-function use-cases. -//! -//! Additionally hash functions implement traits from `std`: `Default`, `Clone`, -//! `Write`. (the latter depends on enabled-by-default `std` crate feature) -//! -//! The `Digest` trait is the most commonly used trait. -#![no_std] -#![doc(html_logo_url = - "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")] -pub extern crate generic_array; -#[cfg(feature = "std")] -#[macro_use] extern crate std; -#[cfg(feature = "dev")] -pub extern crate blobby; -use generic_array::{GenericArray, ArrayLength}; -#[cfg(feature = "std")] -use std::vec::Vec; - -mod digest; -mod dyn_digest; -mod errors; -#[cfg(feature = "dev")] -pub mod dev; - -pub use errors::InvalidOutputSize; -pub use digest::Digest; -#[cfg(feature = "std")] -pub use dyn_digest::DynDigest; - -/// Trait for processing input data -pub trait Input { - /// Digest input data. - /// - /// This method can be called repeatedly, e.g. for processing streaming - /// messages. - fn input>(&mut self, data: B); - - /// Digest input data in a chained manner. - fn chain>(mut self, data: B) -> Self where Self: Sized { - self.input(data); - self - } -} - -/// Trait to indicate that digest function processes data in blocks of size -/// `BlockSize`. -/// -/// The main usage of this trait is for implementing HMAC generically. -pub trait BlockInput { - type BlockSize: ArrayLength; -} - -/// Trait for returning digest result with the fixed size -pub trait FixedOutput { - type OutputSize: ArrayLength; - - /// Retrieve result and consume hasher instance. - fn fixed_result(self) -> GenericArray; -} - -/// Trait for returning digest result with the variable size -pub trait VariableOutput: core::marker::Sized { - /// Create new hasher instance with the given output size. - /// - /// It will return `Err(InvalidOutputSize)` in case if hasher can not return - /// specified output size. It will always return an error if output size - /// equals to zero. - fn new(output_size: usize) -> Result; - - /// Get output size of the hasher instance provided to the `new` method - fn output_size(&self) -> usize; - - /// Retrieve result via closure and consume hasher. - /// - /// Closure is guaranteed to be called, length of the buffer passed to it - /// will be equal to `output_size`. - fn variable_result(self, f: F); - - /// Retrieve result into vector and consume hasher. - #[cfg(feature = "std")] - fn vec_result(self) -> Vec { - let mut buf = Vec::with_capacity(self.output_size()); - self.variable_result(|res| buf.extend_from_slice(res)); - buf - } -} - -/// Trait for describing readers which are used to extract extendable output -/// from XOF (extendable-output function) result. -pub trait XofReader { - /// Read output into the `buffer`. Can be called unlimited number of times. - fn read(&mut self, buffer: &mut [u8]); -} - -/// Trait which describes extendable-output functions (XOF). -pub trait ExtendableOutput: core::marker::Sized { - type Reader: XofReader; - - /// Retrieve XOF reader and consume hasher instance. - fn xof_result(self) -> Self::Reader; - - /// Retrieve result into vector of specified length. - #[cfg(feature = "std")] - fn vec_result(self, n: usize) -> Vec { - let mut buf = vec![0u8; n]; - self.xof_result().read(&mut buf); - buf - } -} - -/// Trait for resetting hash instances -pub trait Reset { - /// Reset hasher instance to its initial state and return current state. - fn reset(&mut self); -} - -#[macro_export] -/// Implements `std::io::Write` trait for implementer of `Input` -macro_rules! impl_write { - ($hasher:ident) => { - #[cfg(feature = "std")] - impl ::std::io::Write for $hasher { - fn write(&mut self, buf: &[u8]) -> ::std::io::Result { - Input::input(self, buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> ::std::io::Result<()> { - Ok(()) - } - } - } -} diff --git a/vendor/either/.cargo-checksum.json b/vendor/either/.cargo-checksum.json index 207aba04a..5e1f8841d 100644 --- a/vendor/either/.cargo-checksum.json +++ b/vendor/either/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"77c37f327af7a6146ba111c1c0a3e861bd444f31cfe44c3645c8e090502f66b4","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7576269ea71f767b99297934c0b2367532690f8c4badc695edf8e04ab6a1e545","README-crates.io.md":"b775991a01ab4a0a8de6169f597775319d9ce8178f5c74ccdc634f13a286b20c","README.rst":"f948f4333e9d66477128bcaf69a449a139bf00633eb57491fa1b379a3ce30b74","src/lib.rs":"e0f7c05e75af07765c2298a1791c65ea80f3c099491ed95c2e6c771041aa9931","src/serde_untagged.rs":"e826ee0ab31616e49c3e3f3711c8441001ee424b3e7a8c4c466cfcc4f8a7701a","src/serde_untagged_optional.rs":"86265f09d0795428bb2ce013b070d1badf1e2210217844a9ff3f04b2795868ab"},"package":"3f107b87b6afc2a64fd13cac55fe06d6c8859f12d4b14cbcdd2c67d0976781be"} \ No newline at end of file +{"files":{"Cargo.toml":"321950b99b4f04079e2470d754419bedba9851b71d1a2d8bd9c9046e38b87640","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7576269ea71f767b99297934c0b2367532690f8c4badc695edf8e04ab6a1e545","README-crates.io.md":"b775991a01ab4a0a8de6169f597775319d9ce8178f5c74ccdc634f13a286b20c","README.rst":"1369598deaae0ff925e8910df42354d33a43606961c40e7b71a7454a7f0b775e","src/lib.rs":"bc950126c901ea5c12ce4d02a7e58e3b1e2b428caca68bd510bad1f2488e2ced","src/serde_untagged.rs":"e826ee0ab31616e49c3e3f3711c8441001ee424b3e7a8c4c466cfcc4f8a7701a","src/serde_untagged_optional.rs":"86265f09d0795428bb2ce013b070d1badf1e2210217844a9ff3f04b2795868ab"},"package":"90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"} \ No newline at end of file diff --git a/vendor/either/Cargo.toml b/vendor/either/Cargo.toml index d571ff8da..eb1c5b4b5 100644 --- a/vendor/either/Cargo.toml +++ b/vendor/either/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2018" -rust-version = "1.31" +rust-version = "1.36" name = "either" -version = "1.7.0" +version = "1.8.0" authors = ["bluss"] description = """ The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. diff --git a/vendor/either/README.rst b/vendor/either/README.rst index 992e49c50..43c156a9f 100644 --- a/vendor/either/README.rst +++ b/vendor/either/README.rst @@ -25,12 +25,23 @@ __ https://docs.rs/either/ How to use with cargo:: [dependencies] - either = "1.7" + either = "1.8" Recent Changes -------------- +- 1.8.0 + + - **MSRV**: ``either`` now requires Rust 1.36 or later. + + - Add new methods ``.as_pin_ref()`` and ``.as_pin_mut()`` to project a + pinned ``Either`` as inner ``Pin`` variants, by @cuviper (#77) + + - Implement the ``Future`` trait, by @cuviper (#77) + + - Specialize more methods of the ``io`` traits, by @Kixunil and @cuviper (#75) + - 1.7.0 - **MSRV**: ``either`` now requires Rust 1.31 or later. diff --git a/vendor/either/src/lib.rs b/vendor/either/src/lib.rs index a4f2a5454..9a271c351 100644 --- a/vendor/either/src/lib.rs +++ b/vendor/either/src/lib.rs @@ -26,9 +26,11 @@ pub mod serde_untagged_optional; use core::convert::{AsMut, AsRef}; use core::fmt; +use core::future::Future; use core::iter; use core::ops::Deref; use core::ops::DerefMut; +use core::pin::Pin; #[cfg(any(test, feature = "use_std"))] use std::error::Error; @@ -255,6 +257,35 @@ impl Either { } } + /// Convert `Pin<&Either>` to `Either, Pin<&R>>`, + /// pinned projections of the inner variants. + pub fn as_pin_ref(self: Pin<&Self>) -> Either, Pin<&R>> { + // SAFETY: We can use `new_unchecked` because the `inner` parts are + // guaranteed to be pinned, as they come from `self` which is pinned. + unsafe { + match *Pin::get_ref(self) { + Left(ref inner) => Left(Pin::new_unchecked(inner)), + Right(ref inner) => Right(Pin::new_unchecked(inner)), + } + } + } + + /// Convert `Pin<&mut Either>` to `Either, Pin<&mut R>>`, + /// pinned projections of the inner variants. + pub fn as_pin_mut(self: Pin<&mut Self>) -> Either, Pin<&mut R>> { + // SAFETY: `get_unchecked_mut` is fine because we don't move anything. + // We can use `new_unchecked` because the `inner` parts are guaranteed + // to be pinned, as they come from `self` which is pinned, and we never + // offer an unpinned `&mut L` or `&mut R` through `Pin<&mut Self>`. We + // also don't have an implementation of `Drop`, nor manual `Unpin`. + unsafe { + match *Pin::get_unchecked_mut(self) { + Left(ref mut inner) => Left(Pin::new_unchecked(inner)), + Right(ref mut inner) => Right(Pin::new_unchecked(inner)), + } + } + } + /// Convert `Either` to `Either`. /// /// ``` @@ -1038,6 +1069,22 @@ where { } +/// `Either` is a future if both `L` and `R` are futures. +impl Future for Either +where + L: Future, + R: Future, +{ + type Output = L::Output; + + fn poll( + self: Pin<&mut Self>, + cx: &mut core::task::Context<'_>, + ) -> core::task::Poll { + for_both!(self.as_pin_mut(), inner => inner.poll(cx)) + } +} + #[cfg(any(test, feature = "use_std"))] /// `Either` implements `Read` if both `L` and `R` do. /// @@ -1051,9 +1098,17 @@ where for_both!(*self, ref mut inner => inner.read(buf)) } + fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { + for_both!(*self, ref mut inner => inner.read_exact(buf)) + } + fn read_to_end(&mut self, buf: &mut std::vec::Vec) -> io::Result { for_both!(*self, ref mut inner => inner.read_to_end(buf)) } + + fn read_to_string(&mut self, buf: &mut std::string::String) -> io::Result { + for_both!(*self, ref mut inner => inner.read_to_string(buf)) + } } #[cfg(any(test, feature = "use_std"))] @@ -1084,6 +1139,14 @@ where fn consume(&mut self, amt: usize) { for_both!(*self, ref mut inner => inner.consume(amt)) } + + fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec) -> io::Result { + for_both!(*self, ref mut inner => inner.read_until(byte, buf)) + } + + fn read_line(&mut self, buf: &mut std::string::String) -> io::Result { + for_both!(*self, ref mut inner => inner.read_line(buf)) + } } #[cfg(any(test, feature = "use_std"))] @@ -1099,6 +1162,14 @@ where for_both!(*self, ref mut inner => inner.write(buf)) } + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + for_both!(*self, ref mut inner => inner.write_all(buf)) + } + + fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { + for_both!(*self, ref mut inner => inner.write_fmt(fmt)) + } + fn flush(&mut self) -> io::Result<()> { for_both!(*self, ref mut inner => inner.flush()) } diff --git a/vendor/fake-simd/.cargo-checksum.json b/vendor/fake-simd/.cargo-checksum.json deleted file mode 100644 index f91a4a68f..000000000 --- a/vendor/fake-simd/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"c63db0226f9aac6e001898735c81392b8f01dfc8b7245f37e290990562c3c0d8","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"52232c2cee3bb7d8cabe47ef367f1bf8bb607c22bdfca0219d6156cb7f446e9d","src/lib.rs":"2cd66d61acfb96f3425194c12695d8e55cf56c6fbd02de90033c45bdcc338c1a"},"package":"e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"} \ No newline at end of file diff --git a/vendor/fake-simd/Cargo.toml b/vendor/fake-simd/Cargo.toml deleted file mode 100644 index 135c66097..000000000 --- a/vendor/fake-simd/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "fake-simd" -version = "0.1.2" -authors = ["The Rust-Crypto Project Developers"] -license = "MIT/Apache-2.0" -description = "Crate for mimicking simd crate on stable Rust" -documentation = "https://docs.rs/fake-simd" -repository = "https://github.com/RustCrypto/utils" -keywords = ["simd"] diff --git a/vendor/fake-simd/LICENSE-APACHE b/vendor/fake-simd/LICENSE-APACHE deleted file mode 100644 index 78173fa2e..000000000 --- a/vendor/fake-simd/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/fake-simd/LICENSE-MIT b/vendor/fake-simd/LICENSE-MIT deleted file mode 100644 index 1da3a5f6d..000000000 --- a/vendor/fake-simd/LICENSE-MIT +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2006-2009 Graydon Hoare -Copyright (c) 2009-2013 Mozilla Foundation - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/fake-simd/src/lib.rs b/vendor/fake-simd/src/lib.rs deleted file mode 100644 index 22c8727ed..000000000 --- a/vendor/fake-simd/src/lib.rs +++ /dev/null @@ -1,108 +0,0 @@ -#![no_std] -use core::ops::{Add, BitAnd, BitOr, BitXor, Shl, Shr, Sub}; - -#[derive(Clone, Copy, PartialEq, Eq)] -#[allow(non_camel_case_types)] -pub struct u32x4(pub u32, pub u32, pub u32, pub u32); - -impl Add for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn add(self, rhs: u32x4) -> u32x4 { - u32x4( - self.0.wrapping_add(rhs.0), - self.1.wrapping_add(rhs.1), - self.2.wrapping_add(rhs.2), - self.3.wrapping_add(rhs.3)) - } -} - -impl Sub for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn sub(self, rhs: u32x4) -> u32x4 { - u32x4( - self.0.wrapping_sub(rhs.0), - self.1.wrapping_sub(rhs.1), - self.2.wrapping_sub(rhs.2), - self.3.wrapping_sub(rhs.3)) - } -} - -impl BitAnd for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn bitand(self, rhs: u32x4) -> u32x4 { - u32x4(self.0 & rhs.0, self.1 & rhs.1, self.2 & rhs.2, self.3 & rhs.3) - } -} - -impl BitOr for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn bitor(self, rhs: u32x4) -> u32x4 { - u32x4(self.0 | rhs.0, self.1 | rhs.1, self.2 | rhs.2, self.3 | rhs.3) - } -} - -impl BitXor for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn bitxor(self, rhs: u32x4) -> u32x4 { - u32x4(self.0 ^ rhs.0, self.1 ^ rhs.1, self.2 ^ rhs.2, self.3 ^ rhs.3) - } -} - -impl Shl for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn shl(self, amt: usize) -> u32x4 { - u32x4(self.0 << amt, self.1 << amt, self.2 << amt, self.3 << amt) - } -} - -impl Shl for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn shl(self, rhs: u32x4) -> u32x4 { - u32x4(self.0 << rhs.0, self.1 << rhs.1, self.2 << rhs.2, self.3 << rhs.3) - } -} - -impl Shr for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn shr(self, amt: usize) -> u32x4 { - u32x4(self.0 >> amt, self.1 >> amt, self.2 >> amt, self.3 >> amt) - } -} - -impl Shr for u32x4 { - type Output = u32x4; - - #[inline(always)] - fn shr(self, rhs: u32x4) -> u32x4 { - u32x4(self.0 >> rhs.0, self.1 >> rhs.1, self.2 >> rhs.2, self.3 >> rhs.3) - } -} - -#[derive(Clone, Copy)] -#[allow(non_camel_case_types)] -pub struct u64x2(pub u64, pub u64); - -impl Add for u64x2 { - type Output = u64x2; - - #[inline(always)] - fn add(self, rhs: u64x2) -> u64x2 { - u64x2(self.0.wrapping_add(rhs.0), self.1.wrapping_add(rhs.1)) - } -} diff --git a/vendor/form_urlencoded/.cargo-checksum.json b/vendor/form_urlencoded/.cargo-checksum.json index 33e19d140..29befa62b 100644 --- a/vendor/form_urlencoded/.cargo-checksum.json +++ b/vendor/form_urlencoded/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"aadc4e4ba33e86861d8d1d8b848ac11a27b6f87340d082b47f762387464c61ed","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"20c7855c364d57ea4c97889a5e8d98470a9952dade37bd9248b9a54431670e5e","src/lib.rs":"5d30edec687843447c97e4ea87583983eb9fc06135ae718c8ecc0fa8cebef2df"},"package":"5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191"} \ No newline at end of file +{"files":{"Cargo.toml":"1771c35bc67b544a7ebc6f31168d7bc08d29ae76323e7ee10352d43b5a38afac","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"20c7855c364d57ea4c97889a5e8d98470a9952dade37bd9248b9a54431670e5e","src/lib.rs":"c1a0db36086e4fd0e8bb1489f9c2bb55945dd233614bf5dc3a0c41cb49292dd3"},"package":"a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"} \ No newline at end of file diff --git a/vendor/form_urlencoded/Cargo.toml b/vendor/form_urlencoded/Cargo.toml index 4c9fae259..037361d31 100644 --- a/vendor/form_urlencoded/Cargo.toml +++ b/vendor/form_urlencoded/Cargo.toml @@ -3,26 +3,24 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" +rust-version = "1.51" name = "form_urlencoded" -version = "1.0.1" +version = "1.1.0" authors = ["The rust-url developers"] description = "Parser and serializer for the application/x-www-form-urlencoded syntax, as used by HTML forms." -license = "MIT/Apache-2.0" +license = "MIT OR Apache-2.0" repository = "https://github.com/servo/rust-url" [lib] test = false -[dependencies.matches] -version = "0.1" [dependencies.percent-encoding] -version = "2.1.0" +version = "2.2.0" diff --git a/vendor/form_urlencoded/src/lib.rs b/vendor/form_urlencoded/src/lib.rs index 765ee168a..477594bf7 100644 --- a/vendor/form_urlencoded/src/lib.rs +++ b/vendor/form_urlencoded/src/lib.rs @@ -13,9 +13,6 @@ //! Converts between a string (such as an URL’s query string) //! and a sequence of (name, value) pairs. -#[macro_use] -extern crate matches; - use percent_encoding::{percent_decode, percent_encode_byte}; use std::borrow::{Borrow, Cow}; use std::str; @@ -402,8 +399,7 @@ pub(crate) fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> { // replace invalid bytes with a placeholder. // First we do a debug_assert to confirm our description above. - let raw_utf8: *const [u8]; - raw_utf8 = utf8.as_bytes(); + let raw_utf8: *const [u8] = utf8.as_bytes(); debug_assert!(raw_utf8 == &*bytes as *const [u8]); // Given we know the original input bytes are valid UTF-8, diff --git a/vendor/fortanix-sgx-abi/.cargo-checksum.json b/vendor/fortanix-sgx-abi/.cargo-checksum.json index 54731bac0..71c7c4425 100644 --- a/vendor/fortanix-sgx-abi/.cargo-checksum.json +++ b/vendor/fortanix-sgx-abi/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"2f11a404e7361ab1b4bfd6bf5189c18091df9dcedda93dce14dcb01b59a2d85a","src/lib.rs":"2493f0264dfaaac19471aa5cb3da8011ead8f804f3ac722195478894a7d011d1"},"package":"c56c422ef86062869b2d57ae87270608dc5929969dd130a6e248979cf4fb6ca6"} \ No newline at end of file +{"files":{"Cargo.toml":"5ef38d3c4329644a02d5fe6019ea401cdd64d31c1a26fd16cf30c7d2dd87873f","src/lib.rs":"2da4a01e8baae15069a6ea32610602f1741e8deccad696f7f7d3e69035da2962"},"package":"57cafc2274c10fab234f176b25903ce17e690fca7597090d50880e047a0389c5"} \ No newline at end of file diff --git a/vendor/fortanix-sgx-abi/Cargo.toml b/vendor/fortanix-sgx-abi/Cargo.toml index 1a3b9c168..28e2993bb 100644 --- a/vendor/fortanix-sgx-abi/Cargo.toml +++ b/vendor/fortanix-sgx-abi/Cargo.toml @@ -3,26 +3,41 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] name = "fortanix-sgx-abi" -version = "0.3.3" +version = "0.5.0" authors = ["Fortanix, Inc."] -description = "An interface for Intel SGX enclaves. This is the interface for the\n`x86_64-fortanix-unknown-sgx` target.\n\nThis is a small yet functional interface suitable for writing larger enclaves. \nIn contrast to other enclave interfaces, this interface is primarly designed \nfor running entire applications in an enclave.\n\nThis crate fully describes the type-level interface complete with \ndocumentation. For implementors, this crate contains all the type definitions\nand a macro with the function definitions.\n" +description = """ +An interface for Intel SGX enclaves. This is the interface for the +`x86_64-fortanix-unknown-sgx` target. + +This is a small yet functional interface suitable for writing larger enclaves. +In contrast to other enclave interfaces, this interface is primarly designed +for running entire applications in an enclave. + +This crate fully describes the type-level interface complete with +documentation. For implementors, this crate contains all the type definitions +and a macro with the function definitions. +""" homepage = "https://edp.fortanix.com/" documentation = "https://edp.fortanix.com/docs/api/fortanix_sgx_abi/" -keywords = ["sgx", "enclave"] +keywords = [ + "sgx", + "enclave", +] categories = ["os"] license = "MPL-2.0" repository = "https://github.com/fortanix/rust-sgx" + [package.metadata.docs.rs] features = ["docs"] + [dependencies.compiler_builtins] version = "0.1.0" optional = true @@ -34,4 +49,7 @@ package = "rustc-std-workspace-core" [features] docs = [] -rustc-dep-of-std = ["core", "compiler_builtins/rustc-dep-of-std"] +rustc-dep-of-std = [ + "core", + "compiler_builtins/rustc-dep-of-std", +] diff --git a/vendor/fortanix-sgx-abi/src/lib.rs b/vendor/fortanix-sgx-abi/src/lib.rs index 362defb8f..3511ae34b 100644 --- a/vendor/fortanix-sgx-abi/src/lib.rs +++ b/vendor/fortanix-sgx-abi/src/lib.rs @@ -15,7 +15,7 @@ //! The Fortanix SGX ABI (compiler target `x86_64-fortanix-unknown-sgx`) is an //! interface for Intel SGX enclaves. It is a small yet functional interface //! suitable for writing larger enclaves. In contrast to other enclave -//! interfaces, this interface is primarly designed for running entire +//! interfaces, this interface is primarily designed for running entire //! applications in an enclave. //! //! The Fortanix SGX ABI specification consists of two parts: @@ -82,7 +82,7 @@ html_root_url = "https://edp.fortanix.com/docs/api/")] use core::ptr::NonNull; -use core::sync::atomic::AtomicUsize; +use core::sync::atomic::{AtomicU64, AtomicUsize}; macro_rules! invoke_with_abi_spec [ ( $m:ident ) => [ $m![ @@ -186,6 +186,9 @@ pub struct ByteBuffer { pub len: usize } +#[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] +unsafe impl Send for ByteBuffer {} + /// Error code definitions and space allocation. /// /// Only non-zero positive values are valid errors. The variants are designed @@ -222,7 +225,7 @@ pub enum Error { UserRangeEnd = 0x7fff_ffff, } -/// A value indicating that the operation was succesful. +/// A value indicating that the operation was successful. #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] pub const RESULT_SUCCESS: Result = 0; @@ -301,7 +304,7 @@ impl Usercalls { /// Read up to `len` bytes from stream `fd`. /// /// `buf` must point to a buffer in userspace with a size of at least - /// `len`. On a succesful return, the number of bytes written is returned. + /// `len`. On a successful return, the number of bytes written is returned. /// The enclave must check that the returned length is no more than `len`. /// If `len` is `0`, this call should block until the stream is ready for /// reading. If `len` is `0` or end of stream is reached, `0` may be @@ -330,7 +333,7 @@ impl Usercalls { /// Write up to `len` bytes to stream `fd`. /// /// `buf` must point to a buffer in userspace with a size of at least - /// `len`. On a succesful return, the number of bytes written is returned. + /// `len`. On a successful return, the number of bytes written is returned. /// The enclave must check that the returned length is no more than `len`. /// If `len` is `0`, this call should block until the stream is ready for /// writing. If `len` is `0` or the stream is closed, `0` may be returned. @@ -453,6 +456,10 @@ pub const EV_RETURNQ_NOT_EMPTY: u64 = 0b0000_0000_0000_0010; /// An event that enclaves can use for synchronization. #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] pub const EV_UNPARK: u64 = 0b0000_0000_0000_0100; +/// An event that will be triggered by userspace when the cancel queue is not +/// or no longer full. +#[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] +pub const EV_CANCELQ_NOT_FULL: u64 = 0b0000_0000_0000_1000; #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] pub const WAIT_NO: u64 = 0; @@ -464,9 +471,10 @@ pub const WAIT_INDEFINITE: u64 = !0; /// ## TCS event queues /// /// Userspace will maintain a queue for each running TCS with events to be -/// delivered. Each event is characterized by a bitset. Userspace or the -/// enclave (using the `send` usercall) can put events on this queue. If the -/// enclave isn't waiting for an event when an event is queued, the event +/// delivered. Each event is characterized by a bitset with at least one bit +/// set. Userspace or the enclave (using the `send` usercall) can put events on +/// this queue. +/// If the enclave isn't waiting for an event when an event is queued, the event /// remains on the queue until it delivered to the enclave in a later `wait` /// usercall. If an enclave is waiting for an event, and the queue contains an /// event that is a subset of the waited-for event mask, that event is removed @@ -481,7 +489,7 @@ impl Usercalls { /// this with the number of entries into [`thread_entry`]. If no free TCSes /// are immediately available, this may return an error. /// - /// This function will never be succesful in [libraries]. See the + /// This function will never be successful in [libraries]. See the /// [`library`] documentation on how to use threads with libraries. /// /// [`thread_entry`]: entry/executable/fn.thread_entry.html @@ -503,14 +511,18 @@ impl Usercalls { /// Wait for an event to occur, or check if an event is currently pending. /// - /// `timeout` must be [`WAIT_NO`] or [`WAIT_INDEFINITE`]. If it is another - /// value, userspace will return an error. + /// `timeout` must be [`WAIT_NO`] or [`WAIT_INDEFINITE`] or a positive + /// value smaller than u64::MAX specifying number of nanoseconds to wait. /// /// If `timeout` is [`WAIT_INDEFINITE`], this call will block and return /// once a matching event is queued on this TCS. If `timeout` is /// [`WAIT_NO`], this call will return immediately, and the return value /// will indicate if an event was pending. If it was, it has been dequeued. - /// If not, the [`WouldBlock`] error value will be returned. + /// If not, the [`WouldBlock`] error value will be returned. If `timeout` + /// is a value other than [`WAIT_NO`] and [`WAIT_INDEFINITE`], this call + /// will block until either a matching event is queued in which case the + /// return value will indicate the event, or the timeout is reached in + /// which case the [`TimedOut`] error value will be returned. /// /// A matching event is one whose bits are equal to or a subset of /// `event_mask`. If `event_mask` is `0`, this call will never return due @@ -534,6 +546,7 @@ impl Usercalls { /// [`WAIT_INDEFINITE`]: constant.WAIT_INDEFINITE.html /// [`EV_RETURNQ_NOT_EMPTY`]: constant.EV_RETURNQ_NOT_EMPTY.html /// [`WouldBlock`]: enum.Error.html#variant.WouldBlock + /// [`TimedOut`]: enum.Error.html#variant.TimedOut pub fn wait(event_mask: u64, timeout: u64) -> (Result, u64) { unimplemented!() } /// Send an event to one or all TCSes. @@ -568,7 +581,7 @@ impl Usercalls { /// Request user memory. /// /// Request an allocation in user memory of size `size` and with alignment - /// `align`. If succesful, a pointer to this memory will be returned. The + /// `align`. If successful, a pointer to this memory will be returned. The /// enclave must check the pointer is correctly aligned and that the entire /// range of memory pointed to is outside the enclave. /// @@ -589,7 +602,7 @@ impl Usercalls { /// Asynchronous usercall specification. /// /// An asynchronous usercall allows an enclave to submit a usercall without -/// exiting the enclave. This is necessary since enclave entries and exists are +/// exiting the enclave. This is necessary since enclave entries and exits are /// slow (see academic work on [SCONE], [HotCalls]). In addition, the enclave /// can perform other tasks while it waits for the usercall to complete. Those /// tasks may include issuing other usercalls, either synchronously or @@ -605,18 +618,40 @@ impl Usercalls { /// concurrent usercalls with the same `id`, but it may reuse an `id` once the /// original usercall with that `id` has returned. /// +/// An optional third queue can be used to cancel usercalls. To cancel an async +/// usercall, the enclave should send the usercall's id and number on this +/// queue. If the usercall has already been processed, the enclave may still +/// receive a successful result for the usercall. Otherwise, the userspace will +/// cancel the usercall's execution and return an [`Interrupted`] error on the +/// return queue to notify the enclave of the cancellation. Note that usercalls +/// that do not return [`Result`] cannot be cancelled and if the enclave sends +/// a cancellation for such a usercall, the userspace should simply ignore it. +/// Additionally, userspace may choose to ignore cancellations for non-blocking +/// usercalls. Userspace should be able to cancel a usercall that has been sent +/// by the enclave but not yet received by the userspace, i.e. if cancellation +/// is received before the usercall itself. To avoid keeping such cancellations +/// forever and preventing the enclave from re-using usercall ids, userspace +/// should synchronize cancel queue with the usercall queue such that the +/// following invariant is maintained: whenever the enclave writes an id to the +/// usercall or cancel queue, the enclave will not reuse that id until the +/// usercall queue's read pointer has advanced to the write pointer at the time +/// the id was written. +/// /// *TODO*: Add diagram. /// /// [MPSC queues]: struct.FifoDescriptor.html /// [allocated per enclave]: ../struct.Usercalls.html#method.async_queues /// [SCONE]: https://www.usenix.org/conference/osdi16/technical-sessions/presentation/arnautov /// [HotCalls]: http://www.ofirweisse.com/ISCA17_Ofir_Weisse.pdf +/// [`Interrupted`]: enum.Error.html#variant.Interrupted +/// [`Result`]: type.Result.html /// /// # Enclave/userspace synchronization /// /// When the enclave needs to wait on a queue, it executes the [`wait()`] /// usercall synchronously, specifying [`EV_USERCALLQ_NOT_FULL`], -/// [`EV_RETURNQ_NOT_EMPTY`], or both in the `event_mask`. Userspace will wake +/// [`EV_RETURNQ_NOT_EMPTY`], [`EV_CANCELQ_NOT_FULL`], or any combination +/// thereof in the `event_mask`. Userspace will wake /// any or all threads waiting on the appropriate event when it is triggered. /// /// When userspace needs to wait on a queue, it will park the current thread @@ -627,34 +662,70 @@ impl Usercalls { /// [`wait()`]: ../struct.Usercalls.html#method.wait /// [`EV_USERCALLQ_NOT_FULL`]: ../constant.EV_USERCALLQ_NOT_FULL.html /// [`EV_RETURNQ_NOT_EMPTY`]: ../constant.EV_RETURNQ_NOT_EMPTY.html +/// [`EV_CANCELQ_NOT_FULL`]: ../constant.EV_CANCELQ_NOT_FULL.html pub mod async { use super::*; - use core::sync::atomic::AtomicUsize; + use core::sync::atomic::{AtomicU64, AtomicUsize}; - /// An identified usercall. #[repr(C)] - #[derive(Copy, Clone)] #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] - pub struct Usercall { - /// `0` indicates this slot is empty. - pub id: u64, - /// The elements correspond to the RDI, RSI, RDX, R8, and R9 registers - /// in the synchronous calling convention. - pub args: (u64, u64, u64, u64, u64) + pub struct WithId { + pub id: AtomicU64, + pub data: T, + } + + /// A usercall. + /// The elements correspond to the RDI, RSI, RDX, R8, and R9 registers + /// in the synchronous calling convention. + #[repr(C)] + #[derive(Copy, Clone, Default)] + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + pub struct Usercall(pub u64, pub u64, pub u64, pub u64, pub u64); + + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + impl From for (u64, u64, u64, u64, u64) { + fn from(u: Usercall) -> Self { + let Usercall(p1, p2, p3, p4, p5) = u; + (p1, p2, p3, p4, p5) + } + } + + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + impl From<(u64, u64, u64, u64, u64)> for Usercall { + fn from(p: (u64, u64, u64, u64, u64)) -> Self { + Usercall(p.0, p.1, p.2, p.3, p.4) + } } - /// The return value of an identified usercall. + /// The return value of a usercall. + /// The elements correspond to the RSI and RDX registers in the + /// synchronous calling convention. #[repr(C)] - #[derive(Copy, Clone)] + #[derive(Copy, Clone, Default)] #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] - pub struct Return { - /// `0` indicates this slot is empty. - pub id: u64, - /// The elements correspond to the RSI and RDX registers in the - /// synchronous calling convention. - pub value: (u64, u64) + pub struct Return(pub u64, pub u64); + + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + impl From for (u64, u64) { + fn from(r: Return) -> Self { + let Return(r1, r2) = r; + (r1, r2) + } } + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + impl From<(u64, u64)> for Return { + fn from(r: (u64, u64)) -> Self { + Return(r.0, r.1) + } + } + + /// Cancel a usercall previously sent to userspace. + #[repr(C)] + #[derive(Copy, Clone, Default)] + #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] + pub struct Cancel; + /// A circular buffer used as a FIFO queue with atomic reads and writes. /// /// The read offset is the element that was most recently read by the @@ -679,7 +750,7 @@ pub mod async { /// 1. Load the current offsets. /// 2. If the queue is full, wait, then go to step 1. /// 3. Add 1 to the write offset and do an atomic compare-and-swap (CAS) - /// with the current offsets. If the CAS was not succesful, go to step + /// with the current offsets. If the CAS was not successful, go to step /// 1\. /// 4. Write the data, then the `id`. /// 5. If the queue was empty in step 1, signal the reader to wake up. @@ -695,14 +766,15 @@ pub mod async { /// 5. If `id` is `0`, go to step 4 (spin). Spinning is OK because data is /// expected to be written imminently. /// 6. Read the data, then store `0` in the `id`. - /// 7. Store the new read offset. - /// 8. If the queue was full in step 1, signal the writer to wake up. + /// 7. Store the new read offset, retrieving the old offsets. + /// 8. If the queue was full before step 7, signal the writer to wake up. #[repr(C)] #[cfg_attr(feature = "rustc-dep-of-std", unstable(feature = "sgx_platform", issue = "56975"))] pub struct FifoDescriptor { /// Pointer to the queue memory. Must have a size of - /// `len * size_of::()` bytes and have alignment `align_of::`. - pub data: *mut T, + /// `len * size_of::>()` bytes and have alignment + /// `align_of::>`. + pub data: *mut WithId, /// The number of elements pointed to by `data`. Must be a power of two /// less than or equal to 2³¹. pub len: usize, @@ -735,11 +807,13 @@ pub mod async { impl Usercalls { /// Request FIFO queues for asynchronous usercalls. `usercall_queue` /// and `return_queue` must point to valid user memory with the correct - /// size and alignment for their types. On return, userspace will have - /// filled these structures with information about the queues. A single - /// set of queues will be allocated per enclave. Once this usercall has - /// returned succesfully, calling this usercall again is equivalent to - /// calling `exit(true)`. + /// size and alignment for their types. `cancel_queue` is optional, but + /// if specified (not null) it must point to valid user memory with + /// correct size and alignment. + /// On return, userspace will have filled these structures with + /// information about the queues. A single set of queues will be + /// allocated per enclave. Once this usercall has returned successfully, + /// calling this usercall again is equivalent to calling `exit(true)`. /// /// May fail if the platform does not support asynchronous usercalls. /// @@ -747,7 +821,11 @@ pub mod async { /// [`FifoDescriptor`] is outside the enclave. /// /// [`FifoDescriptor`]: async/struct.FifoDescriptor.html - pub fn async_queues(usercall_queue: *mut FifoDescriptor, return_queue: *mut FifoDescriptor) -> Result { unimplemented!() } + pub fn async_queues( + usercall_queue: *mut FifoDescriptor, + return_queue: *mut FifoDescriptor, + cancel_queue: *mut FifoDescriptor + ) -> Result { unimplemented!() } } } diff --git a/vendor/fs-err/.cargo-checksum.json b/vendor/fs-err/.cargo-checksum.json index 96f6899da..0cafc2bae 100644 --- a/vendor/fs-err/.cargo-checksum.json +++ b/vendor/fs-err/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"8b53bca7b646d3afd45cde66ce850b263218904ecdd66f47e5684ef04ec873b8","Cargo.toml":"03bb23a8e71f90f8e7e5c6120f97f22b3319b2be1adb751a5f6b312fa62c9a18","LICENSE-APACHE":"7cfd738c53d61c79f07e348f622bf7707c9084237054d37fbe07788a75f5881c","LICENSE-MIT":"36516aefdc84c5d5a1e7485425913a22dbda69eb1930c5e84d6ae4972b5194b9","README.md":"e5c3355cb080a50bade0664df1f853e3f041121a9aa5bda2074ce6e01e210437","README.tpl":"de2f4fa16d473b928004aed4e11bd70522690961c6e34094a07fc68e9a092426","src/dir.rs":"1fbc8a3ada7e5e8a8c15dc0bf0e3c94cbeeea26e4a5f2b411c62d93adc023ebb","src/errors.rs":"263370df16fb2fc2c77c7b434da301792c61841960855dc11ba99523a324a2f3","src/file.rs":"dccdbd8f2b2e4e7c167df555f3a1facbf8003292c081d842711a852f2cf4b471","src/lib.rs":"f3e2041ef73f15b88594d93370b53e8f08717f7ce142184ec0c40e42d7b73c91","src/open_options.rs":"3ea24a370732eff1da0fae2205f251d3171d4e5e03f4c38508a2114942a16466","src/os.rs":"54fe6cb71a24592de1cb4e1fcebdeaba5e58b26925dbf2dc868e8dd0b0a7bef7","src/os/unix.rs":"3e2940651ce8d7b624d10bb9f3e64334812e1bb0476d12dfec130dcb1b16fe7e","src/os/windows.rs":"6dc3099f9e48a386cba9f58599796583f0cb3c8b7123168f8d1c8e27fd8763e3","src/path.rs":"949dff5847ef0983ede9e9eec1fa0f3e6d8ffd1a35004249ad04a2d2700eb85b","tests/version-numbers.rs":"370467b40ce930d655389ba82015ae2842b3361bf24280c3dc7214d3ac163a2d"},"package":"bcd1163ae48bda72a20ae26d66a04d3094135cadab911cff418ae5e33f253431"} \ No newline at end of file +{"files":{"CHANGELOG.md":"fb2609e5837d71e923def1765b6addc4d11b0b5040e7eb9bdbf50d59a4a5cd42","Cargo.toml":"b468e8d560ea6e30277c2ee438ac650bbb2397f5b62da911126c180921aa5d29","LICENSE-APACHE":"7cfd738c53d61c79f07e348f622bf7707c9084237054d37fbe07788a75f5881c","LICENSE-MIT":"36516aefdc84c5d5a1e7485425913a22dbda69eb1930c5e84d6ae4972b5194b9","README.md":"adbf428f33a04028cc8db98d7b75bdcf28d0edb5e792867578bcb93f1784abec","src/dir.rs":"c5255382d7357f2fbcb0b45325a343277d347f0dd0b5f0e5ff74cb808020795d","src/errors.rs":"f04771790f55627fdc39de43a1d16f7d0125bbf48d4a1c8a70921f2670dd3eaa","src/file.rs":"4516834bc52f1219f10e369bf570fd432493ceaf5d52d239d93a5e69ceaed0aa","src/lib.rs":"1a10c04bde2bc3ae30cc328afb0aa00ac98ab80c6bfff5ae94ee7e5bdbe86ec8","src/open_options.rs":"304c5be36b5a6c5ecc2c731e2956627494945d093952c879d8f3c5b15216b1d0","src/os.rs":"54fe6cb71a24592de1cb4e1fcebdeaba5e58b26925dbf2dc868e8dd0b0a7bef7","src/os/unix.rs":"21ab862305b9e1034c41bb4be31b1f3d43e3d208ca3e622211b6b54d1bbd9acc","src/os/windows.rs":"4cf0530becb6fed439f469e1f22f57de9ae2ac15e39f2a973f4734aee6267ed0","src/path.rs":"a026ae234184ed1bbadd9051099e201c3ac6309b1fd939d1b2d2b2a7cb82230d"},"package":"64db3e262960f0662f43a6366788d5f10f7f244b8f7d7d987f560baf5ded5c50"} \ No newline at end of file diff --git a/vendor/fs-err/CHANGELOG.md b/vendor/fs-err/CHANGELOG.md index bc973e22c..ee7e4be32 100644 --- a/vendor/fs-err/CHANGELOG.md +++ b/vendor/fs-err/CHANGELOG.md @@ -1,5 +1,22 @@ # fs-err Changelog +## 2.8.1 + +* Fixed docs.rs build + +## 2.8.0 + +* Implement I/O safety traits (`AsFd`/`AsHandle`, `Into`/`Into`) for file. This feature requires Rust 1.63 or later and is gated behind the `io_safety` feature flag. ([#39](https://github.com/andrewhickman/fs-err/pull/39)) + +## 2.7.0 + +* Implement `From for std::fs::File` ([#38](https://github.com/andrewhickman/fs-err/pull/38)) + +## 2.6.0 + +* Added [`File::into_parts`](https://docs.rs/fs-err/2.6.0/fs_err/struct.File.html#method.into_parts) and [`File::file_mut`](https://docs.rs/fs-err/2.6.0/fs_err/struct.File.html#method.file_mut) to provide more access to the underlying `std::fs::File`. +* Fixed some typos in documention ([#33](https://github.com/andrewhickman/fs-err/pull/33)) + ## 2.5.0 * Added `symlink` for unix platforms * Added `symlink_file` and `symlink_dir` for windows @@ -11,7 +28,7 @@ - Added trait wrappers for `std::os::{unix, windows}::fs::OpenOptionsExt` and implemented them for `fs_err::OpenOptions` * Improved compile times by converting arguments early and forwarding only a small number of types internally. There will be a slight performance hit only in the error case. * Reduced trait bounds on generics from `AsRef + Into` to either `AsRef` or `Into`, making the functions more general. - + ## 2.4.0 * Added `canonicalize`, `hard link`, `read_link`, `rename`, `symlink_metadata` and `soft_link`. ([#25](https://github.com/andrewhickman/fs-err/pull/25)) * Added aliases to `std::path::Path` via extension trait ([#26](https://github.com/andrewhickman/fs-err/pull/26)) diff --git a/vendor/fs-err/Cargo.toml b/vendor/fs-err/Cargo.toml index 62c4c651c..07bada50a 100644 --- a/vendor/fs-err/Cargo.toml +++ b/vendor/fs-err/Cargo.toml @@ -3,28 +3,53 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies +# to registry (e.g., crates.io) dependencies. # -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "fs-err" -version = "2.5.0" +version = "2.8.1" authors = ["Andrew Hickman "] +exclude = [ + ".github", + ".gitignore", + "README.tpl", +] description = "A drop-in replacement for std::fs with more helpful error messages." documentation = "https://docs.rs/fs-err" readme = "README.md" -categories = ["command-line-interface", "filesystem"] +categories = [ + "command-line-interface", + "filesystem", +] license = "MIT/Apache-2.0" repository = "https://github.com/andrewhickman/fs-err" +[package.metadata.release] +tag-name = "{{version}}" +sign-tag = true + +[[package.metadata.release.pre-release-replacements]] +file = "src/lib.rs" +search = 'html_root_url = "https://docs\.rs/fs-err/.*?"' +replace = "html_root_url = \"https://docs.rs/fs-err/{{version}}\"" +exactly = 1 + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = [ + "--cfg", + "docsrs", +] + [dependencies] + [dev-dependencies.serde_json] -version = "1.0.48" +version = "1.0.64" -[dev-dependencies.version-sync] -version = "0.8.1" +[features] +io_safety = [] diff --git a/vendor/fs-err/README.md b/vendor/fs-err/README.md index 70bf1fa44..0dc5fc1c3 100644 --- a/vendor/fs-err/README.md +++ b/vendor/fs-err/README.md @@ -11,7 +11,7 @@ fs-err is a drop-in replacement for [`std::fs`][std::fs] that provides more helpful messages on errors. Extra information includes which operations was -attmpted and any involved paths. +attempted and any involved paths. ## Error Messages diff --git a/vendor/fs-err/README.tpl b/vendor/fs-err/README.tpl deleted file mode 100644 index 35ac8052d..000000000 --- a/vendor/fs-err/README.tpl +++ /dev/null @@ -1,28 +0,0 @@ - - -# {{crate}} - -[![Crates.io](https://img.shields.io/crates/v/fs-err.svg)](https://crates.io/crates/fs-err) -[![GitHub Actions](https://github.com/andrewhickman/fs-err/workflows/CI/badge.svg)](https://github.com/andrewhickman/fs-err/actions?query=workflow%3ACI) - -{{readme}} - -## License - -Licensed under either of - -* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) -* MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) - -at your option. - -### Contribution - -Unless you explicitly state otherwise, any contribution intentionally -submitted for inclusion in the work by you, as defined in the Apache-2.0 -license, shall be dual licensed as above, without any additional terms or -conditions. \ No newline at end of file diff --git a/vendor/fs-err/src/dir.rs b/vendor/fs-err/src/dir.rs index adba643b9..6efa58da6 100644 --- a/vendor/fs-err/src/dir.rs +++ b/vendor/fs-err/src/dir.rs @@ -11,7 +11,7 @@ pub fn read_dir>(path: P) -> io::Result { match fs::read_dir(&path) { Ok(inner) => Ok(ReadDir { inner, path }), - Err(source) => Err(Error::new(source, ErrorKind::ReadDir, path)), + Err(source) => Err(Error::build(source, ErrorKind::ReadDir, path)), } } @@ -32,7 +32,12 @@ impl Iterator for ReadDir { type Item = io::Result; fn next(&mut self) -> Option { - Some(self.inner.next()?.map(|inner| DirEntry { inner })) + Some( + self.inner + .next()? + .map_err(|source| Error::build(source, ErrorKind::ReadDir, &self.path)) + .map(|inner| DirEntry { inner }), + ) } } @@ -55,14 +60,14 @@ impl DirEntry { pub fn metadata(&self) -> io::Result { self.inner .metadata() - .map_err(|source| Error::new(source, ErrorKind::Metadata, self.path())) + .map_err(|source| Error::build(source, ErrorKind::Metadata, self.path())) } /// Wrapper for [`DirEntry::file_type`](https://doc.rust-lang.org/stable/std/fs/struct.DirEntry.html#method.file_type). pub fn file_type(&self) -> io::Result { self.inner .file_type() - .map_err(|source| Error::new(source, ErrorKind::Metadata, self.path())) + .map_err(|source| Error::build(source, ErrorKind::Metadata, self.path())) } /// Wrapper for [`DirEntry::file_name`](https://doc.rust-lang.org/stable/std/fs/struct.DirEntry.html#method.file_name). diff --git a/vendor/fs-err/src/errors.rs b/vendor/fs-err/src/errors.rs index 466d28f11..43bc4ba42 100644 --- a/vendor/fs-err/src/errors.rs +++ b/vendor/fs-err/src/errors.rs @@ -47,12 +47,15 @@ pub(crate) struct Error { } impl Error { - pub fn new(source: io::Error, kind: ErrorKind, path: impl Into) -> io::Error { - Self::_new(source, kind, path.into()) - } - - fn _new(source: io::Error, kind: ErrorKind, path: PathBuf) -> io::Error { - io::Error::new(source.kind(), Self { kind, source, path }) + pub fn build(source: io::Error, kind: ErrorKind, path: impl Into) -> io::Error { + io::Error::new( + source.kind(), + Self { + kind, + source, + path: path.into(), + }, + ) } } @@ -131,28 +134,19 @@ pub(crate) struct SourceDestError { } impl SourceDestError { - pub fn new( + pub fn build( source: io::Error, kind: SourceDestErrorKind, from_path: impl Into, to_path: impl Into, - ) -> io::Error { - Self::_new(source, kind, from_path.into(), to_path.into()) - } - - fn _new( - source: io::Error, - kind: SourceDestErrorKind, - from_path: PathBuf, - to_path: PathBuf, ) -> io::Error { io::Error::new( source.kind(), Self { kind, source, - from_path, - to_path, + from_path: from_path.into(), + to_path: to_path.into(), }, ) } diff --git a/vendor/fs-err/src/file.rs b/vendor/fs-err/src/file.rs index a9c8988e5..fcf54fe3c 100644 --- a/vendor/fs-err/src/file.rs +++ b/vendor/fs-err/src/file.rs @@ -17,12 +17,12 @@ pub struct File { // Opens a std File and returns it or an error generator which only needs the path to produce the error. // Exists for the `crate::read*` functions so they don't unconditionally build a PathBuf. pub(crate) fn open(path: &Path) -> Result io::Error> { - fs::File::open(&path).map_err(|err| |path| Error::new(err, ErrorKind::OpenFile, path)) + fs::File::open(&path).map_err(|err| |path| Error::build(err, ErrorKind::OpenFile, path)) } // like `open()` but for `crate::write` pub(crate) fn create(path: &Path) -> Result io::Error> { - fs::File::create(&path).map_err(|err| |path| Error::new(err, ErrorKind::CreateFile, path)) + fs::File::create(&path).map_err(|err| |path| Error::build(err, ErrorKind::CreateFile, path)) } /// Wrappers for methods from [`std::fs::File`][std::fs::File]. @@ -65,7 +65,7 @@ impl File { let path = path.into(); match options.open(&path) { Ok(file) => Ok(File::from_parts(file, path)), - Err(source) => Err(Error::new(source, ErrorKind::OpenFile, path)), + Err(source) => Err(Error::build(source, ErrorKind::OpenFile, path)), } } @@ -114,7 +114,13 @@ impl File { .set_permissions(perm) .map_err(|source| self.error(source, ErrorKind::SetPermissions)) } +} +/// Methods added by fs-err that are not available on +/// [`std::fs::File`][std::fs::File]. +/// +/// [std::fs::File]: https://doc.rust-lang.org/stable/std/fs/struct.File.html +impl File { /// Creates a [`File`](struct.File.html) from a raw file and its path. pub fn from_parts

{} + + pub trait _ValueParserViaValueEnumSealed {} + impl _ValueParserViaValueEnumSealed for &_AutoValueParser {} + + pub trait _ValueParserViaFromStrSealed {} + impl _ValueParserViaFromStrSealed for _AutoValueParser + where + FromStr: std::str::FromStr + std::any::Any + Send + Sync + 'static, + ::Err: + Into>, + { + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn ensure_typed_applies_to_parse() { + fn parse(_: &str) -> Result { + Ok(10) + } + let cmd = crate::Command::new("cmd"); + let arg = None; + assert_eq!( + TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(), + 10 + ); + } +} diff --git a/vendor/clap-3.2.20/src/derive.rs b/vendor/clap-3.2.20/src/derive.rs new file mode 100644 index 000000000..b6ac04df6 --- /dev/null +++ b/vendor/clap-3.2.20/src/derive.rs @@ -0,0 +1,577 @@ +//! This module contains traits that are usable with the `#[derive(...)].` +//! macros in [`clap_derive`]. + +use crate::{ArgMatches, Command, Error, PossibleValue}; + +use std::ffi::OsString; + +/// Parse command-line arguments into `Self`. +/// +/// The primary one-stop-shop trait used to create an instance of a `clap` +/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back +/// into concrete instance of the user struct. +/// +/// This trait is primarily a convenience on top of [`FromArgMatches`] + +/// [`CommandFactory`] which uses those two underlying traits to build the two +/// fundamental functions `parse` which uses the `std::env::args_os` iterator, +/// and `parse_from` which allows the consumer to supply the iterator (along +/// with fallible options for each). +/// +/// See also [`Subcommand`] and [`Args`]. +/// +/// See the [derive reference](crate::_derive) for attributes and best practices. +/// +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] +/// +/// # Examples +/// +/// The following example creates a `Context` struct that would be used +/// throughout the application representing the normalized values coming from +/// the CLI. +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// /// My super CLI +/// #[derive(clap::Parser)] +/// #[clap(name = "demo")] +/// struct Context { +/// /// More verbose output +/// #[clap(long)] +/// verbose: bool, +/// /// An optional name +/// #[clap(short, long)] +/// name: Option, +/// } +/// ``` +/// +/// The equivalent [`Command`] struct + `From` implementation: +/// +/// ```rust +/// # use clap::{Command, Arg, ArgMatches, ArgAction}; +/// Command::new("demo") +/// .about("My super CLI") +/// .arg(Arg::new("verbose") +/// .long("verbose") +/// .action(ArgAction::SetTrue) +/// .help("More verbose output")) +/// .arg(Arg::new("name") +/// .long("name") +/// .short('n') +/// .help("An optional name") +/// .takes_value(true)); +/// +/// struct Context { +/// verbose: bool, +/// name: Option, +/// } +/// +/// impl From for Context { +/// fn from(m: ArgMatches) -> Self { +/// Context { +/// verbose: *m.get_one::("verbose").expect("defaulted_by_clap"), +/// name: m.get_one::("name").cloned(), +/// } +/// } +/// } +/// ``` +/// +pub trait Parser: FromArgMatches + CommandFactory + Sized { + /// Parse from `std::env::args_os()`, exit on error + fn parse() -> Self { + let mut matches = ::command().get_matches(); + let res = ::from_arg_matches_mut(&mut matches) + .map_err(format_error::); + match res { + Ok(s) => s, + Err(e) => { + // Since this is more of a development-time error, we aren't doing as fancy of a quit + // as `get_matches` + e.exit() + } + } + } + + /// Parse from `std::env::args_os()`, return Err on error. + fn try_parse() -> Result { + let mut matches = ::command().try_get_matches()?; + ::from_arg_matches_mut(&mut matches).map_err(format_error::) + } + + /// Parse from iterator, exit on error + fn parse_from(itr: I) -> Self + where + I: IntoIterator, + T: Into + Clone, + { + let mut matches = ::command().get_matches_from(itr); + let res = ::from_arg_matches_mut(&mut matches) + .map_err(format_error::); + match res { + Ok(s) => s, + Err(e) => { + // Since this is more of a development-time error, we aren't doing as fancy of a quit + // as `get_matches_from` + e.exit() + } + } + } + + /// Parse from iterator, return Err on error. + fn try_parse_from(itr: I) -> Result + where + I: IntoIterator, + T: Into + Clone, + { + let mut matches = ::command().try_get_matches_from(itr)?; + ::from_arg_matches_mut(&mut matches).map_err(format_error::) + } + + /// Update from iterator, exit on error + fn update_from(&mut self, itr: I) + where + I: IntoIterator, + T: Into + Clone, + { + let mut matches = ::command_for_update().get_matches_from(itr); + let res = ::update_from_arg_matches_mut(self, &mut matches) + .map_err(format_error::); + if let Err(e) = res { + // Since this is more of a development-time error, we aren't doing as fancy of a quit + // as `get_matches_from` + e.exit() + } + } + + /// Update from iterator, return Err on error. + fn try_update_from(&mut self, itr: I) -> Result<(), Error> + where + I: IntoIterator, + T: Into + Clone, + { + let mut matches = + ::command_for_update().try_get_matches_from(itr)?; + ::update_from_arg_matches_mut(self, &mut matches) + .map_err(format_error::) + } + + /// Deprecated, `StructOpt::clap` replaced with [`CommandFactory::command`] (derive as part of + /// [`Parser`]) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::clap` is replaced with `CommandFactory::command` (derived as part of `Parser`)" + ) + )] + #[doc(hidden)] + fn clap<'help>() -> Command<'help> { + ::command() + } + + /// Deprecated, `StructOpt::from_clap` replaced with [`FromArgMatches::from_arg_matches_mut`] (derive as part of + /// [`Parser`]) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::from_clap` is replaced with `FromArgMatches::from_arg_matches_mut` (derived as part of `Parser`)" + ) + )] + #[doc(hidden)] + fn from_clap(matches: &ArgMatches) -> Self { + ::from_arg_matches(matches).unwrap() + } + + /// Deprecated, `StructOpt::from_args` replaced with `Parser::parse` (note the change in derives) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::from_args` is replaced with `Parser::parse` (note the change in derives)" + ) + )] + #[doc(hidden)] + fn from_args() -> Self { + Self::parse() + } + + /// Deprecated, `StructOpt::from_args_safe` replaced with `Parser::try_parse` (note the change in derives) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::from_args_safe` is replaced with `Parser::try_parse` (note the change in derives)" + ) + )] + #[doc(hidden)] + fn from_args_safe() -> Result { + Self::try_parse() + } + + /// Deprecated, `StructOpt::from_iter` replaced with `Parser::parse_from` (note the change in derives) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::from_iter` is replaced with `Parser::parse_from` (note the change in derives)" + ) + )] + #[doc(hidden)] + fn from_iter(itr: I) -> Self + where + I: IntoIterator, + T: Into + Clone, + { + Self::parse_from(itr) + } + + /// Deprecated, `StructOpt::from_iter_safe` replaced with `Parser::try_parse_from` (note the + /// change in derives) + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "`StructOpt::from_iter_safe` is replaced with `Parser::try_parse_from` (note the change in derives)" + ) + )] + #[doc(hidden)] + fn from_iter_safe(itr: I) -> Result + where + I: IntoIterator, + T: Into + Clone, + { + Self::try_parse_from(itr) + } +} + +/// Create a [`Command`] relevant for a user-defined container. +/// +/// Derived as part of [`Parser`]. +pub trait CommandFactory: Sized { + /// Build a [`Command`] that can instantiate `Self`. + /// + /// See [`FromArgMatches::from_arg_matches_mut`] for instantiating `Self`. + fn command<'help>() -> Command<'help> { + #[allow(deprecated)] + Self::into_app() + } + /// Deprecated, replaced with `CommandFactory::command` + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `CommandFactory::command") + )] + fn into_app<'help>() -> Command<'help>; + /// Build a [`Command`] that can update `self`. + /// + /// See [`FromArgMatches::update_from_arg_matches_mut`] for updating `self`. + fn command_for_update<'help>() -> Command<'help> { + #[allow(deprecated)] + Self::into_app_for_update() + } + /// Deprecated, replaced with `CommandFactory::command_for_update` + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.1.0", + note = "Replaced with `CommandFactory::command_for_update" + ) + )] + fn into_app_for_update<'help>() -> Command<'help>; +} + +/// Converts an instance of [`ArgMatches`] to a user-defined container. +/// +/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`]. +pub trait FromArgMatches: Sized { + /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. + /// + /// Motivation: If our application had two CLI options, `--name + /// ` and the flag `--debug`, we may create a struct as follows: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// struct Context { + /// name: String, + /// debug: bool + /// } + /// ``` + /// + /// We then need to convert the `ArgMatches` that `clap` generated into our struct. + /// `from_arg_matches` serves as the equivalent of: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// # use clap::ArgMatches; + /// # struct Context { + /// # name: String, + /// # debug: bool + /// # } + /// impl From for Context { + /// fn from(m: ArgMatches) -> Self { + /// Context { + /// name: m.get_one::("name").unwrap().clone(), + /// debug: *m.get_one::("debug").expect("defaulted by clap"), + /// } + /// } + /// } + /// ``` + fn from_arg_matches(matches: &ArgMatches) -> Result; + + /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. + /// + /// Motivation: If our application had two CLI options, `--name + /// ` and the flag `--debug`, we may create a struct as follows: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// struct Context { + /// name: String, + /// debug: bool + /// } + /// ``` + /// + /// We then need to convert the `ArgMatches` that `clap` generated into our struct. + /// `from_arg_matches_mut` serves as the equivalent of: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// # use clap::ArgMatches; + /// # struct Context { + /// # name: String, + /// # debug: bool + /// # } + /// impl From for Context { + /// fn from(m: ArgMatches) -> Self { + /// Context { + /// name: m.get_one::("name").unwrap().to_string(), + /// debug: *m.get_one::("debug").expect("defaulted by clap"), + /// } + /// } + /// } + /// ``` + fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { + Self::from_arg_matches(matches) + } + + /// Assign values from `ArgMatches` to `self`. + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>; + + /// Assign values from `ArgMatches` to `self`. + fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { + self.update_from_arg_matches(matches) + } +} + +/// Parse a set of arguments into a user-defined container. +/// +/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`. +/// with: +/// - `#[clap(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl +/// `Args`. +/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. +/// +/// See the [derive reference](crate::_derive) for attributes and best practices. +/// +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(flatten)] +/// logging: LogArgs, +/// } +/// +/// #[derive(clap::Args)] +/// struct LogArgs { +/// #[clap(long, short = 'v', parse(from_occurrences))] +/// verbose: i8, +/// } +/// ``` +pub trait Args: FromArgMatches + Sized { + /// Append to [`Command`] so it can instantiate `Self`. + /// + /// See also [`CommandFactory`]. + fn augment_args(cmd: Command<'_>) -> Command<'_>; + /// Append to [`Command`] so it can update `self`. + /// + /// This is used to implement `#[clap(flatten)]` + /// + /// See also [`CommandFactory`]. + fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>; +} + +/// Parse a sub-command into a user-defined enum. +/// +/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`. +/// with: +/// - `#[clap(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum +/// variants that impl `Subcommand`. +/// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl +/// `Subcommand`. +/// +/// See the [derive reference](crate::_derive) for attributes and best practices. +/// +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(subcommand)] +/// action: Action, +/// } +/// +/// #[derive(clap::Subcommand)] +/// enum Action { +/// Add, +/// Remove, +/// } +/// ``` +pub trait Subcommand: FromArgMatches + Sized { + /// Append to [`Command`] so it can instantiate `Self`. + /// + /// See also [`CommandFactory`]. + fn augment_subcommands(cmd: Command<'_>) -> Command<'_>; + /// Append to [`Command`] so it can update `self`. + /// + /// This is used to implement `#[clap(flatten)]` + /// + /// See also [`CommandFactory`]. + fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>; + /// Test whether `Self` can parse a specific subcommand + fn has_subcommand(name: &str) -> bool; +} + +/// Parse arguments into enums. +/// +/// When deriving [`Parser`], a field whose type implements `ValueEnum` can have the attribute +/// `#[clap(value_enum)]` which will +/// - Call [`Arg::possible_values`][crate::Arg::possible_values] +/// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`. +/// +/// See the [derive reference](crate::_derive) for attributes and best practices. +/// +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(value_enum)] +/// level: Level, +/// } +/// +/// #[derive(clap::ValueEnum, Clone)] +/// enum Level { +/// Debug, +/// Info, +/// Warning, +/// Error, +/// } +/// ``` +pub trait ValueEnum: Sized + Clone { + /// All possible argument values, in display order. + fn value_variants<'a>() -> &'a [Self]; + + /// Parse an argument into `Self`. + fn from_str(input: &str, ignore_case: bool) -> Result { + Self::value_variants() + .iter() + .find(|v| { + v.to_possible_value() + .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value") + .matches(input, ignore_case) + }) + .cloned() + .ok_or_else(|| format!("Invalid variant: {}", input)) + } + + /// The canonical argument value. + /// + /// The value is `None` for skipped variants. + fn to_possible_value<'a>(&self) -> Option>; +} + +impl Parser for Box { + fn parse() -> Self { + Box::new(::parse()) + } + + fn try_parse() -> Result { + ::try_parse().map(Box::new) + } + + fn parse_from(itr: I) -> Self + where + I: IntoIterator, + It: Into + Clone, + { + Box::new(::parse_from(itr)) + } + + fn try_parse_from(itr: I) -> Result + where + I: IntoIterator, + It: Into + Clone, + { + ::try_parse_from(itr).map(Box::new) + } +} + +#[allow(deprecated)] +impl CommandFactory for Box { + fn into_app<'help>() -> Command<'help> { + ::into_app() + } + fn into_app_for_update<'help>() -> Command<'help> { + ::into_app_for_update() + } +} + +impl FromArgMatches for Box { + fn from_arg_matches(matches: &ArgMatches) -> Result { + ::from_arg_matches(matches).map(Box::new) + } + fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { + ::from_arg_matches_mut(matches).map(Box::new) + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + ::update_from_arg_matches(self, matches) + } + fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { + ::update_from_arg_matches_mut(self, matches) + } +} + +impl Args for Box { + fn augment_args(cmd: Command<'_>) -> Command<'_> { + ::augment_args(cmd) + } + fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> { + ::augment_args_for_update(cmd) + } +} + +impl Subcommand for Box { + fn augment_subcommands(cmd: Command<'_>) -> Command<'_> { + ::augment_subcommands(cmd) + } + fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> { + ::augment_subcommands_for_update(cmd) + } + fn has_subcommand(name: &str) -> bool { + ::has_subcommand(name) + } +} + +fn format_error(err: crate::Error) -> crate::Error { + let mut cmd = I::command(); + err.format(&mut cmd) +} diff --git a/vendor/clap-3.2.20/src/error/context.rs b/vendor/clap-3.2.20/src/error/context.rs new file mode 100644 index 000000000..985cd4d70 --- /dev/null +++ b/vendor/clap-3.2.20/src/error/context.rs @@ -0,0 +1,55 @@ +/// Semantics for a piece of error information +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ContextKind { + /// The cause of the error + InvalidSubcommand, + /// The cause of the error + InvalidArg, + /// Existing arguments + PriorArg, + /// Accepted values + ValidValue, + /// Rejected values + InvalidValue, + /// Number of values present + ActualNumValues, + /// Number of allowed values + ExpectedNumValues, + /// Minimum number of allowed values + MinValues, + /// Number of occurrences present + ActualNumOccurrences, + /// Maximum number of allowed occurrences + MaxOccurrences, + /// Potential fix for the user + SuggestedCommand, + /// Potential fix for the user + SuggestedSubcommand, + /// Potential fix for the user + SuggestedArg, + /// Potential fix for the user + SuggestedValue, + /// Trailing argument + TrailingArg, + /// A usage string + Usage, + /// An opaque message to the user + Custom, +} + +/// A piece of error information +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ContextValue { + /// [`ContextKind`] is self-sufficient, no additional information needed + None, + /// A single value + Bool(bool), + /// A single value + String(String), + /// Many values + Strings(Vec), + /// A single value + Number(isize), +} diff --git a/vendor/clap-3.2.20/src/error/kind.rs b/vendor/clap-3.2.20/src/error/kind.rs new file mode 100644 index 000000000..4c3dc48b0 --- /dev/null +++ b/vendor/clap-3.2.20/src/error/kind.rs @@ -0,0 +1,440 @@ +/// Command line argument parser kind of error +#[derive(Debug, Copy, Clone, PartialEq)] +#[non_exhaustive] +pub enum ErrorKind { + /// Occurs when an [`Arg`][crate::Arg] has a set of possible values, + /// and the user provides a value which isn't in that set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("speed") + /// .value_parser(["fast", "slow"])) + /// .try_get_matches_from(vec!["prog", "other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue); + /// ``` + InvalidValue, + + /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(arg!(--flag "some flag")) + /// .try_get_matches_from(vec!["prog", "--other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + UnknownArgument, + + /// Occurs when the user provides an unrecognized [`Subcommand`] which meets the threshold for + /// being similar enough to an existing subcommand. + /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, + /// the more general [`UnknownArgument`] error is returned. + /// + /// # Examples + /// + #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] + #[cfg_attr(feature = "suggestions", doc = " ```")] + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog", "confi"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`UnknownArgument`]: ErrorKind::UnknownArgument + InvalidSubcommand, + + /// Occurs when the user provides an unrecognized [`Subcommand`] which either + /// doesn't meet the threshold for being similar enough to an existing subcommand, + /// or the 'suggestions' feature is disabled. + /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. + /// + /// This error typically happens when passing additional subcommand names to the `help` + /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog", "help", "nothing"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`InvalidSubcommand`]: ErrorKind::InvalidSubcommand + /// [`UnknownArgument`]: ErrorKind::UnknownArgument + UnrecognizedSubcommand, + + /// Occurs when the user provides an empty value for an option that does not allow empty + /// values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("color") + /// .takes_value(true) + /// .forbid_empty_values(true) + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--color="]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); + /// ``` + EmptyValue, + + /// Occurs when the user doesn't use equals for an option that requires equal + /// sign to provide values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("color") + /// .takes_value(true) + /// .require_equals(true) + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--color", "red"]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); + /// ``` + NoEquals, + + /// Occurs when the user provides a value for an argument with a custom validation and the + /// value fails that validation. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// fn is_numeric(val: &str) -> Result<(), String> { + /// match val.parse::() { + /// Ok(..) => Ok(()), + /// Err(..) => Err(String::from("Value wasn't a number!")), + /// } + /// } + /// + /// let result = Command::new("prog") + /// .arg(Arg::new("num") + /// .validator(is_numeric)) + /// .try_get_matches_from(vec!["prog", "NotANumber"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation); + /// ``` + ValueValidation, + + /// Occurs when a user provides more values for an argument than were defined by setting + /// [`Arg::max_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("arg") + /// .max_values(2)) + /// .try_get_matches_from(vec!["prog", "too", "many", "values"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues); + /// ``` + /// [`Arg::max_values`]: crate::Arg::max_values() + TooManyValues, + + /// Occurs when the user provides fewer values for an argument than were defined by setting + /// [`Arg::min_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("some_opt") + /// .long("opt") + /// .min_values(3)) + /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues); + /// ``` + /// [`Arg::min_values`]: crate::Arg::min_values() + TooFewValues, + + /// Occurs when a user provides more occurrences for an argument than were defined by setting + /// [`Arg::max_occurrences`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("verbosity") + /// .short('v') + /// .max_occurrences(2)) + /// .try_get_matches_from(vec!["prog", "-vvv"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyOccurrences); + /// ``` + /// [`Arg::max_occurrences`]: crate::Arg::max_occurrences() + TooManyOccurrences, + + /// Occurs when the user provides a different number of values for an argument than what's + /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by + /// [`Arg::value_names`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("some_opt") + /// .long("opt") + /// .takes_value(true) + /// .number_of_values(2)) + /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); + /// ``` + /// + /// [`Arg::number_of_values`]: crate::Arg::number_of_values() + /// [`Arg::value_names`]: crate::Arg::value_names() + WrongNumberOfValues, + + /// Occurs when the user provides two values which conflict with each other and can't be used + /// together. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .conflicts_with("color")) + /// .arg(Arg::new("color") + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--debug", "--color"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + ArgumentConflict, + + /// Occurs when the user does not provide one or more required arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .required(true)) + /// .try_get_matches_from(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + MissingRequiredArgument, + + /// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]), + /// but the user does not provide one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let err = Command::new("prog") + /// .subcommand_required(true) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`Command::subcommand_required`]: crate::Command::subcommand_required + MissingSubcommand, + + /// Occurs when the user provides multiple values to an argument which doesn't allow that. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .multiple_occurrences(false)) + /// .try_get_matches_from(vec!["prog", "--debug", "--debug"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage); + /// ``` + UnexpectedMultipleUsage, + + /// Occurs when the user provides a value containing invalid UTF-8. + /// + /// To allow arbitrary data + /// - Set [`Arg::allow_invalid_utf8`] for argument values + /// - Set [`Command::allow_invalid_utf8_for_external_subcommands`] for external-subcommand + /// values + /// + /// # Platform Specific + /// + /// Non-Windows platforms only (such as Linux, Unix, OSX, etc.) + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, Arg, ErrorKind}; + /// # use std::os::unix::ffi::OsStringExt; + /// # use std::ffi::OsString; + /// let result = Command::new("prog") + /// .arg(Arg::new("utf8") + /// .short('u') + /// .takes_value(true)) + /// .try_get_matches_from(vec![OsString::from("myprog"), + /// OsString::from("-u"), + /// OsString::from_vec(vec![0xE9])]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8); + /// ``` + /// + /// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8 + /// [`Command::allow_invalid_utf8_for_external_subcommands`]: crate::Command::allow_invalid_utf8_for_external_subcommands + InvalidUtf8, + + /// Not a true "error" as it means `--help` or similar was used. + /// The help message will be sent to `stdout`. + /// + /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will + /// be sent to `stderr` instead of `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .try_get_matches_from(vec!["prog", "--help"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp); + /// ``` + DisplayHelp, + + /// Occurs when either an argument or a [`Subcommand`] is required, as defined by + /// [`Command::arg_required_else_help`] , but the user did not provide + /// one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .arg_required_else_help(true) + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help + DisplayHelpOnMissingArgumentOrSubcommand, + + /// Not a true "error" as it means `--version` or similar was used. + /// The message will be sent to `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .version("3.0") + /// .try_get_matches_from(vec!["prog", "--version"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion); + /// ``` + DisplayVersion, + + /// Occurs when using the [`ArgMatches::value_of_t`] and friends to convert an argument value + /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument + /// with name `config` to be converted, but `config` wasn't used by the user. + /// + /// [`ArgMatches::value_of_t`]: crate::ArgMatches::value_of_t() + ArgumentNotFound, + + /// Represents an [I/O error]. + /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. + /// + /// [I/O error]: std::io::Error + Io, + + /// Represents a [Format error] (which is a part of [`Display`]). + /// Typically caused by writing to `stderr` or `stdout`. + /// + /// [`Display`]: std::fmt::Display + /// [Format error]: std::fmt::Error + Format, +} + +impl ErrorKind { + /// End-user description of the error case, where relevant + pub fn as_str(self) -> Option<&'static str> { + match self { + Self::InvalidValue => Some("One of the values isn't valid for an argument"), + Self::UnknownArgument => { + Some("Found an argument which wasn't expected or isn't valid in this context") + } + Self::InvalidSubcommand => Some("A subcommand wasn't recognized"), + Self::UnrecognizedSubcommand => Some("A subcommand wasn't recognized"), + Self::EmptyValue => Some("An argument requires a value but none was supplied"), + Self::NoEquals => Some("Equal is needed when assigning values to one of the arguments"), + Self::ValueValidation => Some("Invalid value for one of the arguments"), + Self::TooManyValues => Some("An argument received an unexpected value"), + Self::TooFewValues => Some("An argument requires more values"), + Self::TooManyOccurrences => Some("An argument occurred too many times"), + Self::WrongNumberOfValues => Some("An argument received too many or too few values"), + Self::ArgumentConflict => { + Some("An argument cannot be used with one or more of the other specified arguments") + } + Self::MissingRequiredArgument => { + Some("One or more required arguments were not provided") + } + Self::MissingSubcommand => Some("A subcommand is required but one was not provided"), + Self::UnexpectedMultipleUsage => { + Some("An argument was provided more than once but cannot be used multiple times") + } + Self::InvalidUtf8 => Some("Invalid UTF-8 was detected in one or more arguments"), + Self::DisplayHelp => None, + Self::DisplayHelpOnMissingArgumentOrSubcommand => None, + Self::DisplayVersion => None, + Self::ArgumentNotFound => Some("An argument wasn't found"), + Self::Io => None, + Self::Format => None, + } + } +} + +impl std::fmt::Display for ErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.as_str().unwrap_or_default().fmt(f) + } +} diff --git a/vendor/clap-3.2.20/src/error/mod.rs b/vendor/clap-3.2.20/src/error/mod.rs new file mode 100644 index 000000000..fbd2b30a8 --- /dev/null +++ b/vendor/clap-3.2.20/src/error/mod.rs @@ -0,0 +1,1153 @@ +//! Error reporting +#![allow(deprecated)] + +// Std +use std::{ + borrow::Cow, + convert::From, + error, + fmt::{self, Debug, Display, Formatter}, + io::{self, BufRead}, + result::Result as StdResult, +}; + +// Internal +use crate::output::fmt::Colorizer; +use crate::output::fmt::Stream; +use crate::parser::features::suggestions; +use crate::util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}; +use crate::AppSettings; +use crate::Command; + +mod context; +mod kind; + +pub use context::ContextKind; +pub use context::ContextValue; +pub use kind::ErrorKind; + +/// Short hand for [`Result`] type +/// +/// [`Result`]: std::result::Result +pub type Result = StdResult; + +/// Command Line Argument Parser Error +/// +/// See [`Command::error`] to create an error. +/// +/// [`Command::error`]: crate::Command::error +#[derive(Debug)] +pub struct Error { + inner: Box, + /// Deprecated, replaced with [`Error::kind()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Error::kind()`") + )] + pub kind: ErrorKind, + /// Deprecated, replaced with [`Error::context()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `Error::context()`") + )] + pub info: Vec, +} + +#[derive(Debug)] +struct ErrorInner { + kind: ErrorKind, + context: Vec<(ContextKind, ContextValue)>, + message: Option, + source: Option>, + help_flag: Option<&'static str>, + color_when: ColorChoice, + wait_on_exit: bool, + backtrace: Option, +} + +impl Error { + /// Create an unformatted error + /// + /// This is for you need to pass the error up to + /// a place that has access to the `Command` at which point you can call [`Error::format`]. + /// + /// Prefer [`Command::error`] for generating errors. + /// + /// [`Command::error`]: crate::Command::error + pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { + Self::new(kind).set_message(message.to_string()) + } + + /// Format the existing message with the Command's context + #[must_use] + pub fn format(mut self, cmd: &mut Command) -> Self { + cmd._build_self(); + let usage = cmd.render_usage(); + if let Some(message) = self.inner.message.as_mut() { + message.format(cmd, usage); + } + self.with_cmd(cmd) + } + + /// Type of error for programmatic processing + pub fn kind(&self) -> ErrorKind { + self.inner.kind + } + + /// Additional information to further qualify the error + pub fn context(&self) -> impl Iterator { + self.inner.context.iter().map(|(k, v)| (*k, v)) + } + + /// Should the message be written to `stdout` or not? + #[inline] + pub fn use_stderr(&self) -> bool { + self.stream() == Stream::Stderr + } + + pub(crate) fn stream(&self) -> Stream { + match self.kind() { + ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => Stream::Stdout, + _ => Stream::Stderr, + } + } + + /// Prints the error and exits. + /// + /// Depending on the error kind, this either prints to `stderr` and exits with a status of `2` + /// or prints to `stdout` and exits with a status of `0`. + pub fn exit(&self) -> ! { + if self.use_stderr() { + // Swallow broken pipe errors + let _ = self.print(); + + if self.inner.wait_on_exit { + wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); + let mut s = String::new(); + let i = io::stdin(); + i.lock().read_line(&mut s).unwrap(); + } + + safe_exit(USAGE_CODE); + } + + // Swallow broken pipe errors + let _ = self.print(); + safe_exit(SUCCESS_CODE) + } + + /// Prints formatted and colored error to `stdout` or `stderr` according to its error kind + /// + /// # Example + /// ```no_run + /// use clap::Command; + /// + /// match Command::new("Command").try_get_matches() { + /// Ok(matches) => { + /// // do_something + /// }, + /// Err(err) => { + /// err.print().expect("Error writing Error"); + /// // do_something + /// }, + /// }; + /// ``` + pub fn print(&self) -> io::Result<()> { + self.formatted().print() + } + + /// Deprecated, replaced with [`Command::error`] + /// + /// [`Command::error`]: crate::Command::error + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::error`") + )] + #[doc(hidden)] + pub fn with_description(description: String, kind: ErrorKind) -> Self { + Error::raw(kind, description) + } + + fn new(kind: ErrorKind) -> Self { + Self { + inner: Box::new(ErrorInner { + kind, + context: Vec::new(), + message: None, + source: None, + help_flag: None, + color_when: ColorChoice::Never, + wait_on_exit: false, + backtrace: Backtrace::new(), + }), + kind, + info: vec![], + } + } + + #[inline(never)] + fn for_app(kind: ErrorKind, cmd: &Command, colorizer: Colorizer, info: Vec) -> Self { + Self::new(kind) + .set_message(colorizer) + .with_cmd(cmd) + .set_info(info) + } + + pub(crate) fn with_cmd(self, cmd: &Command) -> Self { + self.set_wait_on_exit(cmd.is_set(AppSettings::WaitOnError)) + .set_color(cmd.get_color()) + .set_help_flag(get_help_flag(cmd)) + } + + pub(crate) fn set_message(mut self, message: impl Into) -> Self { + self.inner.message = Some(message.into()); + self + } + + pub(crate) fn set_info(mut self, info: Vec) -> Self { + self.info = info; + self + } + + pub(crate) fn set_source(mut self, source: Box) -> Self { + self.inner.source = Some(source); + self + } + + pub(crate) fn set_color(mut self, color_when: ColorChoice) -> Self { + self.inner.color_when = color_when; + self + } + + pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self { + self.inner.help_flag = help_flag; + self + } + + pub(crate) fn set_wait_on_exit(mut self, yes: bool) -> Self { + self.inner.wait_on_exit = yes; + self + } + + /// Does not verify if `ContextKind` is already present + #[inline(never)] + pub(crate) fn insert_context_unchecked( + mut self, + kind: ContextKind, + value: ContextValue, + ) -> Self { + self.inner.context.push((kind, value)); + self + } + + /// Does not verify if `ContextKind` is already present + #[inline(never)] + pub(crate) fn extend_context_unchecked( + mut self, + context: [(ContextKind, ContextValue); N], + ) -> Self { + self.inner.context.extend(context); + self + } + + #[inline(never)] + fn get_context(&self, kind: ContextKind) -> Option<&ContextValue> { + self.inner + .context + .iter() + .find_map(|(k, v)| (*k == kind).then(|| v)) + } + + pub(crate) fn display_help(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app(ErrorKind::DisplayHelp, cmd, colorizer, vec![]) + } + + pub(crate) fn display_help_error(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app( + ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, + cmd, + colorizer, + vec![], + ) + } + + pub(crate) fn display_version(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app(ErrorKind::DisplayVersion, cmd, colorizer, vec![]) + } + + pub(crate) fn argument_conflict( + cmd: &Command, + arg: String, + mut others: Vec, + usage: String, + ) -> Self { + let info = others.clone(); + let others = match others.len() { + 0 => ContextValue::None, + 1 => ContextValue::String(others.pop().unwrap()), + _ => ContextValue::Strings(others), + }; + Self::new(ErrorKind::ArgumentConflict) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::PriorArg, others), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn empty_value(cmd: &Command, good_vals: &[&str], arg: String) -> Self { + let info = vec![arg.clone()]; + let mut err = Self::new(ErrorKind::EmptyValue) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]); + if !good_vals.is_empty() { + err = err.insert_context_unchecked( + ContextKind::ValidValue, + ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), + ); + } + err + } + + pub(crate) fn no_equals(cmd: &Command, arg: String, usage: String) -> Self { + let info = vec![arg.clone()]; + Self::new(ErrorKind::NoEquals) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn invalid_value( + cmd: &Command, + bad_val: String, + good_vals: &[&str], + arg: String, + ) -> Self { + let mut info = vec![arg.clone(), bad_val.clone()]; + info.extend(good_vals.iter().map(|s| (*s).to_owned())); + + let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); + let mut err = Self::new(ErrorKind::InvalidValue) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::InvalidValue, ContextValue::String(bad_val)), + ( + ContextKind::ValidValue, + ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), + ), + ]); + if let Some(suggestion) = suggestion { + err = err.insert_context_unchecked( + ContextKind::SuggestedValue, + ContextValue::String(suggestion), + ); + } + err + } + + pub(crate) fn invalid_subcommand( + cmd: &Command, + subcmd: String, + did_you_mean: String, + name: String, + usage: String, + ) -> Self { + let info = vec![subcmd.clone()]; + let suggestion = format!("{} -- {}", name, subcmd); + Self::new(ErrorKind::InvalidSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), + ( + ContextKind::SuggestedSubcommand, + ContextValue::String(did_you_mean), + ), + ( + ContextKind::SuggestedCommand, + ContextValue::String(suggestion), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unrecognized_subcommand(cmd: &Command, subcmd: String, usage: String) -> Self { + let info = vec![subcmd.clone()]; + Self::new(ErrorKind::UnrecognizedSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn missing_required_argument( + cmd: &Command, + required: Vec, + usage: String, + ) -> Self { + let info = required.clone(); + Self::new(ErrorKind::MissingRequiredArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::Strings(required)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn missing_subcommand(cmd: &Command, name: String, usage: String) -> Self { + let info = vec![]; + Self::new(ErrorKind::MissingSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(name)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn invalid_utf8(cmd: &Command, usage: String) -> Self { + let info = vec![]; + Self::new(ErrorKind::InvalidUtf8) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([(ContextKind::Usage, ContextValue::String(usage))]) + } + + pub(crate) fn too_many_occurrences( + cmd: &Command, + arg: String, + max_occurs: usize, + curr_occurs: usize, + usage: String, + ) -> Self { + let info = vec![arg.clone(), curr_occurs.to_string(), max_occurs.to_string()]; + Self::new(ErrorKind::TooManyOccurrences) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + ( + ContextKind::MaxOccurrences, + ContextValue::Number(max_occurs as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_occurs as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn too_many_values(cmd: &Command, val: String, arg: String, usage: String) -> Self { + let info = vec![arg.clone(), val.clone()]; + Self::new(ErrorKind::TooManyValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::InvalidValue, ContextValue::String(val)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn too_few_values( + cmd: &Command, + arg: String, + min_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let info = vec![arg.clone(), curr_vals.to_string(), min_vals.to_string()]; + Self::new(ErrorKind::TooFewValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + ( + ContextKind::MinValues, + ContextValue::Number(min_vals as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_vals as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn value_validation( + arg: String, + val: String, + err: Box, + ) -> Self { + let info = vec![arg.clone(), val.to_string(), err.to_string()]; + Self::new(ErrorKind::ValueValidation) + .set_info(info) + .set_source(err) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::InvalidValue, ContextValue::String(val)), + ]) + } + + pub(crate) fn wrong_number_of_values( + cmd: &Command, + arg: String, + num_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let info = vec![arg.clone(), curr_vals.to_string(), num_vals.to_string()]; + Self::new(ErrorKind::WrongNumberOfValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + ( + ContextKind::ExpectedNumValues, + ContextValue::Number(num_vals as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_vals as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unexpected_multiple_usage(cmd: &Command, arg: String, usage: String) -> Self { + let info = vec![arg.clone()]; + Self::new(ErrorKind::UnexpectedMultipleUsage) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unknown_argument( + cmd: &Command, + arg: String, + did_you_mean: Option<(String, Option)>, + usage: String, + ) -> Self { + let info = vec![arg.clone()]; + let mut err = Self::new(ErrorKind::UnknownArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::Usage, ContextValue::String(usage)), + ]); + if let Some((flag, sub)) = did_you_mean { + err = err.insert_context_unchecked( + ContextKind::SuggestedArg, + ContextValue::String(format!("--{}", flag)), + ); + if let Some(sub) = sub { + err = err.insert_context_unchecked( + ContextKind::SuggestedSubcommand, + ContextValue::String(sub), + ); + } + } + err + } + + pub(crate) fn unnecessary_double_dash(cmd: &Command, arg: String, usage: String) -> Self { + let info = vec![arg.clone()]; + Self::new(ErrorKind::UnknownArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::TrailingArg, ContextValue::Bool(true)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn argument_not_found_auto(arg: String) -> Self { + let info = vec![arg.clone()]; + Self::new(ErrorKind::ArgumentNotFound) + .set_info(info) + .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]) + } + + fn formatted(&self) -> Cow<'_, Colorizer> { + if let Some(message) = self.inner.message.as_ref() { + message.formatted() + } else { + let mut c = Colorizer::new(self.stream(), self.inner.color_when); + + start_error(&mut c); + + if !self.write_dynamic_context(&mut c) { + if let Some(msg) = self.kind().as_str() { + c.none(msg.to_owned()); + } else if let Some(source) = self.inner.source.as_ref() { + c.none(source.to_string()); + } else { + c.none("Unknown cause"); + } + } + + let usage = self.get_context(ContextKind::Usage); + if let Some(ContextValue::String(usage)) = usage { + put_usage(&mut c, usage); + } + + try_help(&mut c, self.inner.help_flag); + + Cow::Owned(c) + } + } + + #[must_use] + fn write_dynamic_context(&self, c: &mut Colorizer) -> bool { + match self.kind() { + ErrorKind::ArgumentConflict => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let prior_arg = self.get_context(ContextKind::PriorArg); + if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) = + (invalid_arg, prior_arg) + { + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' cannot be used with"); + + match prior_arg { + ContextValue::Strings(values) => { + c.none(":"); + for v in values { + c.none("\n "); + c.warning(&**v); + } + } + ContextValue::String(value) => { + c.none(" '"); + c.warning(value); + c.none("'"); + } + _ => { + c.none(" one or more of the other specified arguments"); + } + } + true + } else { + false + } + } + ErrorKind::EmptyValue => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires a value but none was supplied"); + + let possible_values = self.get_context(ContextKind::ValidValue); + if let Some(ContextValue::Strings(possible_values)) = possible_values { + c.none("\n\t[possible values: "); + if let Some((last, elements)) = possible_values.split_last() { + for v in elements { + c.good(escape(v)); + c.none(", "); + } + c.good(escape(last)); + } + c.none("]"); + } + true + } else { + false + } + } + ErrorKind::NoEquals => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("Equal sign is needed when assigning values to '"); + c.warning(invalid_arg); + c.none("'."); + true + } else { + false + } + } + ErrorKind::InvalidValue => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none(quote(invalid_value)); + c.none(" isn't a valid value for '"); + c.warning(invalid_arg); + c.none("'"); + + let possible_values = self.get_context(ContextKind::ValidValue); + if let Some(ContextValue::Strings(possible_values)) = possible_values { + c.none("\n\t[possible values: "); + if let Some((last, elements)) = possible_values.split_last() { + for v in elements { + c.good(escape(v)); + c.none(", "); + } + c.good(escape(last)); + } + c.none("]"); + } + + let suggestion = self.get_context(ContextKind::SuggestedValue); + if let Some(ContextValue::String(suggestion)) = suggestion { + c.none("\n\n\tDid you mean "); + c.good(quote(suggestion)); + c.none("?"); + } + true + } else { + false + } + } + ErrorKind::InvalidSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("The subcommand '"); + c.warning(invalid_sub); + c.none("' wasn't recognized"); + + let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); + if let Some(ContextValue::String(valid_sub)) = valid_sub { + c.none("\n\n\tDid you mean "); + c.good(valid_sub); + c.none("?"); + } + + let suggestion = self.get_context(ContextKind::SuggestedCommand); + if let Some(ContextValue::String(suggestion)) = suggestion { + c.none( + "\n\nIf you believe you received this message in error, try re-running with '", + ); + c.good(suggestion); + c.none("'"); + } + true + } else { + false + } + } + ErrorKind::UnrecognizedSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("The subcommand '"); + c.warning(invalid_sub); + c.none("' wasn't recognized"); + true + } else { + false + } + } + ErrorKind::MissingRequiredArgument => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg { + c.none("The following required arguments were not provided:"); + for v in invalid_arg { + c.none("\n "); + c.good(&**v); + } + true + } else { + false + } + } + ErrorKind::MissingSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("'"); + c.warning(invalid_sub); + c.none("' requires a subcommand but one was not provided"); + true + } else { + false + } + } + ErrorKind::InvalidUtf8 => false, + ErrorKind::TooManyOccurrences => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_occurs = self.get_context(ContextKind::ActualNumOccurrences); + let max_occurs = self.get_context(ContextKind::MaxOccurrences); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_occurs)), + Some(ContextValue::Number(max_occurs)), + ) = (invalid_arg, actual_num_occurs, max_occurs) + { + let were_provided = Error::singular_or_plural(*actual_num_occurs as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' allows at most "); + c.warning(max_occurs.to_string()); + c.none(" occurrences but "); + c.warning(actual_num_occurs.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::TooManyValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none("The value '"); + c.warning(invalid_value); + c.none("' was provided to '"); + c.warning(invalid_arg); + c.none("' but it wasn't expecting any more values"); + true + } else { + false + } + } + ErrorKind::TooFewValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_values = self.get_context(ContextKind::ActualNumValues); + let min_values = self.get_context(ContextKind::MinValues); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_values)), + Some(ContextValue::Number(min_values)), + ) = (invalid_arg, actual_num_values, min_values) + { + let were_provided = Error::singular_or_plural(*actual_num_values as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires at least "); + c.warning(min_values.to_string()); + c.none(" values but only "); + c.warning(actual_num_values.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::ValueValidation => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none("Invalid value "); + c.warning(quote(invalid_value)); + c.none(" for '"); + c.warning(invalid_arg); + if let Some(source) = self.inner.source.as_deref() { + c.none("': "); + c.none(source.to_string()); + } else { + c.none("'"); + } + true + } else { + false + } + } + ErrorKind::WrongNumberOfValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_values = self.get_context(ContextKind::ActualNumValues); + let num_values = self.get_context(ContextKind::ExpectedNumValues); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_values)), + Some(ContextValue::Number(num_values)), + ) = (invalid_arg, actual_num_values, num_values) + { + let were_provided = Error::singular_or_plural(*actual_num_values as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires "); + c.warning(num_values.to_string()); + c.none(" values, but "); + c.warning(actual_num_values.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::UnexpectedMultipleUsage => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg.to_string()); + c.none("' was provided more than once, but cannot be used multiple times"); + true + } else { + false + } + } + ErrorKind::UnknownArgument => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("Found argument '"); + c.warning(invalid_arg.to_string()); + c.none("' which wasn't expected, or isn't valid in this context"); + + let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); + let valid_arg = self.get_context(ContextKind::SuggestedArg); + match (valid_sub, valid_arg) { + ( + Some(ContextValue::String(valid_sub)), + Some(ContextValue::String(valid_arg)), + ) => { + c.none("\n\n\tDid you mean "); + c.none("to put '"); + c.good(valid_arg); + c.none("' after the subcommand '"); + c.good(valid_sub); + c.none("'?"); + } + (None, Some(ContextValue::String(valid_arg))) => { + c.none("\n\n\tDid you mean '"); + c.good(valid_arg); + c.none("'?"); + } + (_, _) => {} + } + + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + if invalid_arg.starts_with('-') { + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a value rather than a flag, use `-- {}`", + invalid_arg, invalid_arg + )); + } + + let trailing_arg = self.get_context(ContextKind::TrailingArg); + if trailing_arg == Some(&ContextValue::Bool(true)) { + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a subcommand, remove the '--' before it.", + invalid_arg + )); + } + } + true + } else { + false + } + } + ErrorKind::ArgumentNotFound => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg.to_string()); + c.none("' wasn't found"); + true + } else { + false + } + } + ErrorKind::DisplayHelp + | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand + | ErrorKind::DisplayVersion + | ErrorKind::Io + | ErrorKind::Format => false, + } + } + + /// Returns the singular or plural form on the verb to be based on the argument's value. + fn singular_or_plural(n: usize) -> &'static str { + if n > 1 { + " were provided" + } else { + " was provided" + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::raw(ErrorKind::Io, e) + } +} + +impl From for Error { + fn from(e: fmt::Error) -> Self { + Error::raw(ErrorKind::Format, e) + } +} + +impl error::Error for Error { + #[allow(trivial_casts)] + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + self.inner.source.as_ref().map(|e| e.as_ref() as _) + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // Assuming `self.message` already has a trailing newline, from `try_help` or similar + write!(f, "{}", self.formatted())?; + if let Some(backtrace) = self.inner.backtrace.as_ref() { + writeln!(f)?; + writeln!(f, "Backtrace:")?; + writeln!(f, "{}", backtrace)?; + } + Ok(()) + } +} + +fn start_error(c: &mut Colorizer) { + c.error("error:"); + c.none(" "); +} + +fn put_usage(c: &mut Colorizer, usage: impl Into) { + c.none("\n\n"); + c.none(usage); +} + +fn get_help_flag(cmd: &Command) -> Option<&'static str> { + if !cmd.is_disable_help_flag_set() { + Some("--help") + } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() { + Some("help") + } else { + None + } +} + +fn try_help(c: &mut Colorizer, help: Option<&str>) { + if let Some(help) = help { + c.none("\n\nFor more information try "); + c.good(help); + c.none("\n"); + } else { + c.none("\n"); + } +} + +fn quote(s: impl AsRef) -> String { + let s = s.as_ref(); + format!("{:?}", s) +} + +fn escape(s: impl AsRef) -> String { + let s = s.as_ref(); + if s.contains(char::is_whitespace) { + quote(s) + } else { + s.to_owned() + } +} + +#[derive(Clone, Debug)] +pub(crate) enum Message { + Raw(String), + Formatted(Colorizer), +} + +impl Message { + fn format(&mut self, cmd: &Command, usage: String) { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(Stream::Stderr, cmd.get_color()); + + let mut message = String::new(); + std::mem::swap(s, &mut message); + start_error(&mut c); + c.none(message); + put_usage(&mut c, usage); + try_help(&mut c, get_help_flag(cmd)); + *self = Self::Formatted(c); + } + Message::Formatted(_) => {} + } + } + + fn formatted(&self) -> Cow { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(Stream::Stderr, ColorChoice::Never); + start_error(&mut c); + c.none(s); + Cow::Owned(c) + } + Message::Formatted(c) => Cow::Borrowed(c), + } + } +} + +impl From for Message { + fn from(inner: String) -> Self { + Self::Raw(inner) + } +} + +impl From for Message { + fn from(inner: Colorizer) -> Self { + Self::Formatted(inner) + } +} + +#[cfg(feature = "debug")] +#[derive(Debug)] +struct Backtrace(backtrace::Backtrace); + +#[cfg(feature = "debug")] +impl Backtrace { + fn new() -> Option { + Some(Self(backtrace::Backtrace::new())) + } +} + +#[cfg(feature = "debug")] +impl Display for Backtrace { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // `backtrace::Backtrace` uses `Debug` instead of `Display` + write!(f, "{:?}", self.0) + } +} + +#[cfg(not(feature = "debug"))] +#[derive(Debug)] +struct Backtrace; + +#[cfg(not(feature = "debug"))] +impl Backtrace { + fn new() -> Option { + None + } +} + +#[cfg(not(feature = "debug"))] +impl Display for Backtrace { + fn fmt(&self, _: &mut Formatter) -> fmt::Result { + Ok(()) + } +} + +#[test] +fn check_auto_traits() { + static_assertions::assert_impl_all!(Error: Send, Sync, Unpin); +} diff --git a/vendor/clap-3.2.20/src/lib.rs b/vendor/clap-3.2.20/src/lib.rs new file mode 100644 index 000000000..5cefe6ec1 --- /dev/null +++ b/vendor/clap-3.2.20/src/lib.rs @@ -0,0 +1,232 @@ +// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/graphs/contributors). +// Licensed under the MIT license +// (see LICENSE or ) All files in the project carrying such +// notice may not be copied, modified, or distributed except according to those terms. + +//! > **Command Line Argument Parser for Rust** +//! +//! Quick Links: +//! - Derive [tutorial][_derive::_tutorial] and [reference][_derive] +//! - Builder [tutorial][_tutorial] and [reference](index.html) +//! - [Cookbook][_cookbook] +//! - [FAQ][_faq] +//! - [Discussions](https://github.com/clap-rs/clap/discussions) +//! +//! ## Aspirations +//! +//! - Out of the box, users get a polished CLI experience +//! - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc +//! - Flexible enough to port your existing CLI interface +//! - However, we won't necessarily streamline support for each use case +//! - Reasonable parse performance +//! - Resilient maintainership, including +//! - Willing to break compatibility rather than batching up breaking changes in large releases +//! - Leverage feature flags to keep to one active branch +//! - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor +//! - We follow semver and will wait about 6-9 months between major breaking changes +//! - We will support the last two minor Rust releases (MSRV, currently 1.56.1) +//! +//! While these aspirations can be at odds with fast build times and low binary +//! size, we will still strive to keep these reasonable for the flexibility you +//! get. Check out the +//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for +//! CLI parsers optimized for other use cases. +//! +//! ## Example +//! +//! Run +//! ```console +//! $ cargo add clap --features derive +//! ``` +//! *(See also [feature flag reference][_features])* +//! +//! Then define your CLI in `main.rs`: +#![cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#![cfg_attr(feature = "derive", doc = " ```no_run")] +#![doc = include_str!("../examples/demo.rs")] +//! ``` +//! +//! And try it out: +#![doc = include_str!("../examples/demo.md")] +//! +//! See also the derive [tutorial][_derive::_tutorial] and [reference][_derive] +//! +//! ### Related Projects +//! +//! Augment clap: +//! - [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux +//! - [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files) +//! - [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version` +//! - [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff) +//! - [clap_complete](https://crates.io/crates/clap_complete) for shell completion support +//! +//! CLI Helpers +//! - [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) +//! - [clap-cargo](https://crates.io/crates/clap-cargo) +//! - [concolor-clap](https://crates.io/crates/concolor-clap) +//! +//! Testing +//! - [`trycmd`](https://crates.io/crates/trycmd): Bulk snapshot testing +//! - [`snapbox`](https://crates.io/crates/snapbox): Specialized snapshot testing +//! - [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs): Customized testing +//! +//! Documentation: +//! - [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book +//! + +#![cfg_attr(docsrs, feature(doc_auto_cfg))] +#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] +#![warn( + missing_docs, + missing_debug_implementations, + missing_copy_implementations, + trivial_casts, + unused_allocation, + trivial_numeric_casts, + clippy::single_char_pattern +)] +#![forbid(unsafe_code)] +// HACK https://github.com/rust-lang/rust-clippy/issues/7290 +#![allow(clippy::single_component_path_imports)] +#![allow(clippy::branches_sharing_code)] +// Doesn't allow for debug statements, etc to be unique +#![allow(clippy::if_same_then_else)] + +#[cfg(not(feature = "std"))] +compile_error!("`std` feature is currently required to build `clap`"); + +pub use crate::builder::ArgAction; +pub use crate::builder::Command; +pub use crate::builder::{Arg, ArgGroup}; +pub use crate::error::Error; +pub use crate::parser::ArgMatches; +#[cfg(feature = "color")] +pub use crate::util::color::ColorChoice; +#[cfg(not(feature = "color"))] +#[allow(unused_imports)] +pub(crate) use crate::util::color::ColorChoice; + +pub use crate::derive::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; + +#[allow(deprecated)] +pub use crate::builder::App; +pub use crate::builder::{AppFlags, AppSettings, ArgFlags, ArgSettings, PossibleValue, ValueHint}; +pub use crate::error::{ErrorKind, Result}; +#[allow(deprecated)] +pub use crate::parser::{Indices, OsValues, ValueSource, Values}; + +#[cfg(feature = "yaml")] +#[doc(hidden)] +#[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + ) +)] +#[doc(hidden)] +pub use yaml_rust::YamlLoader; + +#[cfg(feature = "derive")] +#[doc(hidden)] +pub use clap_derive::{self, *}; + +/// Deprecated, replaced with [`CommandFactory`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `CommandFactory`") +)] +pub use CommandFactory as IntoApp; +/// Deprecated, replaced with [`Parser`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Parser`") +)] +#[doc(hidden)] +pub use Parser as StructOpt; +/// Deprecated, replaced with [`ValueEnum`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ValueEnum`") +)] +pub use ValueEnum as ArgEnum; + +#[cfg(feature = "unstable-doc")] +pub mod _cookbook; +#[cfg(feature = "unstable-doc")] +pub mod _derive; +#[cfg(feature = "unstable-doc")] +pub mod _faq; +#[cfg(feature = "unstable-doc")] +pub mod _features; +#[cfg(feature = "unstable-doc")] +pub mod _tutorial; + +#[doc(hidden)] +pub mod __macro_refs { + #[cfg(any(feature = "derive", feature = "cargo"))] + #[doc(hidden)] + pub use once_cell; +} + +#[macro_use] +#[allow(missing_docs)] +mod macros; + +mod derive; + +#[cfg(feature = "regex")] +pub use crate::builder::RegexRef; + +pub mod builder; +pub mod error; +pub mod parser; + +mod mkeymap; +mod output; +mod util; + +const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ + report at https://github.com/clap-rs/clap/issues"; +const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; + +/// Deprecated, replaced with [`Command::new`], unless you were looking for [Subcommand] +#[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `Command::new` unless you intended the `Subcommand` trait" + ) +)] +#[doc(hidden)] +#[derive(Debug, Copy, Clone)] +pub struct SubCommand {} + +#[allow(deprecated)] +impl SubCommand { + /// Deprecated, replaced with [`Command::new`]. + /// Did you mean Subcommand (lower-case c)? + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `Command::new`") + )] + #[doc(hidden)] + pub fn with_name<'help>(name: &str) -> App<'help> { + Command::new(name) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + ) + )] + #[doc(hidden)] + pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App { + #![allow(deprecated)] + Command::from_yaml(yaml) + } +} diff --git a/vendor/clap-3.2.20/src/macros.rs b/vendor/clap-3.2.20/src/macros.rs new file mode 100644 index 000000000..1f9167408 --- /dev/null +++ b/vendor/clap-3.2.20/src/macros.rs @@ -0,0 +1,1058 @@ +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +#[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + ) +)] +#[doc(hidden)] +#[macro_export] +macro_rules! load_yaml { + ($yaml:expr) => { + &$crate::YamlLoader::load_from_str(include_str!($yaml)).expect("failed to load YAML file") + [0] + }; +} + +/// Deprecated, replaced with [`ArgMatches::value_of_t`][crate::ArgMatches::value_of_t] +#[macro_export] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::get_one`") +)] +#[doc(hidden)] +macro_rules! value_t { + ($m:ident, $v:expr, $t:ty) => { + $crate::value_t!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + $m.value_of_t::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::value_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] +#[macro_export] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::get_one`") +)] +#[doc(hidden)] +macro_rules! value_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + value_t_or_exit!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + $m.value_of_t_or_exit::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::values_of_t`][crate::ArgMatches::value_of_t] +#[macro_export] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::get_many`") +)] +#[doc(hidden)] +macro_rules! values_t { + ($m:ident, $v:expr, $t:ty) => { + values_t!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + $m.values_of_t::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::values_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] +#[macro_export] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::get_many`") +)] +#[doc(hidden)] +macro_rules! values_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + values_t_or_exit!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + $m.values_of_t_or_exit::<$t>($v) + }; +} + +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ValueEnum`") +)] +#[doc(hidden)] +#[macro_export] +macro_rules! _clap_count_exprs { + () => { 0 }; + ($e:expr) => { 1 }; + ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; +} + +/// Deprecated, replaced with [`ArgEnum`][crate::ArgEnum] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.0.0", note = "Replaced with `ValueEnum`") +)] +#[doc(hidden)] +#[macro_export] +macro_rules! arg_enum { + (@as_item $($i:item)*) => ($($i)*); + (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { + $crate::arg_enum!(@as_item + $($tts)* + + impl ::std::str::FromStr for $e { + type Err = String; + + fn from_str(s: &str) -> ::std::result::Result { + #[allow(deprecated, unused_imports)] + use ::std::ascii::AsciiExt; + match s { + $(stringify!($v) | + _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, + _ => Err({ + let v = vec![ + $(stringify!($v),)+ + ]; + format!("valid values: {}", + v.join(", ")) + }), + } + } + } + impl ::std::fmt::Display for $e { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + $($e::$v => write!(f, stringify!($v)),)+ + } + } + } + impl $e { + #[allow(dead_code)] + pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { + [ + $(stringify!($v),)+ + ] + } + }); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; +} + +/// Allows you to pull the version from your Cargo.toml at compile time as +/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .version(crate_version!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_version { + () => { + env!("CARGO_PKG_VERSION") + }; +} + +/// Allows you to pull the authors for the command from your Cargo.toml at +/// compile time in the form: +/// `"author1 lastname :author2 lastname "` +/// +/// You can replace the colons with a custom separator by supplying a +/// replacement string, so, for example, +/// `crate_authors!(",\n")` would become +/// `"author1 lastname ,\nauthor2 lastname ,\nauthor3 lastname "` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .author(crate_authors!("\n")) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_authors { + ($sep:expr) => {{ + static CACHED: clap::__macro_refs::once_cell::sync::Lazy = + clap::__macro_refs::once_cell::sync::Lazy::new(|| { + env!("CARGO_PKG_AUTHORS").replace(':', $sep) + }); + + let s: &'static str = &*CACHED; + s + }}; + () => { + env!("CARGO_PKG_AUTHORS") + }; +} + +/// Allows you to pull the description from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .about(crate_description!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_description { + () => { + env!("CARGO_PKG_DESCRIPTION") + }; +} + +/// Allows you to pull the name from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new(crate_name!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_name { + () => { + env!("CARGO_PKG_NAME") + }; +} + +/// Allows you to build the `Command` instance from your Cargo.toml at compile time. +/// +/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, +/// and therefore won't change the generated output until you recompile. +/// +/// In some cases you can "trick" the compiler into triggering a rebuild when your +/// `Cargo.toml` is changed by including this in your `src/main.rs` file +/// `include_str!("../Cargo.toml");` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # fn main() { +/// let m = command!().get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! command { + () => {{ + $crate::command!($crate::crate_name!()) + }}; + ($name:expr) => {{ + let mut cmd = $crate::Command::new($name).version($crate::crate_version!()); + + let author = $crate::crate_authors!(); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; +} + +/// Requires `cargo` feature flag to be enabled. +#[cfg(not(feature = "cargo"))] +#[macro_export] +macro_rules! command { + () => {{ + compile_error!("`cargo` feature flag is required"); + }}; + ($name:expr) => {{ + compile_error!("`cargo` feature flag is required"); + }}; +} + +/// Deprecated, replaced with [`clap::command!`][crate::command] +#[cfg(feature = "cargo")] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.1.0", note = "Replaced with `clap::command!") +)] +#[macro_export] +macro_rules! app_from_crate { + () => {{ + let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!(", "); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; + ($sep:expr) => {{ + let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!($sep); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! arg_impl { + ( @string $val:ident ) => { + stringify!($val) + }; + ( @string $val:literal ) => {{ + let ident_or_string_literal: &str = $val; + ident_or_string_literal + }}; + ( @string $val:tt ) => { + ::std::compile_error!("Only identifiers or string literals supported"); + }; + ( @string ) => { + None + }; + + ( @char $val:ident ) => {{ + let ident_or_char_literal = stringify!($val); + debug_assert_eq!( + ident_or_char_literal.len(), + 1, + "Single-letter identifier expected, got {}", + ident_or_char_literal + ); + ident_or_char_literal.chars().next().unwrap() + }}; + ( @char $val:literal ) => {{ + let ident_or_char_literal: char = $val; + ident_or_char_literal + }}; + ( @char ) => {{ + None + }}; + + ( + @arg + ($arg:expr) + --$long:ident + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + } + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_id().is_empty() { + arg = arg.id(long); + } + arg.long(long) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + --$long:literal + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + } + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_id().is_empty() { + arg = arg.id(long); + } + arg.long(long) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + -$short:ident + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + } + + $arg.short($crate::arg_impl! { @char $short }) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + -$short:literal + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + } + + $arg.short($crate::arg_impl! { @char $short }) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + <$value_name:ident> + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + } + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + arg = arg.required(true); + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + <$value_name:literal> + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + } + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + arg = arg.required(true); + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + [$value_name:ident] + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + } + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + if arg.get_long().is_none() && arg.get_short().is_none() { + arg = arg.required(false); + } else { + arg = arg.min_values(0).max_values(1); + } + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + [$value_name:literal] + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + #[allow(deprecated)] + { + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + } + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + if arg.get_long().is_none() && arg.get_short().is_none() { + arg = arg.required(false); + } else { + arg = arg.min_values(0).max_values(1); + } + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + ... + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({#[allow(deprecated)]{ + $arg.multiple_occurrences(true) + }}) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + $help:literal + ) => { + $arg.help($help) + }; + ( + @arg + ($arg:expr) + ) => { + $arg + }; +} + +/// Create an [`Arg`] from a usage string. +/// +/// Allows creation of basic settings for the [`Arg`]. +/// +/// **NOTE**: Not all settings may be set using the usage string method. Some properties are +/// only available via the builder pattern. +/// +/// # Syntax +/// +/// Usage strings typically following the form: +/// +/// ```notrust +/// [explicit name] [short] [long] [value names] [...] [help string] +/// ``` +/// +/// ### Explicit Name +/// +/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or +/// `"name":`. +/// +/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional +/// fields as the name using the following priority order: +/// +/// 1. Explicit Name +/// 2. Long +/// 3. Value Name +/// +/// See [`Arg::name`][crate::Arg::name]. +/// +/// ### Short +/// +/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or +/// `-'f'`. +/// +/// See [`Arg::short`][crate::Arg::short]. +/// +/// ### Long +/// +/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or +/// `--"foo"`. +/// +/// See [`Arg::long`][crate::Arg::long]. +/// +/// ### Values (Value Notation) +/// +/// This is set by placing bare-word between: +/// - `[]` like `[FOO]` +/// - Positional argument: optional +/// - Named argument: optional value +/// - `<>` like ``: required +/// +/// See [`Arg::value_name`][crate::Arg::value_name]. +/// +/// ### `...` +/// +/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple +/// times (not to be confused with multiple values per occurrence). +/// +/// See [`Arg::multiple_occurrences`][crate::Arg::multiple_occurrences]. +/// +/// ### Help String +/// +/// The help string is denoted between a pair of double quotes `""` and may contain any +/// characters. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg, arg}; +/// Command::new("prog") +/// .args(&[ +/// arg!(--config "a required file for the configuration and no short"), +/// arg!(-d --debug ... "turns on debugging information and allows multiples"), +/// arg!([input] "an optional input file to use") +/// ]) +/// # ; +/// ``` +/// [`Arg`]: ./struct.Arg.html +#[macro_export] +macro_rules! arg { + ( $name:ident: $($tail:tt)+ ) => { + $crate::arg_impl! { + @arg ($crate::Arg::new($crate::arg_impl! { @string $name })) $($tail)+ + } + }; + ( $($tail:tt)+ ) => {{ + let arg = $crate::arg_impl! { + @arg ($crate::Arg::default()) $($tail)+ + }; + debug_assert!(!arg.get_id().is_empty(), "Without a value or long flag, the `name:` prefix is required"); + arg + }}; +} + +/// Deprecated, replaced with [`clap::Parser`][crate::Parser] and [`clap::arg!`][crate::arg] (Issue clap-rs/clap#2835) +#[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.0.0", + note = "Replaced with `clap::Parser` for a declarative API (Issue clap-rs/clap#2835)" + ) +)] +#[doc(hidden)] +#[macro_export] +macro_rules! clap_app { + (@app ($builder:expr)) => { $builder }; + (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.arg( + $crate::clap_app!{ @arg ($crate::Arg::new($name)) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.arg( + $crate::clap_app!{ @arg ($crate::Arg::new(stringify!($name))) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.setting($crate::AppSettings::$setting)) + $($tt)* + } + }; +// Treat the application builder as an argument to set its attributes + (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } + }; + (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name))) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(false)) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(true)) $($tail)* }) + $($tt)* + } + }; +// Handle subcommand creation + (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.subcommand( + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } + )) + $($tt)* + } + }; +// Yaml like function calls - used for setting various meta directly against the app + (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { +// $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } + $crate::clap_app!{ @app + ($builder.$ident($($v),*)) + $($tt)* + } + }; + +// Add members to group and continue argument handling with the parent builder + (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; + // Treat the group builder as an argument to set its attributes + (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @group ($builder, $crate::clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } + }; + (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @group + ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, + $group.arg(stringify!($name))) + $($tt)* + } + }; + +// No more tokens to munch + (@arg ($arg:expr) $modes:tt) => { $arg }; +// Shorthand tokens influenced by the usage_string + (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* } + }; + (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } + }; + (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } + }; + (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes +multiple +takes_value $($tail)* } + }; +// Shorthand magic + (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* } + }; +// !foo -> .foo(false) + (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } + }; +// +foo -> .foo(true) + (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } + }; +// Validator + (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } + }; + (@as_expr $expr:expr) => { $expr }; +// Help + (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help($crate::clap_app!{ @as_expr $desc }) }; +// Handle functions that need to be called multiple times for each argument + (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } + }; +// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; +// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; + +// Build a subcommand outside of an app. + (@subcommand $name:ident => $($tail:tt)*) => { + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } + }; +// Start the magic + (($name:expr) => $($tail:tt)*) => {{ + $crate::clap_app!{ @app ($crate::Command::new($name)) $($tail)*} + }}; + + ($name:ident => $($tail:tt)*) => {{ + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)*} + }}; +} + +macro_rules! impl_settings { + ($settings:ident, $flags:ident, + $( + $(#[$inner:ident $($args:tt)*])* + $setting:ident => $flag:path + ),+ + ) => { + impl $flags { + #[allow(dead_code)] + pub(crate) fn empty() -> Self { + $flags(Flags::empty()) + } + + #[allow(dead_code)] + pub(crate) fn insert(&mut self, rhs: Self) { + self.0.insert(rhs.0); + } + + #[allow(dead_code)] + pub(crate) fn remove(&mut self, rhs: Self) { + self.0.remove(rhs.0); + } + + #[allow(dead_code)] + pub(crate) fn set(&mut self, s: $settings) { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.insert($flag), + )* + } + } + + #[allow(dead_code)] + pub(crate) fn unset(&mut self, s: $settings) { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.remove($flag), + )* + } + } + + #[allow(dead_code)] + pub(crate) fn is_set(&self, s: $settings) -> bool { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.contains($flag), + )* + } + } + } + + impl BitOr for $flags { + type Output = Self; + + fn bitor(mut self, rhs: Self) -> Self::Output { + self.0.insert(rhs.0); + self + } + } + + impl From<$settings> for $flags { + fn from(setting: $settings) -> Self { + let mut flags = $flags::empty(); + flags.set(setting); + flags + } + } + + impl BitOr<$settings> for $flags { + type Output = Self; + + fn bitor(mut self, rhs: $settings) -> Self::Output { + self.set(rhs); + self + } + } + + impl BitOr for $settings { + type Output = $flags; + + fn bitor(self, rhs: Self) -> Self::Output { + let mut flags = $flags::empty(); + flags.set(self); + flags.set(rhs); + flags + } + } + } +} + +// Convenience for writing to stderr thanks to https://github.com/BurntSushi +macro_rules! wlnerr { + ($($arg:tt)*) => ({ + use std::io::{Write, stderr}; + writeln!(&mut stderr(), $($arg)*).ok(); + }) +} + +#[cfg(feature = "debug")] +macro_rules! debug { + ($($arg:tt)*) => ({ + let prefix = format!("[{:>w$}] \t", module_path!(), w = 28); + let body = format!($($arg)*); + let mut color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto); + color.hint(prefix); + color.hint(body); + color.none("\n"); + let _ = color.print(); + }) +} + +#[cfg(not(feature = "debug"))] +macro_rules! debug { + ($($arg:tt)*) => {}; +} diff --git a/vendor/clap-3.2.20/src/mkeymap.rs b/vendor/clap-3.2.20/src/mkeymap.rs new file mode 100644 index 000000000..97ecdda77 --- /dev/null +++ b/vendor/clap-3.2.20/src/mkeymap.rs @@ -0,0 +1,193 @@ +use std::iter::Iterator; +use std::ops::Index; +use std::{ffi::OsStr, ffi::OsString}; + +use crate::util::Id; +use crate::Arg; +use crate::INTERNAL_ERROR_MSG; + +#[derive(PartialEq, Eq, Debug, Clone)] +pub(crate) struct Key { + key: KeyType, + index: usize, +} + +#[derive(Default, PartialEq, Eq, Debug, Clone)] +pub(crate) struct MKeyMap<'help> { + /// All of the arguments. + args: Vec>, + + // Cache part: + /// Will be set after `_build()`. + keys: Vec, +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub(crate) enum KeyType { + Short(char), + Long(OsString), + Position(usize), +} + +impl KeyType { + pub(crate) fn is_position(&self) -> bool { + matches!(self, KeyType::Position(_)) + } +} + +impl PartialEq for KeyType { + fn eq(&self, rhs: &usize) -> bool { + match self { + KeyType::Position(x) => x == rhs, + _ => false, + } + } +} + +impl PartialEq<&str> for KeyType { + fn eq(&self, rhs: &&str) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq for KeyType { + fn eq(&self, rhs: &str) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq for KeyType { + fn eq(&self, rhs: &OsStr) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq for KeyType { + fn eq(&self, rhs: &char) -> bool { + match self { + KeyType::Short(c) => c == rhs, + _ => false, + } + } +} + +impl<'help> MKeyMap<'help> { + /// If any arg has corresponding key in this map, we can search the key with + /// u64(for positional argument), char(for short flag), &str and OsString + /// (for long flag) + pub(crate) fn contains(&self, key: K) -> bool + where + KeyType: PartialEq, + { + self.keys.iter().any(|x| x.key == key) + } + + /// Reserves capacity for at least additional more elements to be inserted + pub(crate) fn reserve(&mut self, additional: usize) { + self.args.reserve(additional); + } + + /// Push an argument in the map. + pub(crate) fn push(&mut self, new_arg: Arg<'help>) { + self.args.push(new_arg); + } + + /// Find the arg have corresponding key in this map, we can search the key + /// with u64(for positional argument), char(for short flag), &str and + /// OsString (for long flag) + pub(crate) fn get(&self, key: &K) -> Option<&Arg<'help>> + where + KeyType: PartialEq, + { + self.keys + .iter() + .find(|k| &k.key == key) + .map(|k| &self.args[k.index]) + } + + /// Find out if the map have no arg. + pub(crate) fn is_empty(&self) -> bool { + self.args.is_empty() + } + + /// Return iterators of all keys. + pub(crate) fn keys(&self) -> impl Iterator { + self.keys.iter().map(|x| &x.key) + } + + /// Return iterators of all args. + pub(crate) fn args(&self) -> impl Iterator> { + self.args.iter() + } + + /// Return mutable iterators of all args. + pub(crate) fn args_mut<'map>(&'map mut self) -> impl Iterator> { + self.args.iter_mut() + } + + /// We need a lazy build here since some we may change args after creating + /// the map, you can checkout who uses `args_mut`. + pub(crate) fn _build(&mut self) { + for (i, arg) in self.args.iter().enumerate() { + append_keys(&mut self.keys, arg, i); + } + } + + /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return + /// `Some(arg)` if removed. + pub(crate) fn remove_by_name(&mut self, name: &Id) -> Option> { + self.args + .iter() + .position(|arg| &arg.id == name) + // since it's a cold function, using this wouldn't hurt much + .map(|i| self.args.remove(i)) + } + + /// Remove an arg based on index + pub(crate) fn remove(&mut self, index: usize) -> Arg<'help> { + self.args.remove(index) + } +} + +impl<'help> Index<&'_ KeyType> for MKeyMap<'help> { + type Output = Arg<'help>; + + fn index(&self, key: &KeyType) -> &Self::Output { + self.get(key).expect(INTERNAL_ERROR_MSG) + } +} + +/// Generate key types for an specific Arg. +fn append_keys(keys: &mut Vec, arg: &Arg, index: usize) { + if let Some(pos_index) = arg.index { + let key = KeyType::Position(pos_index); + keys.push(Key { key, index }); + } else { + if let Some(short) = arg.short { + let key = KeyType::Short(short); + keys.push(Key { key, index }); + } + if let Some(long) = arg.long { + let key = KeyType::Long(OsString::from(long)); + keys.push(Key { key, index }); + } + + for (short, _) in arg.short_aliases.iter() { + let key = KeyType::Short(*short); + keys.push(Key { key, index }); + } + for (long, _) in arg.aliases.iter() { + let key = KeyType::Long(OsString::from(long)); + keys.push(Key { key, index }); + } + } +} diff --git a/vendor/clap-3.2.20/src/output/fmt.rs b/vendor/clap-3.2.20/src/output/fmt.rs new file mode 100644 index 000000000..dc1f46e08 --- /dev/null +++ b/vendor/clap-3.2.20/src/output/fmt.rs @@ -0,0 +1,158 @@ +use crate::util::color::ColorChoice; + +use std::{ + fmt::{self, Display, Formatter}, + io::{self, Write}, +}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stream { + Stdout, + Stderr, +} + +#[derive(Clone, Debug)] +pub(crate) struct Colorizer { + stream: Stream, + #[allow(unused)] + color_when: ColorChoice, + pieces: Vec<(String, Style)>, +} + +impl Colorizer { + #[inline(never)] + pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self { + Colorizer { + stream, + color_when, + pieces: vec![], + } + } + + #[inline(never)] + pub(crate) fn good(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Good)); + } + + #[inline(never)] + pub(crate) fn warning(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Warning)); + } + + #[inline(never)] + pub(crate) fn error(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Error)); + } + + #[inline(never)] + #[allow(dead_code)] + pub(crate) fn hint(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Hint)); + } + + #[inline(never)] + pub(crate) fn none(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Default)); + } +} + +/// Printing methods. +impl Colorizer { + #[cfg(feature = "color")] + pub(crate) fn print(&self) -> io::Result<()> { + use termcolor::{BufferWriter, ColorChoice as DepColorChoice, ColorSpec, WriteColor}; + + let color_when = match self.color_when { + ColorChoice::Always => DepColorChoice::Always, + ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto, + _ => DepColorChoice::Never, + }; + + let writer = match self.stream { + Stream::Stderr => BufferWriter::stderr(color_when), + Stream::Stdout => BufferWriter::stdout(color_when), + }; + + let mut buffer = writer.buffer(); + + for piece in &self.pieces { + let mut color = ColorSpec::new(); + match piece.1 { + Style::Good => { + color.set_fg(Some(termcolor::Color::Green)); + } + Style::Warning => { + color.set_fg(Some(termcolor::Color::Yellow)); + } + Style::Error => { + color.set_fg(Some(termcolor::Color::Red)); + color.set_bold(true); + } + Style::Hint => { + color.set_dimmed(true); + } + Style::Default => {} + } + + buffer.set_color(&color)?; + buffer.write_all(piece.0.as_bytes())?; + buffer.reset()?; + } + + writer.print(&buffer) + } + + #[cfg(not(feature = "color"))] + pub(crate) fn print(&self) -> io::Result<()> { + // [e]println can't be used here because it panics + // if something went wrong. We don't want that. + match self.stream { + Stream::Stdout => { + let stdout = std::io::stdout(); + let mut stdout = stdout.lock(); + write!(stdout, "{}", self) + } + Stream::Stderr => { + let stderr = std::io::stderr(); + let mut stderr = stderr.lock(); + write!(stderr, "{}", self) + } + } + } +} + +/// Color-unaware printing. Never uses coloring. +impl Display for Colorizer { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + for piece in &self.pieces { + Display::fmt(&piece.0, f)?; + } + + Ok(()) + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Style { + Good, + Warning, + Error, + Hint, + Default, +} + +impl Default for Style { + fn default() -> Self { + Self::Default + } +} + +#[cfg(feature = "color")] +fn is_a_tty(stream: Stream) -> bool { + let stream = match stream { + Stream::Stdout => atty::Stream::Stdout, + Stream::Stderr => atty::Stream::Stderr, + }; + + atty::is(stream) +} diff --git a/vendor/clap-3.2.20/src/output/help.rs b/vendor/clap-3.2.20/src/output/help.rs new file mode 100644 index 000000000..eb53bfa54 --- /dev/null +++ b/vendor/clap-3.2.20/src/output/help.rs @@ -0,0 +1,1176 @@ +// Std +use std::borrow::Cow; +use std::cmp; +use std::fmt::Write as _; +use std::io::{self, Write}; +use std::usize; + +// Internal +use crate::builder::{display_arg_val, Arg, Command}; +use crate::output::{fmt::Colorizer, Usage}; +use crate::PossibleValue; + +// Third party +use indexmap::IndexSet; +use textwrap::core::display_width; + +/// `clap` Help Writer. +/// +/// Wraps a writer stream providing different methods to generate help for `clap` objects. +pub(crate) struct Help<'help, 'cmd, 'writer> { + writer: HelpWriter<'writer>, + cmd: &'cmd Command<'help>, + usage: &'cmd Usage<'help, 'cmd>, + next_line_help: bool, + term_w: usize, + use_long: bool, +} + +// Public Functions +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + #[cfg(feature = "unstable-v4")] + const DEFAULT_TEMPLATE: &'static str = "\ + {before-help}{name} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + #[cfg(not(feature = "unstable-v4"))] + const DEFAULT_TEMPLATE: &'static str = "\ + {before-help}{bin} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + + #[cfg(feature = "unstable-v4")] + const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ + {before-help}{name} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}{after-help}\ + "; + #[cfg(not(feature = "unstable-v4"))] + const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ + {before-help}{bin} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}{after-help}\ + "; + + /// Create a new `Help` instance. + pub(crate) fn new( + writer: HelpWriter<'writer>, + cmd: &'cmd Command<'help>, + usage: &'cmd Usage<'help, 'cmd>, + use_long: bool, + ) -> Self { + debug!("Help::new cmd={}, use_long={}", cmd.get_name(), use_long); + let term_w = match cmd.get_term_width() { + Some(0) => usize::MAX, + Some(w) => w, + None => cmp::min( + dimensions().map_or(100, |(w, _)| w), + match cmd.get_max_term_width() { + None | Some(0) => usize::MAX, + Some(mw) => mw, + }, + ), + }; + let next_line_help = cmd.is_next_line_help_set(); + + Help { + writer, + cmd, + usage, + next_line_help, + term_w, + use_long, + } + } + + /// Writes the parser help to the wrapped stream. + pub(crate) fn write_help(&mut self) -> io::Result<()> { + debug!("Help::write_help"); + + if let Some(h) = self.cmd.get_override_help() { + self.none(h)?; + } else if let Some(tmpl) = self.cmd.get_help_template() { + self.write_templated_help(tmpl)?; + } else { + let pos = self + .cmd + .get_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let non_pos = self + .cmd + .get_non_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let subcmds = self.cmd.has_visible_subcommands(); + + if non_pos || pos || subcmds { + self.write_templated_help(Self::DEFAULT_TEMPLATE)?; + } else { + self.write_templated_help(Self::DEFAULT_NO_ARGS_TEMPLATE)?; + } + } + + self.none("\n")?; + + Ok(()) + } +} + +macro_rules! write_method { + ($_self:ident, $msg:ident, $meth:ident) => { + match &mut $_self.writer { + HelpWriter::Buffer(c) => { + c.$meth(($msg).into()); + Ok(()) + } + HelpWriter::Normal(w) => w.write_all($msg.as_ref()), + } + }; +} + +// Methods to write Arg help. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + #[inline(never)] + fn good + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, good) + } + + #[inline(never)] + fn warning + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, warning) + } + + #[inline(never)] + fn none + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, none) + } + + #[inline(never)] + fn spaces(&mut self, n: usize) -> io::Result<()> { + // A string with 64 consecutive spaces. + const SHORT_SPACE: &str = + " "; + if let Some(short) = SHORT_SPACE.get(..n) { + self.none(short) + } else { + self.none(" ".repeat(n)) + } + } + + /// Writes help for each argument in the order they were declared to the wrapped stream. + fn write_args_unsorted(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { + debug!("Help::write_args_unsorted"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut arg_v = Vec::with_capacity(10); + + for &arg in args + .iter() + .filter(|arg| should_show_arg(self.use_long, *arg)) + { + if arg.longest_filter() { + longest = longest.max(display_width(&arg.to_string())); + debug!( + "Help::write_args_unsorted: arg={:?} longest={}", + arg.get_id(), + longest + ); + } + arg_v.push(arg) + } + + let next_line_help = self.will_args_wrap(args, longest); + + let argc = arg_v.len(); + for (i, arg) in arg_v.iter().enumerate() { + self.write_arg(arg, i + 1 == argc, next_line_help, longest)?; + } + Ok(()) + } + + /// Sorts arguments by length and display order and write their help to the wrapped stream. + fn write_args(&mut self, args: &[&Arg<'help>], _category: &str) -> io::Result<()> { + debug!("Help::write_args {}", _category); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut ord_v = Vec::new(); + + // Determine the longest + for &arg in args.iter().filter(|arg| { + // If it's NextLineHelp we don't care to compute how long it is because it may be + // NextLineHelp on purpose simply *because* it's so long and would throw off all other + // args alignment + should_show_arg(self.use_long, *arg) + }) { + if arg.longest_filter() { + longest = longest.max(display_width(&arg.to_string())); + debug!( + "Help::write_args: arg={:?} longest={}", + arg.get_id(), + longest + ); + } + + // Formatting key like this to ensure that: + // 1. Argument has long flags are printed just after short flags. + // 2. For two args both have short flags like `-c` and `-C`, the + // `-C` arg is printed just after the `-c` arg + // 3. For args without short or long flag, print them at last(sorted + // by arg name). + // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x + + let key = if let Some(x) = arg.short { + let mut s = x.to_ascii_lowercase().to_string(); + s.push(if x.is_ascii_lowercase() { '0' } else { '1' }); + s + } else if let Some(x) = arg.long { + x.to_string() + } else { + let mut s = '{'.to_string(); + s.push_str(arg.name); + s + }; + ord_v.push((arg.get_display_order(), key, arg)); + } + ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); + + let next_line_help = self.will_args_wrap(args, longest); + + for (i, (_, _, arg)) in ord_v.iter().enumerate() { + let last_arg = i + 1 == ord_v.len(); + self.write_arg(arg, last_arg, next_line_help, longest)?; + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg( + &mut self, + arg: &Arg<'help>, + last_arg: bool, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + let spec_vals = &self.spec_vals(arg); + + self.short(arg)?; + self.long(arg)?; + self.val(arg)?; + self.align_to_about(arg, next_line_help, longest)?; + + let about = if self.use_long { + arg.long_help.or(arg.help).unwrap_or("") + } else { + arg.help.or(arg.long_help).unwrap_or("") + }; + + self.help(Some(arg), about, spec_vals, next_line_help, longest)?; + + if !last_arg { + self.none("\n")?; + if next_line_help { + self.none("\n")?; + } + } + Ok(()) + } + + /// Writes argument's short command to the wrapped stream. + fn short(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::short"); + + self.none(TAB)?; + + if let Some(s) = arg.short { + self.good(format!("-{}", s)) + } else if !arg.is_positional() { + self.none(TAB) + } else { + Ok(()) + } + } + + /// Writes argument's long command to the wrapped stream. + fn long(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::long"); + if let Some(long) = arg.long { + if arg.short.is_some() { + self.none(", ")?; + } + self.good(format!("--{}", long))?; + } + Ok(()) + } + + /// Writes argument's possible values to the wrapped stream. + fn val(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::val: arg={}", arg.name); + let mut need_closing_bracket = false; + if arg.is_takes_value_set() && !arg.is_positional() { + let is_optional_val = arg.min_vals == Some(0); + let sep = if arg.is_require_equals_set() { + if is_optional_val { + need_closing_bracket = true; + "[=" + } else { + "=" + } + } else if is_optional_val { + need_closing_bracket = true; + " [" + } else { + " " + }; + self.none(sep)?; + } + + if arg.is_takes_value_set() || arg.is_positional() { + display_arg_val( + arg, + |s, good| if good { self.good(s) } else { self.none(s) }, + )?; + } + + if need_closing_bracket { + self.none("]")?; + } + Ok(()) + } + + /// Write alignment padding between arg's switches/values and its about message. + fn align_to_about( + &mut self, + arg: &Arg<'help>, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!( + "Help::align_to_about: arg={}, next_line_help={}, longest={}", + arg.name, next_line_help, longest + ); + if self.use_long || next_line_help { + // long help prints messages on the next line so it doesn't need to align text + debug!("Help::align_to_about: printing long help so skip alignment"); + } else if !arg.is_positional() { + let self_len = display_width(&arg.to_string()); + // Since we're writing spaces from the tab point we first need to know if we + // had a long and short, or just short + let padding = if arg.long.is_some() { + // Only account 4 after the val + 4 + } else { + // Only account for ', --' + 4 after the val + 8 + }; + let spcs = longest + padding - self_len; + debug!( + "Help::align_to_about: positional=false arg_len={}, spaces={}", + self_len, spcs + ); + + self.spaces(spcs)?; + } else { + let self_len = display_width(&arg.to_string()); + let padding = 4; + let spcs = longest + padding - self_len; + debug!( + "Help::align_to_about: positional=true arg_len={}, spaces={}", + self_len, spcs + ); + + self.spaces(spcs)?; + } + Ok(()) + } + + fn write_before_help(&mut self) -> io::Result<()> { + debug!("Help::write_before_help"); + let before_help = if self.use_long { + self.cmd + .get_before_long_help() + .or_else(|| self.cmd.get_before_help()) + } else { + self.cmd.get_before_help() + }; + if let Some(output) = before_help { + self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; + self.none("\n\n")?; + } + Ok(()) + } + + fn write_after_help(&mut self) -> io::Result<()> { + debug!("Help::write_after_help"); + let after_help = if self.use_long { + self.cmd + .get_after_long_help() + .or_else(|| self.cmd.get_after_help()) + } else { + self.cmd.get_after_help() + }; + if let Some(output) = after_help { + self.none("\n\n")?; + self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; + } + Ok(()) + } + + /// Writes argument's help to the wrapped stream. + fn help( + &mut self, + arg: Option<&Arg<'help>>, + about: &str, + spec_vals: &str, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::help"); + let mut help = String::from(about) + spec_vals; + debug!("Help::help: Next Line...{:?}", next_line_help); + + let spaces = if next_line_help { + 12 // "tab" * 3 + } else { + longest + 12 + }; + + let too_long = spaces + display_width(&help) >= self.term_w; + + // Is help on next line, if so then indent + if next_line_help { + self.none(format!("\n{}{}{}", TAB, TAB, TAB))?; + } + + debug!("Help::help: Too long..."); + if too_long && spaces <= self.term_w || help.contains("{n}") { + debug!("Yes"); + debug!("Help::help: help...{}", help); + debug!("Help::help: help width...{}", display_width(&help)); + // Determine how many newlines we need to insert + let avail_chars = self.term_w - spaces; + debug!("Help::help: Usable space...{}", avail_chars); + help = text_wrapper(&help.replace("{n}", "\n"), avail_chars); + } else { + debug!("No"); + } + if let Some(part) = help.lines().next() { + self.none(part)?; + } + + // indent of help + let spaces = if next_line_help { + TAB_WIDTH * 3 + } else if let Some(true) = arg.map(|a| a.is_positional()) { + longest + TAB_WIDTH * 2 + } else { + longest + TAB_WIDTH * 3 + }; + + for part in help.lines().skip(1) { + self.none("\n")?; + self.spaces(spaces)?; + self.none(part)?; + } + + #[cfg(feature = "unstable-v4")] + if let Some(arg) = arg { + const DASH_SPACE: usize = "- ".len(); + const COLON_SPACE: usize = ": ".len(); + let possible_vals = arg.get_possible_values2(); + if self.use_long + && !arg.is_hide_possible_values_set() + && possible_vals.iter().any(PossibleValue::should_show_help) + { + debug!("Help::help: Found possible vals...{:?}", possible_vals); + if !help.is_empty() { + self.none("\n\n")?; + self.spaces(spaces)?; + } + self.none("Possible values:")?; + let longest = possible_vals + .iter() + .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name))) + .max() + .expect("Only called with possible value"); + let help_longest = possible_vals + .iter() + .filter_map(|f| f.get_visible_help().map(display_width)) + .max() + .expect("Only called with possible value with help"); + // should new line + let taken = longest + spaces + DASH_SPACE; + + let possible_value_new_line = + self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest; + + let spaces = spaces + TAB_WIDTH - DASH_SPACE; + let spaces_help = if possible_value_new_line { + spaces + DASH_SPACE + } else { + spaces + longest + DASH_SPACE + COLON_SPACE + }; + + for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) { + self.none("\n")?; + self.spaces(spaces)?; + self.none("- ")?; + self.good(pv.get_name())?; + if let Some(help) = pv.get_help() { + debug!("Help::help: Possible Value help"); + + if possible_value_new_line { + self.none(":\n")?; + self.spaces(spaces_help)?; + } else { + self.none(": ")?; + // To align help messages + self.spaces(longest - display_width(pv.get_name()))?; + } + + let avail_chars = if self.term_w > spaces_help { + self.term_w - spaces_help + } else { + usize::MAX + }; + + let help = text_wrapper(help, avail_chars); + let mut help = help.lines(); + + self.none(help.next().unwrap_or_default())?; + for part in help { + self.none("\n")?; + self.spaces(spaces_help)?; + self.none(part)?; + } + } + } + } + } + Ok(()) + } + + /// Will use next line help on writing args. + fn will_args_wrap(&self, args: &[&Arg<'help>], longest: usize) -> bool { + args.iter() + .filter(|arg| should_show_arg(self.use_long, *arg)) + .any(|arg| { + let spec_vals = &self.spec_vals(arg); + self.arg_next_line_help(arg, spec_vals, longest) + }) + } + + fn arg_next_line_help(&self, arg: &Arg<'help>, spec_vals: &str, longest: usize) -> bool { + if self.next_line_help || arg.is_next_line_help_set() || self.use_long { + // setting_next_line + true + } else { + // force_next_line + let h = arg.help.unwrap_or(""); + let h_w = display_width(h) + display_width(spec_vals); + let taken = longest + 12; + self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken) + } + } + + fn spec_vals(&self, a: &Arg) -> String { + debug!("Help::spec_vals: a={}", a); + let mut spec_vals = vec![]; + #[cfg(feature = "env")] + if let Some(ref env) = a.env { + if !a.is_hide_env_set() { + debug!( + "Help::spec_vals: Found environment variable...[{:?}:{:?}]", + env.0, env.1 + ); + let env_val = if !a.is_hide_env_values_set() { + format!( + "={}", + env.1 + .as_ref() + .map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) + ) + } else { + String::new() + }; + let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val); + spec_vals.push(env_info); + } + } + if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() { + debug!( + "Help::spec_vals: Found default value...[{:?}]", + a.default_vals + ); + + let pvs = a + .default_vals + .iter() + .map(|&pvs| pvs.to_string_lossy()) + .map(|pvs| { + if pvs.contains(char::is_whitespace) { + Cow::from(format!("{:?}", pvs)) + } else { + pvs + } + }) + .collect::>() + .join(" "); + + spec_vals.push(format!("[default: {}]", pvs)); + } + if !a.aliases.is_empty() { + debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); + + let als = a + .aliases + .iter() + .filter(|&als| als.1) // visible + .map(|&als| als.0) // name + .collect::>() + .join(", "); + + if !als.is_empty() { + spec_vals.push(format!("[aliases: {}]", als)); + } + } + + if !a.short_aliases.is_empty() { + debug!( + "Help::spec_vals: Found short aliases...{:?}", + a.short_aliases + ); + + let als = a + .short_aliases + .iter() + .filter(|&als| als.1) // visible + .map(|&als| als.0.to_string()) // name + .collect::>() + .join(", "); + + if !als.is_empty() { + spec_vals.push(format!("[short aliases: {}]", als)); + } + } + + let possible_vals = a.get_possible_values2(); + if !(a.is_hide_possible_values_set() + || possible_vals.is_empty() + || cfg!(feature = "unstable-v4") + && self.use_long + && possible_vals.iter().any(PossibleValue::should_show_help)) + { + debug!("Help::spec_vals: Found possible vals...{:?}", possible_vals); + + let pvs = possible_vals + .iter() + .filter_map(PossibleValue::get_visible_quoted_name) + .collect::>() + .join(", "); + + spec_vals.push(format!("[possible values: {}]", pvs)); + } + let connector = if self.use_long { "\n" } else { " " }; + let prefix = if !spec_vals.is_empty() && !a.get_help().unwrap_or("").is_empty() { + if self.use_long { + "\n\n" + } else { + " " + } + } else { + "" + }; + prefix.to_string() + &spec_vals.join(connector) + } + + fn write_about(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { + let about = if self.use_long { + self.cmd.get_long_about().or_else(|| self.cmd.get_about()) + } else { + self.cmd.get_about() + }; + if let Some(output) = about { + if before_new_line { + self.none("\n")?; + } + self.none(text_wrapper(output, self.term_w))?; + if after_new_line { + self.none("\n")?; + } + } + Ok(()) + } + + fn write_author(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { + if let Some(author) = self.cmd.get_author() { + if before_new_line { + self.none("\n")?; + } + self.none(text_wrapper(author, self.term_w))?; + if after_new_line { + self.none("\n")?; + } + } + Ok(()) + } + + fn write_version(&mut self) -> io::Result<()> { + let version = self + .cmd + .get_version() + .or_else(|| self.cmd.get_long_version()); + if let Some(output) = version { + self.none(text_wrapper(output, self.term_w))?; + } + Ok(()) + } +} + +/// Methods to write a single subcommand +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + fn write_subcommand( + &mut self, + sc_str: &str, + cmd: &Command<'help>, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::write_subcommand"); + + let spec_vals = &self.sc_spec_vals(cmd); + + let about = cmd + .get_about() + .or_else(|| cmd.get_long_about()) + .unwrap_or(""); + + self.subcmd(sc_str, next_line_help, longest)?; + self.help(None, about, spec_vals, next_line_help, longest) + } + + fn sc_spec_vals(&self, a: &Command) -> String { + debug!("Help::sc_spec_vals: a={}", a.get_name()); + let mut spec_vals = vec![]; + if 0 < a.get_all_aliases().count() || 0 < a.get_all_short_flag_aliases().count() { + debug!( + "Help::spec_vals: Found aliases...{:?}", + a.get_all_aliases().collect::>() + ); + debug!( + "Help::spec_vals: Found short flag aliases...{:?}", + a.get_all_short_flag_aliases().collect::>() + ); + + let mut short_als = a + .get_visible_short_flag_aliases() + .map(|a| format!("-{}", a)) + .collect::>(); + + let als = a.get_visible_aliases().map(|s| s.to_string()); + + short_als.extend(als); + + let all_als = short_als.join(", "); + + if !all_als.is_empty() { + spec_vals.push(format!(" [aliases: {}]", all_als)); + } + } + spec_vals.join(" ") + } + + fn subcommand_next_line_help( + &self, + cmd: &Command<'help>, + spec_vals: &str, + longest: usize, + ) -> bool { + if self.next_line_help | self.use_long { + // setting_next_line + true + } else { + // force_next_line + let h = cmd.get_about().unwrap_or(""); + let h_w = display_width(h) + display_width(spec_vals); + let taken = longest + 12; + self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken) + } + } + + /// Writes subcommand to the wrapped stream. + fn subcmd(&mut self, sc_str: &str, next_line_help: bool, longest: usize) -> io::Result<()> { + self.none(TAB)?; + self.good(sc_str)?; + if !next_line_help { + let width = display_width(sc_str); + self.spaces(width.max(longest + 4) - width)?; + } + Ok(()) + } +} + +// Methods to write Parser help. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + /// Writes help for all arguments (options, flags, args, subcommands) + /// including titles of a Parser Object to the wrapped stream. + pub(crate) fn write_all_args(&mut self) -> io::Result<()> { + debug!("Help::write_all_args"); + let pos = self + .cmd + .get_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::>(); + let non_pos = self + .cmd + .get_non_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::>(); + let subcmds = self.cmd.has_visible_subcommands(); + + let custom_headings = self + .cmd + .get_arguments() + .filter_map(|arg| arg.get_help_heading()) + .collect::>(); + + let mut first = if !pos.is_empty() { + // Write positional args if any + self.warning("ARGS:\n")?; + self.write_args_unsorted(&pos)?; + false + } else { + true + }; + + if !non_pos.is_empty() { + if !first { + self.none("\n\n")?; + } + self.warning("OPTIONS:\n")?; + self.write_args(&non_pos, "OPTIONS")?; + first = false; + } + if !custom_headings.is_empty() { + for heading in custom_headings { + let args = self + .cmd + .get_arguments() + .filter(|a| { + if let Some(help_heading) = a.get_help_heading() { + return help_heading == heading; + } + false + }) + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::>(); + + if !args.is_empty() { + if !first { + self.none("\n\n")?; + } + self.warning(format!("{}:\n", heading))?; + self.write_args(&args, heading)?; + first = false + } + } + } + + if subcmds { + if !first { + self.none("\n\n")?; + } + + self.warning( + self.cmd + .get_subcommand_help_heading() + .unwrap_or("SUBCOMMANDS"), + )?; + self.warning(":\n")?; + + self.write_subcommands(self.cmd)?; + } + + Ok(()) + } + + /// Will use next line help on writing subcommands. + fn will_subcommands_wrap<'a>( + &self, + subcommands: impl IntoIterator>, + longest: usize, + ) -> bool + where + 'help: 'a, + { + subcommands + .into_iter() + .filter(|&subcommand| should_show_subcommand(subcommand)) + .any(|subcommand| { + let spec_vals = &self.sc_spec_vals(subcommand); + self.subcommand_next_line_help(subcommand, spec_vals, longest) + }) + } + + /// Writes help for subcommands of a Parser Object to the wrapped stream. + fn write_subcommands(&mut self, cmd: &Command<'help>) -> io::Result<()> { + debug!("Help::write_subcommands"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut ord_v = Vec::new(); + for subcommand in cmd + .get_subcommands() + .filter(|subcommand| should_show_subcommand(subcommand)) + { + let mut sc_str = String::new(); + sc_str.push_str(subcommand.get_name()); + if let Some(short) = subcommand.get_short_flag() { + write!(sc_str, " -{}", short).unwrap(); + } + if let Some(long) = subcommand.get_long_flag() { + write!(sc_str, " --{}", long).unwrap(); + } + longest = longest.max(display_width(&sc_str)); + ord_v.push((subcommand.get_display_order(), sc_str, subcommand)); + } + ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); + + debug!("Help::write_subcommands longest = {}", longest); + + let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest); + + let mut first = true; + for (_, sc_str, sc) in &ord_v { + if first { + first = false; + } else { + self.none("\n")?; + } + self.write_subcommand(sc_str, sc, next_line_help, longest)?; + } + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_display_name(&mut self) -> io::Result<()> { + debug!("Help::write_display_name"); + + let display_name = text_wrapper( + &self + .cmd + .get_display_name() + .unwrap_or_else(|| self.cmd.get_name()) + .replace("{n}", "\n"), + self.term_w, + ); + self.good(&display_name)?; + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_bin_name(&mut self) -> io::Result<()> { + debug!("Help::write_bin_name"); + + let bin_name = if let Some(bn) = self.cmd.get_bin_name() { + if bn.contains(' ') { + // In case we're dealing with subcommands i.e. git mv is translated to git-mv + bn.replace(' ', "-") + } else { + text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) + } + } else { + text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) + }; + self.good(&bin_name)?; + Ok(()) + } +} + +// Methods to write Parser help using templates. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + /// Write help to stream for the parser in the format defined by the template. + /// + /// For details about the template language see [`Command::help_template`]. + /// + /// [`Command::help_template`]: Command::help_template() + fn write_templated_help(&mut self, template: &str) -> io::Result<()> { + debug!("Help::write_templated_help"); + + // The strategy is to copy the template from the reader to wrapped stream + // until a tag is found. Depending on its value, the appropriate content is copied + // to the wrapped stream. + // The copy from template is then resumed, repeating this sequence until reading + // the complete template. + + macro_rules! tags { + ( + match $part:ident { + $( $tag:expr => $action:stmt )* + } + ) => { + match $part { + $( + part if part.starts_with(concat!($tag, "}")) => { + $action + let rest = &part[$tag.len()+1..]; + self.none(rest)?; + } + )* + + // Unknown tag, write it back. + part => { + self.none("{")?; + self.none(part)?; + } + } + }; + } + + let mut parts = template.split('{'); + if let Some(first) = parts.next() { + self.none(first)?; + } + + for part in parts { + tags! { + match part { + "name" => { + self.write_display_name()?; + } + "bin" => { + self.write_bin_name()?; + } + "version" => { + self.write_version()?; + } + "author" => { + self.write_author(false, false)?; + } + "author-with-newline" => { + self.write_author(false, true)?; + } + "author-section" => { + self.write_author(true, true)?; + } + "about" => { + self.write_about(false, false)?; + } + "about-with-newline" => { + self.write_about(false, true)?; + } + "about-section" => { + self.write_about(true, true)?; + } + "usage-heading" => { + self.warning("USAGE:")?; + } + "usage" => { + self.none(self.usage.create_usage_no_title(&[]))?; + } + "all-args" => { + self.write_all_args()?; + } + "options" => { + // Include even those with a heading as we don't have a good way of + // handling help_heading in the template. + self.write_args(&self.cmd.get_non_positionals().collect::>(), "options")?; + } + "positionals" => { + self.write_args(&self.cmd.get_positionals().collect::>(), "positionals")?; + } + "subcommands" => { + self.write_subcommands(self.cmd)?; + } + "after-help" => { + self.write_after_help()?; + } + "before-help" => { + self.write_before_help()?; + } + } + } + } + + Ok(()) + } +} + +pub(crate) fn dimensions() -> Option<(usize, usize)> { + #[cfg(not(feature = "wrap_help"))] + return None; + + #[cfg(feature = "wrap_help")] + terminal_size::terminal_size().map(|(w, h)| (w.0.into(), h.0.into())) +} + +const TAB: &str = " "; +const TAB_WIDTH: usize = 4; + +pub(crate) enum HelpWriter<'writer> { + Normal(&'writer mut dyn Write), + Buffer(&'writer mut Colorizer), +} + +fn should_show_arg(use_long: bool, arg: &Arg) -> bool { + debug!("should_show_arg: use_long={:?}, arg={}", use_long, arg.name); + if arg.is_hide_set() { + return false; + } + (!arg.is_hide_long_help_set() && use_long) + || (!arg.is_hide_short_help_set() && !use_long) + || arg.is_next_line_help_set() +} + +fn should_show_subcommand(subcommand: &Command) -> bool { + !subcommand.is_hide_set() +} + +fn text_wrapper(help: &str, width: usize) -> String { + let wrapper = textwrap::Options::new(width) + .break_words(false) + .word_splitter(textwrap::WordSplitter::NoHyphenation); + help.lines() + .map(|line| textwrap::fill(line, &wrapper)) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn wrap_help_last_word() { + let help = String::from("foo bar baz"); + assert_eq!(text_wrapper(&help, 5), "foo\nbar\nbaz"); + } + + #[test] + fn display_width_handles_non_ascii() { + // Popular Danish tongue-twister, the name of a fruit dessert. + let text = "rødgrød med fløde"; + assert_eq!(display_width(text), 17); + // Note that the string width is smaller than the string + // length. This is due to the precomposed non-ASCII letters: + assert_eq!(text.len(), 20); + } + + #[test] + fn display_width_handles_emojis() { + let text = "😂"; + // There is a single `char`... + assert_eq!(text.chars().count(), 1); + // but it is double-width: + assert_eq!(display_width(text), 2); + // This is much less than the byte length: + assert_eq!(text.len(), 4); + } +} diff --git a/vendor/clap-3.2.20/src/output/mod.rs b/vendor/clap-3.2.20/src/output/mod.rs new file mode 100644 index 000000000..e32aac26a --- /dev/null +++ b/vendor/clap-3.2.20/src/output/mod.rs @@ -0,0 +1,7 @@ +mod help; +mod usage; + +pub(crate) mod fmt; + +pub(crate) use self::help::{Help, HelpWriter}; +pub(crate) use self::usage::Usage; diff --git a/vendor/clap-3.2.20/src/output/usage.rs b/vendor/clap-3.2.20/src/output/usage.rs new file mode 100644 index 000000000..6f7a2cad4 --- /dev/null +++ b/vendor/clap-3.2.20/src/output/usage.rs @@ -0,0 +1,449 @@ +use indexmap::IndexSet; + +// Internal +use crate::builder::AppSettings as AS; +use crate::builder::{Arg, ArgPredicate, Command}; +use crate::parser::ArgMatcher; +use crate::util::ChildGraph; +use crate::util::Id; +use crate::INTERNAL_ERROR_MSG; + +pub(crate) struct Usage<'help, 'cmd> { + cmd: &'cmd Command<'help>, + required: Option<&'cmd ChildGraph>, +} + +impl<'help, 'cmd> Usage<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { + Usage { + cmd, + required: None, + } + } + + pub(crate) fn required(mut self, required: &'cmd ChildGraph) -> Self { + self.required = Some(required); + self + } + + // Creates a usage string for display. This happens just after all arguments were parsed, but before + // any subcommands have been parsed (so as to give subcommands their own usage recursively) + pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> String { + debug!("Usage::create_usage_with_title"); + let mut usage = String::with_capacity(75); + usage.push_str("USAGE:\n "); + usage.push_str(&*self.create_usage_no_title(used)); + usage + } + + // Creates a usage string (*without title*) if one was not provided by the user manually. + pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> String { + debug!("Usage::create_usage_no_title"); + if let Some(u) = self.cmd.get_override_usage() { + String::from(&*u) + } else if used.is_empty() { + self.create_help_usage(true) + } else { + self.create_smart_usage(used) + } + } + + // Creates a usage string for display in help messages (i.e. not for errors) + fn create_help_usage(&self, incl_reqs: bool) -> String { + debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs); + let mut usage = String::with_capacity(75); + let name = self + .cmd + .get_usage_name() + .or_else(|| self.cmd.get_bin_name()) + .unwrap_or_else(|| self.cmd.get_name()); + usage.push_str(name); + let req_string = if incl_reqs { + self.get_required_usage_from(&[], None, false) + .iter() + .fold(String::new(), |a, s| a + " " + s) + } else { + String::new() + }; + + if self.needs_options_tag() { + usage.push_str(" [OPTIONS]"); + } + + let allow_missing_positional = self.cmd.is_allow_missing_positional_set(); + if !allow_missing_positional { + usage.push_str(&req_string); + } + + let has_last = self.cmd.get_positionals().any(|p| p.is_last_set()); + // places a '--' in the usage string if there are args and options + // supporting multiple values + if self + .cmd + .get_non_positionals() + .any(|o| o.is_multiple_values_set()) + && self.cmd.get_positionals().any(|p| !p.is_required_set()) + && !(self.cmd.has_visible_subcommands() || self.cmd.is_allow_external_subcommands_set()) + && !has_last + { + usage.push_str(" [--]"); + } + let not_req_or_hidden = + |p: &Arg| (!p.is_required_set() || p.is_last_set()) && !p.is_hide_set(); + if self.cmd.get_positionals().any(not_req_or_hidden) { + if let Some(args_tag) = self.get_args_tag(incl_reqs) { + usage.push_str(&*args_tag); + } else { + usage.push_str(" [ARGS]"); + } + if has_last && incl_reqs { + let pos = self + .cmd + .get_positionals() + .find(|p| p.is_last_set()) + .expect(INTERNAL_ERROR_MSG); + debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name); + let req = pos.is_required_set(); + if req && self.cmd.get_positionals().any(|p| !p.is_required_set()) { + usage.push_str(" -- <"); + } else if req { + usage.push_str(" [--] <"); + } else { + usage.push_str(" [-- <"); + } + usage.push_str(&*pos.name_no_brackets()); + usage.push('>'); + usage.push_str(pos.multiple_str()); + if !req { + usage.push(']'); + } + } + } + + if allow_missing_positional { + usage.push_str(&req_string); + } + + // incl_reqs is only false when this function is called recursively + if self.cmd.has_visible_subcommands() && incl_reqs + || self.cmd.is_allow_external_subcommands_set() + { + let placeholder = self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND"); + #[allow(deprecated)] + if self.cmd.is_subcommand_negates_reqs_set() + || self.cmd.is_args_conflicts_with_subcommands_set() + { + usage.push_str("\n "); + if !self.cmd.is_args_conflicts_with_subcommands_set() { + usage.push_str(&*self.create_help_usage(false)); + } else { + usage.push_str(&*name); + } + usage.push_str(" <"); + usage.push_str(placeholder); + usage.push('>'); + } else if self.cmd.is_subcommand_required_set() + || self.cmd.is_set(AS::SubcommandRequiredElseHelp) + { + usage.push_str(" <"); + usage.push_str(placeholder); + usage.push('>'); + } else { + usage.push_str(" ["); + usage.push_str(placeholder); + usage.push(']'); + } + } + let usage = usage.trim().to_owned(); + debug!("Usage::create_help_usage: usage={}", usage); + usage + } + + // Creates a context aware usage string, or "smart usage" from currently used + // args, and requirements + fn create_smart_usage(&self, used: &[Id]) -> String { + debug!("Usage::create_smart_usage"); + let mut usage = String::with_capacity(75); + + let r_string = self + .get_required_usage_from(used, None, true) + .iter() + .fold(String::new(), |acc, s| acc + " " + s); + + usage.push_str( + self.cmd + .get_usage_name() + .or_else(|| self.cmd.get_bin_name()) + .unwrap_or_else(|| self.cmd.get_name()), + ); + usage.push_str(&*r_string); + if self.cmd.is_subcommand_required_set() { + usage.push_str(" <"); + usage.push_str(self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND")); + usage.push('>'); + } + usage.shrink_to_fit(); + usage + } + + // Gets the `[ARGS]` tag for the usage string + fn get_args_tag(&self, incl_reqs: bool) -> Option { + debug!("Usage::get_args_tag; incl_reqs = {:?}", incl_reqs); + let mut count = 0; + for pos in self + .cmd + .get_positionals() + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + { + debug!("Usage::get_args_tag:iter:{}", pos.name); + let required = self.cmd.groups_for_arg(&pos.id).any(|grp_s| { + debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); + // if it's part of a required group we don't want to count it + self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) + }); + if !required { + count += 1; + debug!( + "Usage::get_args_tag:iter: {} Args not required or hidden", + count + ); + } + } + + if !self.cmd.is_dont_collapse_args_in_usage_set() && count > 1 { + debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]"); + + // [ARGS] + None + } else if count == 1 && incl_reqs { + let pos = self + .cmd + .get_positionals() + .find(|pos| { + !pos.is_required_set() + && !pos.is_hide_set() + && !pos.is_last_set() + && !self.cmd.groups_for_arg(&pos.id).any(|grp_s| { + debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); + // if it's part of a required group we don't want to count it + self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) + }) + }) + .expect(INTERNAL_ERROR_MSG); + + debug!( + "Usage::get_args_tag:iter: Exactly one, returning '{}'", + pos.name + ); + + Some(format!( + " [{}]{}", + pos.name_no_brackets(), + pos.multiple_str() + )) + } else if self.cmd.is_dont_collapse_args_in_usage_set() + && self.cmd.has_positionals() + && incl_reqs + { + debug!("Usage::get_args_tag:iter: Don't collapse returning all"); + Some( + self.cmd + .get_positionals() + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::>() + .join(""), + ) + } else if !incl_reqs { + debug!("Usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); + let highest_req_pos = self + .cmd + .get_positionals() + .filter_map(|pos| { + if pos.is_required_set() && !pos.is_last_set() { + Some(pos.index) + } else { + None + } + }) + .max() + .unwrap_or_else(|| Some(self.cmd.get_positionals().count())); + Some( + self.cmd + .get_positionals() + .filter(|pos| pos.index <= highest_req_pos) + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::>() + .join(""), + ) + } else { + Some("".into()) + } + } + + // Determines if we need the `[OPTIONS]` tag in the usage string + fn needs_options_tag(&self) -> bool { + debug!("Usage::needs_options_tag"); + 'outer: for f in self.cmd.get_non_positionals() { + debug!("Usage::needs_options_tag:iter: f={}", f.name); + + // Don't print `[OPTIONS]` just for help or version + if f.long == Some("help") || f.long == Some("version") { + debug!("Usage::needs_options_tag:iter Option is built-in"); + continue; + } + + if f.is_hide_set() { + debug!("Usage::needs_options_tag:iter Option is hidden"); + continue; + } + if f.is_required_set() { + debug!("Usage::needs_options_tag:iter Option is required"); + continue; + } + for grp_s in self.cmd.groups_for_arg(&f.id) { + debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s); + if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) { + debug!("Usage::needs_options_tag:iter:iter: Group is required"); + continue 'outer; + } + } + + debug!("Usage::needs_options_tag:iter: [OPTIONS] required"); + return true; + } + + debug!("Usage::needs_options_tag: [OPTIONS] not required"); + false + } + + // Returns the required args in usage string form by fully unrolling all groups + // `incl_last`: should we include args that are Arg::Last? (i.e. `prog [foo] -- [last]). We + // can't do that for required usages being built for subcommands because it would look like: + // `prog [foo] -- [last] ` which is totally wrong. + pub(crate) fn get_required_usage_from( + &self, + incls: &[Id], + matcher: Option<&ArgMatcher>, + incl_last: bool, + ) -> IndexSet { + debug!( + "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}", + incls, + matcher.is_some(), + incl_last + ); + let mut ret_val = IndexSet::new(); + + let mut unrolled_reqs = IndexSet::new(); + + let required_owned; + let required = if let Some(required) = self.required { + required + } else { + required_owned = self.cmd.required_graph(); + &required_owned + }; + + for a in required.iter() { + let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option { + let required = match val { + ArgPredicate::Equals(_) => { + if let Some(matcher) = matcher { + matcher.check_explicit(a, *val) + } else { + false + } + } + ArgPredicate::IsPresent => true, + }; + required.then(|| req_arg.clone()) + }; + + for aa in self.cmd.unroll_arg_requires(is_relevant, a) { + // if we don't check for duplicates here this causes duplicate error messages + // see https://github.com/clap-rs/clap/issues/2770 + unrolled_reqs.insert(aa); + } + // always include the required arg itself. it will not be enumerated + // by unroll_requirements_for_arg. + unrolled_reqs.insert(a.clone()); + } + + debug!( + "Usage::get_required_usage_from: unrolled_reqs={:?}", + unrolled_reqs + ); + + let mut required_groups_members = IndexSet::new(); + let mut required_opts = IndexSet::new(); + let mut required_groups = IndexSet::new(); + let mut required_positionals = Vec::new(); + for req in unrolled_reqs.iter().chain(incls.iter()) { + if let Some(arg) = self.cmd.find(req) { + let is_present = matcher + .map(|m| m.check_explicit(req, ArgPredicate::IsPresent)) + .unwrap_or(false); + debug!( + "Usage::get_required_usage_from:iter:{:?} arg is_present={}", + req, is_present + ); + if !is_present { + if arg.is_positional() { + if incl_last || !arg.is_last_set() { + required_positionals.push((arg.index.unwrap(), arg.to_string())); + } + } else { + required_opts.insert(arg.to_string()); + } + } + } else { + debug_assert!(self.cmd.find_group(req).is_some()); + let group_members = self.cmd.unroll_args_in_group(req); + let is_present = matcher + .map(|m| { + group_members + .iter() + .any(|arg| m.check_explicit(arg, ArgPredicate::IsPresent)) + }) + .unwrap_or(false); + debug!( + "Usage::get_required_usage_from:iter:{:?} group is_present={}", + req, is_present + ); + if !is_present { + let elem = self.cmd.format_group(req); + required_groups.insert(elem); + required_groups_members.extend( + group_members + .iter() + .flat_map(|id| self.cmd.find(id)) + .map(|arg| arg.to_string()), + ); + } + } + } + + required_opts.retain(|arg| !required_groups_members.contains(arg)); + ret_val.extend(required_opts); + + ret_val.extend(required_groups); + + required_positionals.sort_by_key(|(ind, _)| *ind); // sort by index + for (_, p) in required_positionals { + if !required_groups_members.contains(&p) { + ret_val.insert(p); + } + } + + debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val); + ret_val + } +} diff --git a/vendor/clap-3.2.20/src/parser/arg_matcher.rs b/vendor/clap-3.2.20/src/parser/arg_matcher.rs new file mode 100644 index 000000000..22087e722 --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/arg_matcher.rs @@ -0,0 +1,280 @@ +// Std +use std::collections::HashMap; +use std::ffi::OsString; +use std::mem; +use std::ops::Deref; + +// Internal +use crate::builder::{Arg, ArgPredicate, Command}; +use crate::parser::AnyValue; +use crate::parser::Identifier; +use crate::parser::PendingArg; +use crate::parser::{ArgMatches, MatchedArg, SubCommand, ValueSource}; +use crate::util::Id; +use crate::INTERNAL_ERROR_MSG; + +#[derive(Debug, Default)] +pub(crate) struct ArgMatcher { + matches: ArgMatches, + pending: Option, +} + +impl ArgMatcher { + pub(crate) fn new(_cmd: &Command) -> Self { + ArgMatcher { + matches: ArgMatches { + #[cfg(debug_assertions)] + valid_args: { + let args = _cmd.get_arguments().map(|a| a.id.clone()); + let groups = _cmd.get_groups().map(|g| g.id.clone()); + args.chain(groups).collect() + }, + #[cfg(debug_assertions)] + valid_subcommands: _cmd.get_subcommands().map(|sc| sc.get_id()).collect(), + // HACK: Allow an external subcommand's ArgMatches be a stand-in for any ArgMatches + // since users can't detect it and avoid the asserts. + // + // See clap-rs/clap#3263 + #[cfg(debug_assertions)] + #[cfg(not(feature = "unstable-v4"))] + disable_asserts: _cmd.is_allow_external_subcommands_set(), + #[cfg(debug_assertions)] + #[cfg(feature = "unstable-v4")] + disable_asserts: false, + ..Default::default() + }, + pending: None, + } + } + + pub(crate) fn into_inner(self) -> ArgMatches { + self.matches + } + + pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) { + debug!( + "ArgMatcher::get_global_values: global_arg_vec={:?}", + global_arg_vec + ); + let mut vals_map = HashMap::new(); + self.fill_in_global_values(global_arg_vec, &mut vals_map); + } + + fn fill_in_global_values( + &mut self, + global_arg_vec: &[Id], + vals_map: &mut HashMap, + ) { + for global_arg in global_arg_vec { + if let Some(ma) = self.get(global_arg) { + // We have to check if the parent's global arg wasn't used but still exists + // such as from a default value. + // + // For example, `myprog subcommand --global-arg=value` where `--global-arg` defines + // a default value of `other` myprog would have an existing MatchedArg for + // `--global-arg` where the value is `other` + let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { + if parent_ma.source() > ma.source() { + parent_ma + } else { + ma + } + } else { + ma + } + .clone(); + vals_map.insert(global_arg.clone(), to_update); + } + } + if let Some(ref mut sc) = self.matches.subcommand { + let mut am = ArgMatcher { + matches: mem::take(&mut sc.matches), + pending: None, + }; + am.fill_in_global_values(global_arg_vec, vals_map); + mem::swap(&mut am.matches, &mut sc.matches); + } + + for (name, matched_arg) in vals_map.iter_mut() { + self.matches.args.insert(name.clone(), matched_arg.clone()); + } + } + + pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> { + self.matches.args.get(arg) + } + + pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> { + self.matches.args.get_mut(arg) + } + + pub(crate) fn remove(&mut self, arg: &Id) { + self.matches.args.swap_remove(arg); + } + + pub(crate) fn contains(&self, arg: &Id) -> bool { + self.matches.args.contains_key(arg) + } + + pub(crate) fn arg_ids(&self) -> indexmap::map::Keys { + self.matches.args.keys() + } + + pub(crate) fn entry(&mut self, arg: &Id) -> indexmap::map::Entry { + self.matches.args.entry(arg.clone()) + } + + pub(crate) fn subcommand(&mut self, sc: SubCommand) { + self.matches.subcommand = Some(Box::new(sc)); + } + + pub(crate) fn subcommand_name(&self) -> Option<&str> { + self.matches.subcommand_name() + } + + pub(crate) fn iter(&self) -> indexmap::map::Iter { + self.matches.args.iter() + } + + pub(crate) fn check_explicit<'a>(&self, arg: &Id, predicate: ArgPredicate<'a>) -> bool { + self.get(arg).map_or(false, |a| a.check_explicit(predicate)) + } + + pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) { + let id = &arg.id; + debug!( + "ArgMatcher::start_custom_arg: id={:?}, source={:?}", + id, source + ); + let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg)); + debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id())); + ma.set_source(source); + ma.new_val_group(); + } + + pub(crate) fn start_custom_group(&mut self, id: &Id, source: ValueSource) { + debug!( + "ArgMatcher::start_custom_arg: id={:?}, source={:?}", + id, source + ); + let ma = self.entry(id).or_insert(MatchedArg::new_group()); + debug_assert_eq!(ma.type_id(), None); + ma.set_source(source); + ma.new_val_group(); + } + + pub(crate) fn start_occurrence_of_arg(&mut self, arg: &Arg) { + let id = &arg.id; + debug!("ArgMatcher::start_occurrence_of_arg: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg)); + debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id())); + ma.set_source(ValueSource::CommandLine); + #[allow(deprecated)] + ma.inc_occurrences(); + ma.new_val_group(); + } + + pub(crate) fn start_occurrence_of_group(&mut self, id: &Id) { + debug!("ArgMatcher::start_occurrence_of_group: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new_group()); + debug_assert_eq!(ma.type_id(), None); + ma.set_source(ValueSource::CommandLine); + #[allow(deprecated)] + ma.inc_occurrences(); + ma.new_val_group(); + } + + pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) { + let id = &Id::empty_hash(); + debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,); + let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd)); + debug_assert_eq!( + ma.type_id(), + Some( + cmd.get_external_subcommand_value_parser() + .expect(INTERNAL_ERROR_MSG) + .type_id() + ) + ); + ma.set_source(ValueSource::CommandLine); + #[allow(deprecated)] + ma.inc_occurrences(); + ma.new_val_group(); + } + + pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) { + let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); + ma.append_val(val, raw_val); + } + + pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) { + let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); + ma.push_index(idx); + } + + pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool { + let num_resolved = self.get(&o.id).map(|ma| ma.num_vals()).unwrap_or(0); + let num_pending = self + .pending + .as_ref() + .and_then(|p| (p.id == o.id).then(|| p.raw_vals.len())) + .unwrap_or(0); + let current_num = num_resolved + num_pending; + debug!( + "ArgMatcher::needs_more_vals: o={}, resolved={}, pending={}", + o.name, num_resolved, num_pending + ); + if current_num == 0 { + true + } else if let Some(num) = o.num_vals { + debug!("ArgMatcher::needs_more_vals: num_vals...{}", num); + #[allow(deprecated)] + if o.is_multiple_occurrences_set() { + (current_num % num) != 0 + } else { + num != current_num + } + } else if let Some(num) = o.max_vals { + debug!("ArgMatcher::needs_more_vals: max_vals...{}", num); + current_num < num + } else if o.min_vals.is_some() { + debug!("ArgMatcher::needs_more_vals: min_vals...true"); + true + } else { + o.is_multiple_values_set() + } + } + + pub(crate) fn pending_arg_id(&self) -> Option<&Id> { + self.pending.as_ref().map(|p| &p.id) + } + + pub(crate) fn pending_values_mut( + &mut self, + id: &Id, + ident: Option, + ) -> &mut Vec { + let pending = self.pending.get_or_insert_with(|| PendingArg { + id: id.clone(), + ident, + raw_vals: Default::default(), + }); + debug_assert_eq!(pending.id, *id, "{}", INTERNAL_ERROR_MSG); + if ident.is_some() { + debug_assert_eq!(pending.ident, ident, "{}", INTERNAL_ERROR_MSG); + } + &mut pending.raw_vals + } + + pub(crate) fn take_pending(&mut self) -> Option { + self.pending.take() + } +} + +impl Deref for ArgMatcher { + type Target = ArgMatches; + + fn deref(&self) -> &Self::Target { + &self.matches + } +} diff --git a/vendor/clap-3.2.20/src/parser/error.rs b/vendor/clap-3.2.20/src/parser/error.rs new file mode 100644 index 000000000..caeba4b8f --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/error.rs @@ -0,0 +1,67 @@ +use crate::util::Id; + +/// Violation of [`ArgMatches`][crate::ArgMatches] assumptions +#[derive(Clone, Debug)] +#[allow(missing_copy_implementations)] // We might add non-Copy types in the future +#[non_exhaustive] +pub enum MatchesError { + /// Failed to downcast `AnyValue` to the specified type + #[non_exhaustive] + Downcast { + /// Type for value stored in [`ArgMatches`][crate::ArgMatches] + actual: super::AnyValueId, + /// The target type to downcast to + expected: super::AnyValueId, + }, + /// Argument not defined in [`Command`][crate::Command] + #[non_exhaustive] + UnknownArgument { + // Missing `id` but blocked on a public id type which will hopefully come with `unstable-v4` + }, +} + +impl MatchesError { + #[track_caller] + pub(crate) fn unwrap(id: &Id, r: Result) -> T { + let err = match r { + Ok(t) => { + return t; + } + Err(err) => err, + }; + panic!( + "Mismatch between definition and access of `{:?}`. {}", + id, err + ) + } +} + +impl std::error::Error for MatchesError {} + +impl std::fmt::Display for MatchesError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Downcast { actual, expected } => { + writeln!( + f, + "Could not downcast to {:?}, need to downcast to {:?}", + expected, actual + ) + } + Self::UnknownArgument {} => { + writeln!(f, "Unknown argument or group id. Make sure you are using the argument id and not the short or long flags") + } + } + } +} + +#[test] +fn check_auto_traits() { + static_assertions::assert_impl_all!( + MatchesError: Send, + Sync, + std::panic::RefUnwindSafe, + std::panic::UnwindSafe, + Unpin + ); +} diff --git a/vendor/clap-3.2.20/src/parser/features/mod.rs b/vendor/clap-3.2.20/src/parser/features/mod.rs new file mode 100644 index 000000000..bdeb766ec --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/features/mod.rs @@ -0,0 +1 @@ +pub(crate) mod suggestions; diff --git a/vendor/clap-3.2.20/src/parser/features/suggestions.rs b/vendor/clap-3.2.20/src/parser/features/suggestions.rs new file mode 100644 index 000000000..9e46f3c9e --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/features/suggestions.rs @@ -0,0 +1,105 @@ +#[cfg(feature = "suggestions")] +use std::cmp::Ordering; + +// Internal +use crate::builder::Command; + +/// Produces multiple strings from a given list of possible values which are similar +/// to the passed in value `v` within a certain confidence by least confidence. +/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield +/// `Some("foo")`, whereas "blark" would yield `None`. +#[cfg(feature = "suggestions")] +pub(crate) fn did_you_mean(v: &str, possible_values: I) -> Vec +where + T: AsRef, + I: IntoIterator, +{ + let mut candidates: Vec<(f64, String)> = possible_values + .into_iter() + .map(|pv| (strsim::jaro_winkler(v, pv.as_ref()), pv.as_ref().to_owned())) + .filter(|(confidence, _)| *confidence > 0.8) + .collect(); + candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)); + candidates.into_iter().map(|(_, pv)| pv).collect() +} + +#[cfg(not(feature = "suggestions"))] +pub(crate) fn did_you_mean(_: &str, _: I) -> Vec +where + T: AsRef, + I: IntoIterator, +{ + Vec::new() +} + +/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase +pub(crate) fn did_you_mean_flag<'a, 'help, I, T>( + arg: &str, + remaining_args: &[&str], + longs: I, + subcommands: impl IntoIterator>, +) -> Option<(String, Option)> +where + 'help: 'a, + T: AsRef, + I: IntoIterator, +{ + use crate::mkeymap::KeyType; + + match did_you_mean(arg, longs).pop() { + Some(candidate) => Some((candidate, None)), + None => subcommands + .into_iter() + .filter_map(|subcommand| { + subcommand._build_self(); + + let longs = subcommand.get_keymap().keys().filter_map(|a| { + if let KeyType::Long(v) = a { + Some(v.to_string_lossy().into_owned()) + } else { + None + } + }); + + let subcommand_name = subcommand.get_name(); + + let candidate = did_you_mean(arg, longs).pop()?; + let score = remaining_args.iter().position(|x| *x == subcommand_name)?; + Some((score, (candidate, Some(subcommand_name.to_string())))) + }) + .min_by_key(|(x, _)| *x) + .map(|(_, suggestion)| suggestion), + } +} + +#[cfg(all(test, features = "suggestions"))] +mod test { + use super::*; + + #[test] + fn possible_values_match() { + let p_vals = ["test", "possible", "values"]; + assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test")); + } + + #[test] + fn possible_values_match() { + let p_vals = ["test", "temp"]; + assert_eq!(did_you_mean("te", p_vals.iter()), Some("test")); + } + + #[test] + fn possible_values_nomatch() { + let p_vals = ["test", "possible", "values"]; + assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); + } + + #[test] + fn flag() { + let p_vals = ["test", "possible", "values"]; + assert_eq!( + did_you_mean_flag("tst", p_vals.iter(), []), + Some(("test", None)) + ); + } +} diff --git a/vendor/clap-3.2.20/src/parser/matches/any_value.rs b/vendor/clap-3.2.20/src/parser/matches/any_value.rs new file mode 100644 index 000000000..a9277e75f --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/matches/any_value.rs @@ -0,0 +1,112 @@ +#[derive(Clone)] +pub(crate) struct AnyValue { + inner: std::sync::Arc, + // While we can extract `TypeId` from `inner`, the debug repr is of a number, so let's track + // the type_name in debug builds. + id: AnyValueId, +} + +impl AnyValue { + pub(crate) fn new(inner: V) -> Self { + let id = AnyValueId::of::(); + let inner = std::sync::Arc::new(inner); + Self { inner, id } + } + + pub(crate) fn downcast_ref( + &self, + ) -> Option<&T> { + self.inner.downcast_ref::() + } + + pub(crate) fn downcast_into(self) -> Result { + let id = self.id; + let value = + std::sync::Arc::downcast::(self.inner).map_err(|inner| Self { inner, id })?; + let value = std::sync::Arc::try_unwrap(value).unwrap_or_else(|arc| (*arc).clone()); + Ok(value) + } + + pub(crate) fn type_id(&self) -> AnyValueId { + self.id + } +} + +impl std::fmt::Debug for AnyValue { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + f.debug_struct("AnyValue").field("inner", &self.id).finish() + } +} + +#[derive(Copy, Clone)] +pub struct AnyValueId { + type_id: std::any::TypeId, + #[cfg(debug_assertions)] + type_name: &'static str, +} + +impl AnyValueId { + pub(crate) fn of() -> Self { + Self { + type_id: std::any::TypeId::of::(), + #[cfg(debug_assertions)] + type_name: std::any::type_name::(), + } + } +} + +impl PartialEq for AnyValueId { + fn eq(&self, other: &Self) -> bool { + self.type_id == other.type_id + } +} + +impl Eq for AnyValueId {} + +impl PartialOrd for AnyValueId { + fn partial_cmp(&self, other: &Self) -> Option { + self.type_id.partial_cmp(&other.type_id) + } +} + +impl Ord for AnyValueId { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.type_id.cmp(&other.type_id) + } +} + +impl std::hash::Hash for AnyValueId { + fn hash(&self, state: &mut H) { + self.type_id.hash(state); + } +} + +impl std::fmt::Debug for AnyValueId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + #[cfg(not(debug_assertions))] + { + self.type_id.fmt(f) + } + #[cfg(debug_assertions)] + { + f.debug_struct(self.type_name).finish() + } + } +} + +impl<'a, A: ?Sized + 'static> From<&'a A> for AnyValueId { + fn from(_: &'a A) -> Self { + Self::of::() + } +} + +#[cfg(test)] +mod test { + #[test] + #[cfg(debug_assertions)] + fn debug_impl() { + use super::*; + + assert_eq!(format!("{:?}", AnyValue::new(5)), "AnyValue { inner: i32 }"); + } +} diff --git a/vendor/clap-3.2.20/src/parser/matches/arg_matches.rs b/vendor/clap-3.2.20/src/parser/matches/arg_matches.rs new file mode 100644 index 000000000..2585c0219 --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/matches/arg_matches.rs @@ -0,0 +1,1896 @@ +// Std +use std::any::Any; +use std::borrow::Cow; +use std::ffi::{OsStr, OsString}; +use std::fmt::{Debug, Display}; +use std::iter::{Cloned, Flatten, Map}; +use std::slice::Iter; +use std::str::FromStr; + +// Third Party +use indexmap::IndexMap; + +// Internal +use crate::parser::AnyValue; +use crate::parser::AnyValueId; +use crate::parser::MatchedArg; +use crate::parser::MatchesError; +use crate::parser::ValueSource; +use crate::util::{Id, Key}; +use crate::Error; +use crate::INTERNAL_ERROR_MSG; + +/// Container for parse results. +/// +/// Used to get information about the arguments that were supplied to the program at runtime by +/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of +/// methods. +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{Command, Arg, ValueSource}; +/// let matches = Command::new("MyApp") +/// .arg(Arg::new("out") +/// .long("output") +/// .required(true) +/// .takes_value(true) +/// .default_value("-")) +/// .arg(Arg::new("cfg") +/// .short('c') +/// .takes_value(true)) +/// .get_matches(); // builds the instance of ArgMatches +/// +/// // to get information about the "cfg" argument we created, such as the value supplied we use +/// // various ArgMatches methods, such as [ArgMatches::get_one] +/// if let Some(c) = matches.get_one::("cfg") { +/// println!("Value for -c: {}", c); +/// } +/// +/// // The ArgMatches::get_one method returns an Option because the user may not have supplied +/// // that argument at runtime. But if we specified that the argument was "required" as we did +/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually +/// // used at runtime. +/// println!("Value for --output: {}", matches.get_one::("out").unwrap()); +/// +/// // You can check the presence of an argument's values +/// if matches.contains_id("out") { +/// // However, if you want to know where the value came from +/// if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine { +/// println!("`out` set by user"); +/// } else { +/// println!("`out` is defaulted"); +/// } +/// } +/// ``` +/// [`Command::get_matches`]: crate::Command::get_matches() +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ArgMatches { + #[cfg(debug_assertions)] + pub(crate) valid_args: Vec, + #[cfg(debug_assertions)] + pub(crate) valid_subcommands: Vec, + #[cfg(debug_assertions)] + pub(crate) disable_asserts: bool, + pub(crate) args: IndexMap, + pub(crate) subcommand: Option>, +} + +/// # Arguments +impl ArgMatches { + /// Gets the value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// Returns an error if the wrong type was used. + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. + /// + /// # Panic + /// + /// If the argument definition and access mismatch. To handle this case programmatically, see + /// [`ArgMatches::try_get_one`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, value_parser}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("port") + /// .value_parser(value_parser!(usize)) + /// .takes_value(true) + /// .required(true)) + /// .get_matches_from(vec!["myapp", "2020"]); + /// + /// let port: usize = *m + /// .get_one("port") + /// .expect("`port`is required"); + /// assert_eq!(port, 2020); + /// ``` + /// [option]: crate::Arg::takes_value() + /// [positional]: crate::Arg::index() + /// [`default_value`]: crate::Arg::default_value() + #[track_caller] + pub fn get_one(&self, id: &str) -> Option<&T> { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_get_one(id)) + } + + /// Gets the value of a specific [`ArgAction::Count`][crate::ArgAction::Count] flag + /// + /// # Panic + /// + /// If the argument's action is not [`ArgAction::Count`][crate::ArgAction::Count] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Count) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert_eq!( + /// matches.get_count("flag"), + /// 2 + /// ); + /// ``` + #[track_caller] + pub fn get_count(&self, id: &str) -> u8 { + *self + .get_one::(id) + .expect("ArgAction::Count is defaulted") + } + + /// Gets the value of a specific [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] flag + /// + /// # Panic + /// + /// If the argument's action is not [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetTrue) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// true + /// ); + /// ``` + #[track_caller] + pub fn get_flag(&self, id: &str) -> bool { + *self + .get_one::(id) + .expect("ArgAction::SetTrue / ArgAction::SetFalse is defaulted") + } + + /// Iterate over values of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// Returns an error if the wrong type was used. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panic + /// + /// If the argument definition and access mismatch. To handle this case programmatically, see + /// [`ArgMatches::try_get_many`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, value_parser, ArgAction}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("ports") + /// .action(ArgAction::Append) + /// .value_parser(value_parser!(usize)) + /// .short('p') + /// .takes_value(true) + /// .required(true)) + /// .get_matches_from(vec![ + /// "myprog", "-p", "22", "-p", "80", "-p", "2020" + /// ]); + /// let vals: Vec = m.get_many("ports") + /// .expect("`port`is required") + /// .copied() + /// .collect(); + /// assert_eq!(vals, [22, 80, 2020]); + /// ``` + #[track_caller] + pub fn get_many( + &self, + id: &str, + ) -> Option> { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_get_many(id)) + } + + /// Iterate over the original argument values. + /// + /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they + /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid + /// filename on a Unix system as an argument value may contain invalid UTF-8. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panic + /// + /// If the argument definition and access mismatch. To handle this case programmatically, see + /// [`ArgMatches::try_get_raw`]. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, arg, value_parser}; + /// # use std::ffi::{OsStr,OsString}; + /// # use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// use std::path::PathBuf; + /// + /// let m = Command::new("utf8") + /// .arg(arg!( ... "some arg").value_parser(value_parser!(PathBuf))) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi" + /// OsString::from_vec(vec![b'H', b'i']), + /// // "{0xe9}!" + /// OsString::from_vec(vec![0xe9, b'!'])]); + /// + /// let mut itr = m.get_raw("arg") + /// .expect("`port`is required") + /// .into_iter(); + /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); + /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); + /// assert_eq!(itr.next(), None); + /// ``` + /// [`Iterator`]: std::iter::Iterator + /// [`OsSt`]: std::ffi::OsStr + /// [values]: OsValues + /// [`String`]: std::string::String + #[track_caller] + pub fn get_raw(&self, id: &str) -> Option> { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_get_raw(id)) + } + + /// Returns the value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// Returns an error if the wrong type was used. No item will have been removed. + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. + /// + /// # Panic + /// + /// If the argument definition and access mismatch. To handle this case programmatically, see + /// [`ArgMatches::try_remove_one`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, value_parser}; + /// let mut m = Command::new("myprog") + /// .arg(Arg::new("file") + /// .required(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "myprog", "file.txt", + /// ]); + /// let vals: String = m.remove_one("file") + /// .expect("`file`is required"); + /// assert_eq!(vals, "file.txt"); + /// ``` + /// [option]: crate::Arg::takes_value() + /// [positional]: crate::Arg::index() + /// [`default_value`]: crate::Arg::default_value() + #[track_caller] + pub fn remove_one(&mut self, id: &str) -> Option { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_remove_one(id)) + } + + /// Return values of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// Returns an error if the wrong type was used. No item will have been removed. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panic + /// + /// If the argument definition and access mismatch. To handle this case programmatically, see + /// [`ArgMatches::try_remove_many`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, value_parser, ArgAction}; + /// let mut m = Command::new("myprog") + /// .arg(Arg::new("file") + /// .action(ArgAction::Append) + /// .multiple_values(true) + /// .required(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt", + /// ]); + /// let vals: Vec = m.remove_many("file") + /// .expect("`file`is required") + /// .collect(); + /// assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]); + /// ``` + #[track_caller] + pub fn remove_many( + &mut self, + id: &str, + ) -> Option> { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_remove_many(id)) + } + + /// Check if values are present for the argument or group id + /// + /// *NOTE:* This will always return `true` if [`default_value`] has been set. + /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. To handle this case programmatically, see + /// [`ArgMatches::try_contains_id`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert!(m.contains_id("debug")); + /// ``` + /// + /// [`default_value`]: crate::Arg::default_value() + pub fn contains_id(&self, id: &str) -> bool { + let internal_id = Id::from(id); + MatchesError::unwrap(&internal_id, self.try_contains_id(id)) + } + + /// Check if any args were present on the command line + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let mut cmd = Command::new("myapp") + /// .arg(Arg::new("output") + /// .takes_value(true)); + /// + /// let m = cmd + /// .try_get_matches_from_mut(vec!["myapp", "something"]) + /// .unwrap(); + /// assert!(m.args_present()); + /// + /// let m = cmd + /// .try_get_matches_from_mut(vec!["myapp"]) + /// .unwrap(); + /// assert!(! m.args_present()); + pub fn args_present(&self) -> bool { + !self.args.is_empty() + } + + /// Deprecated, replaced with [`ArgMatches::get_one()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of(&self, id: T) -> Option<&str> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = unwrap_string_arg(&id, arg.first()?); + Some(v) + } + + /// Deprecated, replaced with [`ArgMatches::get_one()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_lossy(&self, id: T) -> Option> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = unwrap_os_string_arg(&id, arg.first()?); + Some(v.to_string_lossy()) + } + + /// Deprecated, replaced with [`ArgMatches::get_one()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_os(&self, id: T) -> Option<&OsStr> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = unwrap_os_string_arg(&id, arg.first()?); + Some(v) + } + + /// Deprecated, replaced with [`ArgMatches::get_many()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of(&self, id: T) -> Option { + #![allow(deprecated)] + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = Values { + iter: arg.vals_flatten().map(unwrap_string), + len: arg.num_vals(), + }; + Some(v) + } + + /// Get an [`Iterator`] over groups of values of a specific option. + /// + /// specifically grouped by the occurrences of the options. + /// + /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence + /// of the option. + /// + /// If the option doesn't support multiple occurrences, or there was only a single occurrence, + /// the iterator will only contain a single item. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. + /// + /// If `id` is not a valid argument or group id. + /// + /// # Examples + /// ```rust + /// # use clap::{Command,Arg, ArgAction}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("exec") + /// .short('x') + /// .min_values(1) + /// .action(ArgAction::Append) + /// .value_terminator(";")) + /// .get_matches_from(vec![ + /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]); + /// let vals: Vec> = m.grouped_values_of("exec").unwrap().collect(); + /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]); + /// ``` + /// [`Iterator`]: std::iter::Iterator + #[cfg(feature = "unstable-grouped")] + #[cfg_attr(debug_assertions, track_caller)] + pub fn grouped_values_of(&self, id: T) -> Option { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = GroupedValues { + iter: arg.vals().map(|g| g.iter().map(unwrap_string).collect()), + len: arg.vals().len(), + }; + Some(v) + } + + /// Deprecated, replaced with [`ArgMatches::get_many()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_lossy(&self, id: T) -> Option> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = arg + .vals_flatten() + .map(|v| unwrap_os_string_arg(&id, v).to_string_lossy().into_owned()) + .collect(); + Some(v) + } + + /// Deprecated, replaced with [`ArgMatches::get_many()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_os(&self, id: T) -> Option { + #![allow(deprecated)] + let id = Id::from(id); + let arg = self.get_arg(&id)?; + let v = OsValues { + iter: arg.vals_flatten().map(unwrap_os_string), + len: arg.num_vals(), + }; + Some(v) + } + + /// Deprecated, replaced with [`ArgMatches::get_one()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_t(&self, name: &str) -> Result + where + R: FromStr, + ::Err: Display, + { + #![allow(deprecated)] + let v = self + .value_of(name) + .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; + v.parse::().map_err(|e| { + let message = format!( + "The argument '{}' isn't a valid value for '{}': {}", + v, name, e + ); + + Error::value_validation(name.to_string(), v.to_string(), message.into()) + }) + } + + /// Deprecated, replaced with [`ArgMatches::get_one()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_t_or_exit(&self, name: &str) -> R + where + R: FromStr, + ::Err: Display, + { + #![allow(deprecated)] + self.value_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Deprecated, replaced with [`ArgMatches::get_many()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_t(&self, name: &str) -> Result, Error> + where + R: FromStr, + ::Err: Display, + { + #![allow(deprecated)] + let v = self + .values_of(name) + .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; + v.map(|v| { + v.parse::().map_err(|e| { + let message = format!("The argument '{}' isn't a valid value: {}", v, e); + + Error::value_validation(name.to_string(), v.to_string(), message.into()) + }) + }) + .collect() + } + + /// Deprecated, replaced with [`ArgMatches::get_many()`] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_t_or_exit(&self, name: &str) -> Vec + where + R: FromStr, + ::Err: Display, + { + #![allow(deprecated)] + self.values_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Deprecated, replaced with [`ArgAction::SetTrue`][crate::ArgAction] or + /// [`ArgMatches::contains_id`]. + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with either `ArgAction::SetTrue` or `ArgMatches::contains_id(...)`" + ) + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn is_present(&self, id: T) -> bool { + let id = Id::from(id); + + #[cfg(debug_assertions)] + self.get_arg(&id); + + self.args.contains_key(&id) + } + + /// Report where argument value came from + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group id. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ValueSource}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// [`default_value`]: crate::Arg::default_value() + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_source(&self, id: T) -> Option { + let id = Id::from(id); + + let value = self.get_arg(&id); + + value.and_then(MatchedArg::source) + } + + /// Deprecated, replaced with [`ArgAction::Count`][crate::ArgAction], + /// [`ArgMatches::get_many`]`.len()`, or [`ArgMatches::value_source`]. + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "3.2.0", + note = "Replaced with either `ArgAction::Count`, `ArgMatches::get_many(...).len()`, or `ArgMatches::value_source`" + ) + )] + #[cfg_attr(debug_assertions, track_caller)] + pub fn occurrences_of(&self, id: T) -> u64 { + #![allow(deprecated)] + self.get_arg(&Id::from(id)) + .map_or(0, |a| a.get_occurrences()) + } + + /// The first index of that an argument showed up. + /// + /// Indices are similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// Besides the flag/option discrepancy, the primary difference between an argv index and clap + /// index, is that clap continues counting once all arguments have properly separated, whereas + /// an argv index does not. + /// + /// The examples should clear this up. + /// + /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* + /// index. See [`ArgMatches::indices_of`]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group id. + /// + /// # Examples + /// + /// The argv indices are listed in the comments below. See how they correspond to the clap + /// indices. Note that if it's not listed in a clap index, this is because it's not saved in + /// in an `ArgMatches` struct for querying. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); + /// // ARGV indices: ^0 ^1 ^2 ^3 + /// // clap indices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Now notice, if we use one of the other styles of options: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); + /// // ARGV indices: ^0 ^1 ^2 + /// // clap indices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Things become much more complicated, or clear if we look at a more complex combination of + /// flags. Let's also throw in the final option style for good measure. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("flag2") + /// .short('F')) + /// .arg(Arg::new("flag3") + /// .short('z')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); + /// // ARGV indices: ^0 ^1 ^2 + /// // clap indices: ^1,2,3 ^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// One final combination of flags/options to see how they combine: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("flag2") + /// .short('F')) + /// .arg(Arg::new("flag3") + /// .short('z')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-fzFoval"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^1,2,3^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// The last part to mention is when values are sent in multiple groups with a [delimiter]. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_value_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.index_of("option"), Some(2)); + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); + /// ``` + /// [delimiter]: crate::Arg::value_delimiter() + #[cfg_attr(debug_assertions, track_caller)] + pub fn index_of(&self, id: T) -> Option { + let arg = self.get_arg(&Id::from(id))?; + let i = arg.get_index(0)?; + Some(i) + } + + /// All indices an argument appeared at when parsing. + /// + /// Indices are similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// *NOTE:* For more information about how clap indices compared to argv indices, see + /// [`ArgMatches::index_of`] + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group id. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_value_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); + /// ``` + /// + /// Another quick example is when flags and options are used together + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true) + /// .action(ArgAction::Append)) + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::Count)) + /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); + /// // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 + /// // clap indices: ^2 ^3 ^5 ^6 + /// + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 5]); + /// assert_eq!(m.indices_of("flag").unwrap().collect::>(), &[6]); + /// ``` + /// + /// One final example, which is an odd case; if we *don't* use value delimiter as we did with + /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they + /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single + /// index. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 + /// // + /// // clap sees the above as 'myapp -o "val1,val2,val3"' + /// // ^0 ^1 ^2 + /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2]); + /// ``` + /// [`ArgMatches::index_of`]: ArgMatches::index_of() + /// [delimiter]: Arg::value_delimiter() + #[cfg_attr(debug_assertions, track_caller)] + pub fn indices_of(&self, id: T) -> Option> { + let arg = self.get_arg(&Id::from(id))?; + let i = Indices { + iter: arg.indices(), + len: arg.num_vals(), + }; + Some(i) + } + + #[inline] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::try_get_one()`") + )] + pub fn is_valid_arg(&self, _id: impl Key) -> bool { + #[cfg(debug_assertions)] + { + let id = Id::from(_id); + self.disable_asserts || id == Id::empty_hash() || self.valid_args.contains(&id) + } + #[cfg(not(debug_assertions))] + { + true + } + } +} + +/// # Subcommands +impl ArgMatches { + /// The name and `ArgMatches` of the current [subcommand]. + /// + /// Subcommand values are put in a child [`ArgMatches`] + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let app_m = Command::new("git") + /// .subcommand(Command::new("clone")) + /// .subcommand(Command::new("push")) + /// .subcommand(Command::new("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand() { + /// Some(("clone", sub_m)) => {}, // clone was used + /// Some(("push", sub_m)) => {}, // push was used + /// Some(("commit", sub_m)) => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// + /// Another useful scenario is when you want to support third party, or external, subcommands. + /// In these cases you can't know the subcommand name ahead of time, so use a variable instead + /// with pattern matching! + /// + /// ```rust + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let app_m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match app_m.subcommand() { + /// Some((external, sub_m)) => { + /// let ext_args: Vec<&str> = sub_m.get_many::("") + /// .unwrap().map(|s| s.as_str()).collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [subcommand]: crate::Command::subcommand + #[inline] + pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> { + self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches)) + } + + /// Return the name and `ArgMatches` of the current [subcommand]. + /// + /// Subcommand values are put in a child [`ArgMatches`] + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let mut app_m = Command::new("git") + /// .subcommand(Command::new("clone")) + /// .subcommand(Command::new("push")) + /// .subcommand(Command::new("commit")) + /// .subcommand_required(true) + /// .get_matches(); + /// + /// let (name, sub_m) = app_m.remove_subcommand().expect("required"); + /// match (name.as_str(), sub_m) { + /// ("clone", sub_m) => {}, // clone was used + /// ("push", sub_m) => {}, // push was used + /// ("commit", sub_m) => {}, // commit was used + /// (name, _) => unimplemented!("{}", name), + /// } + /// ``` + /// + /// Another useful scenario is when you want to support third party, or external, subcommands. + /// In these cases you can't know the subcommand name ahead of time, so use a variable instead + /// with pattern matching! + /// + /// ```rust + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let mut app_m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match app_m.remove_subcommand() { + /// Some((external, mut sub_m)) => { + /// let ext_args: Vec = sub_m.remove_many("") + /// .expect("`file`is required") + /// .collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [subcommand]: crate::Command::subcommand + pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> { + self.subcommand.take().map(|sc| (sc.name, sc.matches)) + } + + /// The `ArgMatches` for the current [subcommand]. + /// + /// Subcommand values are put in a child [`ArgMatches`] + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Panics + /// + /// If `id` is is not a valid subcommand. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let app_m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d') + /// .action(ArgAction::SetTrue) + /// ) + /// .subcommand(Command::new("test") + /// .arg(Arg::new("opt") + /// .long("option") + /// .takes_value(true))) + /// .get_matches_from(vec![ + /// "myprog", "-d", "test", "--option", "val" + /// ]); + /// + /// // Both parent commands, and child subcommands can have arguments present at the same times + /// assert!(*app_m.get_one::("debug").expect("defaulted by clap")); + /// + /// // Get the subcommand's ArgMatches instance + /// if let Some(sub_m) = app_m.subcommand_matches("test") { + /// // Use the struct like normal + /// assert_eq!(sub_m.get_one::("opt").map(|s| s.as_str()), Some("val")); + /// } + /// ``` + /// + /// [subcommand]: crate::Command::subcommand + /// [`Command`]: crate::Command + pub fn subcommand_matches(&self, id: T) -> Option<&ArgMatches> { + self.get_subcommand(&id.into()).map(|sc| &sc.matches) + } + + /// The name of the current [subcommand]. + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let app_m = Command::new("git") + /// .subcommand(Command::new("clone")) + /// .subcommand(Command::new("push")) + /// .subcommand(Command::new("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand_name() { + /// Some("clone") => {}, // clone was used + /// Some("push") => {}, // push was used + /// Some("commit") => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// [subcommand]: crate::Command::subcommand + /// [`Command`]: crate::Command + #[inline] + pub fn subcommand_name(&self) -> Option<&str> { + self.subcommand.as_ref().map(|sc| &*sc.name) + } + + /// Check if a subcommand can be queried + /// + /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer + /// mistakes. In some context, this doesn't work, so users can use this function to check + /// before they do a query on `ArgMatches`. + #[inline] + #[doc(hidden)] + pub fn is_valid_subcommand(&self, _id: impl Key) -> bool { + #[cfg(debug_assertions)] + { + let id = Id::from(_id); + self.disable_asserts || id == Id::empty_hash() || self.valid_subcommands.contains(&id) + } + #[cfg(not(debug_assertions))] + { + true + } + } +} + +/// # Advanced +impl ArgMatches { + /// Non-panicking version of [`ArgMatches::get_one`] + pub fn try_get_one( + &self, + id: &str, + ) -> Result, MatchesError> { + let id = Id::from(id); + let arg = self.try_get_arg_t::(&id)?; + let value = match arg.and_then(|a| a.first()) { + Some(value) => value, + None => { + return Ok(None); + } + }; + Ok(value + .downcast_ref::() + .map(Some) + .expect(INTERNAL_ERROR_MSG)) // enforced by `try_get_arg_t` + } + + /// Non-panicking version of [`ArgMatches::get_many`] + pub fn try_get_many( + &self, + id: &str, + ) -> Result>, MatchesError> { + let id = Id::from(id); + let arg = match self.try_get_arg_t::(&id)? { + Some(arg) => arg, + None => return Ok(None), + }; + let len = arg.num_vals(); + let values = arg.vals_flatten(); + let values = ValuesRef { + // enforced by `try_get_arg_t` + iter: values.map(|v| v.downcast_ref::().expect(INTERNAL_ERROR_MSG)), + len, + }; + Ok(Some(values)) + } + + /// Non-panicking version of [`ArgMatches::get_raw`] + pub fn try_get_raw(&self, id: &str) -> Result>, MatchesError> { + let id = Id::from(id); + let arg = match self.try_get_arg(&id)? { + Some(arg) => arg, + None => return Ok(None), + }; + let len = arg.num_vals(); + let values = arg.raw_vals_flatten(); + let values = RawValues { + iter: values.map(OsString::as_os_str), + len, + }; + Ok(Some(values)) + } + + /// Non-panicking version of [`ArgMatches::remove_one`] + pub fn try_remove_one( + &mut self, + id: &str, + ) -> Result, MatchesError> { + let id = Id::from(id); + match self.try_remove_arg_t::(&id)? { + Some(values) => Ok(values + .into_vals_flatten() + // enforced by `try_get_arg_t` + .map(|v| v.downcast_into::().expect(INTERNAL_ERROR_MSG)) + .next()), + None => Ok(None), + } + } + + /// Non-panicking version of [`ArgMatches::remove_many`] + pub fn try_remove_many( + &mut self, + id: &str, + ) -> Result>, MatchesError> { + let id = Id::from(id); + let arg = match self.try_remove_arg_t::(&id)? { + Some(arg) => arg, + None => return Ok(None), + }; + let len = arg.num_vals(); + let values = arg.into_vals_flatten(); + let values = Values2 { + // enforced by `try_get_arg_t` + iter: values.map(|v| v.downcast_into::().expect(INTERNAL_ERROR_MSG)), + len, + }; + Ok(Some(values)) + } + + /// Non-panicking version of [`ArgMatches::contains_id`] + pub fn try_contains_id(&self, id: &str) -> Result { + let id = Id::from(id); + + self.verify_arg(&id)?; + + let presence = self.args.contains_key(&id); + Ok(presence) + } +} + +// Private methods +impl ArgMatches { + #[inline] + fn try_get_arg(&self, arg: &Id) -> Result, MatchesError> { + self.verify_arg(arg)?; + Ok(self.args.get(arg)) + } + + #[inline] + fn try_get_arg_t( + &self, + arg: &Id, + ) -> Result, MatchesError> { + let arg = match self.try_get_arg(arg)? { + Some(arg) => arg, + None => { + return Ok(None); + } + }; + self.verify_arg_t::(arg)?; + Ok(Some(arg)) + } + + #[inline] + fn try_remove_arg_t( + &mut self, + arg: &Id, + ) -> Result, MatchesError> { + self.verify_arg(arg)?; + let matched = match self.args.remove(arg) { + Some(matched) => matched, + None => { + return Ok(None); + } + }; + + let expected = AnyValueId::of::(); + let actual = matched.infer_type_id(expected); + if actual == expected { + Ok(Some(matched)) + } else { + self.args.insert(arg.clone(), matched); + Err(MatchesError::Downcast { actual, expected }) + } + } + + fn verify_arg_t( + &self, + arg: &MatchedArg, + ) -> Result<(), MatchesError> { + let expected = AnyValueId::of::(); + let actual = arg.infer_type_id(expected); + if expected == actual { + Ok(()) + } else { + Err(MatchesError::Downcast { actual, expected }) + } + } + + #[inline] + fn verify_arg(&self, _arg: &Id) -> Result<(), MatchesError> { + #[cfg(debug_assertions)] + { + if self.disable_asserts || *_arg == Id::empty_hash() || self.valid_args.contains(_arg) { + } else if self.valid_subcommands.contains(_arg) { + debug!( + "Subcommand `{:?}` used where an argument or group name was expected.", + _arg + ); + return Err(MatchesError::UnknownArgument {}); + } else { + debug!( + "`{:?}` is not an id of an argument or a group.\n\ + Make sure you're using the name of the argument itself \ + and not the name of short or long flags.", + _arg + ); + return Err(MatchesError::UnknownArgument {}); + } + } + Ok(()) + } + + #[inline] + #[cfg_attr(debug_assertions, track_caller)] + fn get_arg(&self, arg: &Id) -> Option<&MatchedArg> { + #[cfg(debug_assertions)] + { + if self.disable_asserts || *arg == Id::empty_hash() || self.valid_args.contains(arg) { + } else if self.valid_subcommands.contains(arg) { + panic!( + "Subcommand `{:?}` used where an argument or group name was expected.", + arg + ); + } else { + panic!( + "`{:?}` is not an id of an argument or a group.\n\ + Make sure you're using the name of the argument itself \ + and not the name of short or long flags.", + arg + ); + } + } + + self.args.get(arg) + } + + #[inline] + #[cfg_attr(debug_assertions, track_caller)] + fn get_subcommand(&self, id: &Id) -> Option<&SubCommand> { + #[cfg(debug_assertions)] + { + if self.disable_asserts + || *id == Id::empty_hash() + || self.valid_subcommands.contains(id) + { + } else if self.valid_args.contains(id) { + panic!( + "Argument or group `{:?}` used where a subcommand name was expected.", + id + ); + } else { + panic!("`{:?}` is not a name of a subcommand.", id); + } + } + + if let Some(ref sc) = self.subcommand { + if sc.id == *id { + return Some(sc); + } + } + + None + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SubCommand { + pub(crate) id: Id, + pub(crate) name: String, + pub(crate) matches: ArgMatches, +} + +/// Iterate over multiple values for an argument via [`ArgMatches::remove_many`]. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg, ArgAction}; +/// let mut m = Command::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .action(ArgAction::Append) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); +/// +/// let mut values = m.remove_many::("output") +/// .unwrap(); +/// +/// assert_eq!(values.next(), Some(String::from("val1"))); +/// assert_eq!(values.next(), Some(String::from("val2"))); +/// assert_eq!(values.next(), None); +/// ``` +#[derive(Clone, Debug)] +pub struct Values2 { + #[allow(clippy::type_complexity)] + iter: Map>>, fn(AnyValue) -> T>, + len: usize, +} + +impl Iterator for Values2 { + type Item = T; + + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl DoubleEndedIterator for Values2 { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} + +impl ExactSizeIterator for Values2 {} + +/// Creates an empty iterator. +impl Default for Values2 { + fn default() -> Self { + let empty: Vec> = Default::default(); + Values2 { + iter: empty.into_iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over multiple values for an argument via [`ArgMatches::get_many`]. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg, ArgAction}; +/// let m = Command::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .action(ArgAction::Append) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); +/// +/// let mut values = m.get_many::("output") +/// .unwrap() +/// .map(|s| s.as_str()); +/// +/// assert_eq!(values.next(), Some("val1")); +/// assert_eq!(values.next(), Some("val2")); +/// assert_eq!(values.next(), None); +/// ``` +#[derive(Clone, Debug)] +pub struct ValuesRef<'a, T> { + #[allow(clippy::type_complexity)] + iter: Map>>, fn(&AnyValue) -> &T>, + len: usize, +} + +impl<'a, T: 'a> Iterator for ValuesRef<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} + +impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {} + +/// Creates an empty iterator. +impl<'a, T: 'a> Default for ValuesRef<'a, T> { + fn default() -> Self { + static EMPTY: [Vec; 0] = []; + ValuesRef { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over raw argument values via [`ArgMatches::get_raw`]. +/// +/// # Examples +/// +#[cfg_attr(not(unix), doc = " ```ignore")] +#[cfg_attr(unix, doc = " ```")] +/// # use clap::{Command, arg, value_parser}; +/// use std::ffi::OsString; +/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; +/// +/// let m = Command::new("utf8") +/// .arg(arg!( "some arg") +/// .value_parser(value_parser!(OsString))) +/// .get_matches_from(vec![OsString::from("myprog"), +/// // "Hi {0xe9}!" +/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +/// assert_eq!( +/// &*m.get_raw("arg") +/// .unwrap() +/// .next().unwrap() +/// .as_bytes(), +/// [b'H', b'i', b' ', 0xe9, b'!'] +/// ); +/// ``` +#[derive(Clone, Debug)] +pub struct RawValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map>>, fn(&OsString) -> &OsStr>, + len: usize, +} + +impl<'a> Iterator for RawValues<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for RawValues<'a> { + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for RawValues<'a> {} + +/// Creates an empty iterator. +impl Default for RawValues<'_> { + fn default() -> Self { + static EMPTY: [Vec; 0] = []; + RawValues { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +// The following were taken and adapted from vec_map source +// repo: https://github.com/contain-rs/vec-map +// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 +// license: MIT - Copyright (c) 2015 The Rust Project Developers + +/// Deprecated, replaced with [`ArgMatches::get_many()`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") +)] +#[derive(Clone, Debug)] +pub struct Values<'a> { + #[allow(clippy::type_complexity)] + iter: Map>>, for<'r> fn(&'r AnyValue) -> &'r str>, + len: usize, +} + +#[allow(deprecated)] +impl<'a> Iterator for Values<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +#[allow(deprecated)] +impl<'a> DoubleEndedIterator for Values<'a> { + fn next_back(&mut self) -> Option<&'a str> { + self.iter.next_back() + } +} + +#[allow(deprecated)] +impl<'a> ExactSizeIterator for Values<'a> {} + +/// Creates an empty iterator. +#[allow(deprecated)] +impl<'a> Default for Values<'a> { + fn default() -> Self { + static EMPTY: [Vec; 0] = []; + Values { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +#[derive(Clone)] +#[allow(missing_debug_implementations)] +pub struct GroupedValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map>, fn(&Vec) -> Vec<&str>>, + len: usize, +} + +impl<'a> Iterator for GroupedValues<'a> { + type Item = Vec<&'a str>; + + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for GroupedValues<'a> { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for GroupedValues<'a> {} + +/// Creates an empty iterator. Used for `unwrap_or_default()`. +impl<'a> Default for GroupedValues<'a> { + fn default() -> Self { + #![allow(deprecated)] + static EMPTY: [Vec; 0] = []; + GroupedValues { + iter: EMPTY[..].iter().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Deprecated, replaced with [`ArgMatches::get_many()`] +#[cfg_attr( + feature = "deprecated", + deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`") +)] +#[derive(Clone, Debug)] +pub struct OsValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map>>, fn(&AnyValue) -> &OsStr>, + len: usize, +} + +#[allow(deprecated)] +impl<'a> Iterator for OsValues<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +#[allow(deprecated)] +impl<'a> DoubleEndedIterator for OsValues<'a> { + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } +} + +#[allow(deprecated)] +impl<'a> ExactSizeIterator for OsValues<'a> {} + +/// Creates an empty iterator. +#[allow(deprecated)] +impl Default for OsValues<'_> { + fn default() -> Self { + static EMPTY: [Vec; 0] = []; + OsValues { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`] +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg}; +/// let m = Command::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .multiple_values(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); +/// +/// let mut indices = m.indices_of("output").unwrap(); +/// +/// assert_eq!(indices.next(), Some(2)); +/// assert_eq!(indices.next(), Some(3)); +/// assert_eq!(indices.next(), None); +/// ``` +/// [`ArgMatches::indices_of`]: ArgMatches::indices_of() +#[derive(Clone, Debug)] +pub struct Indices<'a> { + iter: Cloned>, + len: usize, +} + +impl<'a> Iterator for Indices<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for Indices<'a> { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Indices<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for Indices<'a> { + fn default() -> Self { + static EMPTY: [usize; 0] = []; + // This is never called because the iterator is empty: + Indices { + iter: EMPTY[..].iter().cloned(), + len: 0, + } + } +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn unwrap_string(value: &AnyValue) -> &str { + match value.downcast_ref::() { + Some(value) => value, + None => { + panic!("Must use `_os` lookups with `Arg::allow_invalid_utf8`",) + } + } +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn unwrap_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v str { + match value.downcast_ref::() { + Some(value) => value, + None => { + panic!( + "Must use `_os` lookups with `Arg::allow_invalid_utf8` at `{:?}`", + id + ) + } + } +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn unwrap_os_string(value: &AnyValue) -> &OsStr { + match value.downcast_ref::() { + Some(value) => value, + None => { + panic!("Must use `Arg::allow_invalid_utf8` with `_os` lookups",) + } + } +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn unwrap_os_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v OsStr { + match value.downcast_ref::() { + Some(value) => value, + None => { + panic!( + "Must use `Arg::allow_invalid_utf8` with `_os` lookups at `{:?}`", + id + ) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_auto_traits() { + static_assertions::assert_impl_all!(ArgMatches: Send, Sync, Unpin); + } + + #[test] + fn test_default_values() { + #![allow(deprecated)] + let mut values: Values = Values::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues() { + #![allow(deprecated)] + let mut values: OsValues = OsValues::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_raw_values() { + let mut values: RawValues = Default::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_indices() { + let mut indices: Indices = Indices::default(); + assert_eq!(indices.next(), None); + } + + #[test] + fn test_default_indices_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut indices = matches.indices_of("").unwrap_or_default(); + assert_eq!(indices.next(), None); + } + + #[test] + fn values_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .get_many::("POTATO") + .expect("present") + .count(); + assert_eq!(l, 1); + } + + #[test] + fn os_values_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .value_parser(crate::builder::ValueParser::os_string()) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .get_many::("POTATO") + .expect("present") + .count(); + assert_eq!(l, 1); + } + + #[test] + fn indices_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .indices_of("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } +} diff --git a/vendor/clap-3.2.20/src/parser/matches/matched_arg.rs b/vendor/clap-3.2.20/src/parser/matches/matched_arg.rs new file mode 100644 index 000000000..fde6d37f3 --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/matches/matched_arg.rs @@ -0,0 +1,240 @@ +// Std +use std::{ + ffi::{OsStr, OsString}, + iter::{Cloned, Flatten}, + slice::Iter, +}; + +use crate::builder::ArgPredicate; +use crate::parser::AnyValue; +use crate::parser::AnyValueId; +use crate::parser::ValueSource; +use crate::util::eq_ignore_case; +use crate::INTERNAL_ERROR_MSG; + +#[derive(Debug, Clone)] +pub(crate) struct MatchedArg { + occurs: u64, + source: Option, + indices: Vec, + type_id: Option, + vals: Vec>, + raw_vals: Vec>, + ignore_case: bool, +} + +impl MatchedArg { + pub(crate) fn new_arg(arg: &crate::Arg) -> Self { + let ignore_case = arg.is_ignore_case_set(); + Self { + occurs: 0, + source: None, + indices: Vec::new(), + type_id: Some(arg.get_value_parser().type_id()), + vals: Vec::new(), + raw_vals: Vec::new(), + ignore_case, + } + } + + pub(crate) fn new_group() -> Self { + let ignore_case = false; + Self { + occurs: 0, + source: None, + indices: Vec::new(), + type_id: None, + vals: Vec::new(), + raw_vals: Vec::new(), + ignore_case, + } + } + + pub(crate) fn new_external(cmd: &crate::Command) -> Self { + let ignore_case = false; + Self { + occurs: 0, + source: None, + indices: Vec::new(), + type_id: Some( + cmd.get_external_subcommand_value_parser() + .expect(INTERNAL_ERROR_MSG) + .type_id(), + ), + vals: Vec::new(), + raw_vals: Vec::new(), + ignore_case, + } + } + + #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] + pub(crate) fn inc_occurrences(&mut self) { + self.occurs += 1; + } + + #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] + pub(crate) fn set_occurrences(&mut self, occurs: u64) { + self.occurs = occurs + } + + #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))] + pub(crate) fn get_occurrences(&self) -> u64 { + self.occurs + } + + pub(crate) fn indices(&self) -> Cloned> { + self.indices.iter().cloned() + } + + pub(crate) fn get_index(&self, index: usize) -> Option { + self.indices.get(index).cloned() + } + + pub(crate) fn push_index(&mut self, index: usize) { + self.indices.push(index) + } + + #[cfg(feature = "unstable-grouped")] + pub(crate) fn vals(&self) -> Iter> { + self.vals.iter() + } + + pub(crate) fn vals_flatten(&self) -> Flatten>> { + self.vals.iter().flatten() + } + + pub(crate) fn into_vals_flatten(self) -> Flatten>> { + self.vals.into_iter().flatten() + } + + pub(crate) fn raw_vals_flatten(&self) -> Flatten>> { + self.raw_vals.iter().flatten() + } + + pub(crate) fn first(&self) -> Option<&AnyValue> { + self.vals_flatten().next() + } + + #[cfg(test)] + pub(crate) fn first_raw(&self) -> Option<&OsString> { + self.raw_vals_flatten().next() + } + + pub(crate) fn new_val_group(&mut self) { + self.vals.push(vec![]); + self.raw_vals.push(vec![]); + } + + pub(crate) fn append_val(&mut self, val: AnyValue, raw_val: OsString) { + // We assume there is always a group created before. + self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val); + self.raw_vals + .last_mut() + .expect(INTERNAL_ERROR_MSG) + .push(raw_val); + } + + pub(crate) fn num_vals(&self) -> usize { + self.vals.iter().map(|v| v.len()).sum() + } + + // Will be used later + #[allow(dead_code)] + pub(crate) fn num_vals_last_group(&self) -> usize { + self.vals.last().map(|x| x.len()).unwrap_or(0) + } + + pub(crate) fn all_val_groups_empty(&self) -> bool { + self.vals.iter().flatten().count() == 0 + } + + pub(crate) fn check_explicit(&self, predicate: ArgPredicate) -> bool { + if self.source == Some(ValueSource::DefaultValue) { + return false; + } + + match predicate { + ArgPredicate::Equals(val) => self.raw_vals_flatten().any(|v| { + if self.ignore_case { + // If `v` isn't utf8, it can't match `val`, so `OsStr::to_str` should be fine + eq_ignore_case(&v.to_string_lossy(), &val.to_string_lossy()) + } else { + OsString::as_os_str(v) == OsStr::new(val) + } + }), + ArgPredicate::IsPresent => true, + } + } + + pub(crate) fn source(&self) -> Option { + self.source + } + + pub(crate) fn set_source(&mut self, source: ValueSource) { + if let Some(existing) = self.source { + self.source = Some(existing.max(source)); + } else { + self.source = Some(source) + } + } + + pub(crate) fn type_id(&self) -> Option { + self.type_id + } + + pub(crate) fn infer_type_id(&self, expected: AnyValueId) -> AnyValueId { + self.type_id() + .or_else(|| { + self.vals_flatten() + .map(|v| v.type_id()) + .find(|actual| *actual != expected) + }) + .unwrap_or(expected) + } +} + +impl PartialEq for MatchedArg { + fn eq(&self, other: &MatchedArg) -> bool { + let MatchedArg { + occurs: self_occurs, + source: self_source, + indices: self_indices, + type_id: self_type_id, + vals: _, + raw_vals: self_raw_vals, + ignore_case: self_ignore_case, + } = self; + let MatchedArg { + occurs: other_occurs, + source: other_source, + indices: other_indices, + type_id: other_type_id, + vals: _, + raw_vals: other_raw_vals, + ignore_case: other_ignore_case, + } = other; + self_occurs == other_occurs + && self_source == other_source + && self_indices == other_indices + && self_type_id == other_type_id + && self_raw_vals == other_raw_vals + && self_ignore_case == other_ignore_case + } +} + +impl Eq for MatchedArg {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_grouped_vals_first() { + let mut m = MatchedArg::new_group(); + m.new_val_group(); + m.new_val_group(); + m.append_val(AnyValue::new(String::from("bbb")), "bbb".into()); + m.append_val(AnyValue::new(String::from("ccc")), "ccc".into()); + assert_eq!(m.first_raw(), Some(&OsString::from("bbb"))); + } +} diff --git a/vendor/clap-3.2.20/src/parser/matches/mod.rs b/vendor/clap-3.2.20/src/parser/matches/mod.rs new file mode 100644 index 000000000..7b88eeca7 --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/matches/mod.rs @@ -0,0 +1,17 @@ +mod any_value; +mod arg_matches; +mod matched_arg; +mod value_source; + +pub use any_value::AnyValueId; +pub use arg_matches::RawValues; +pub use arg_matches::ValuesRef; +pub use arg_matches::{ArgMatches, Indices}; +pub use value_source::ValueSource; + +pub(crate) use any_value::AnyValue; +pub(crate) use arg_matches::SubCommand; +pub(crate) use matched_arg::MatchedArg; + +#[allow(deprecated)] +pub use arg_matches::{OsValues, Values}; diff --git a/vendor/clap-3.2.20/src/parser/matches/value_source.rs b/vendor/clap-3.2.20/src/parser/matches/value_source.rs new file mode 100644 index 000000000..fb762d2af --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/matches/value_source.rs @@ -0,0 +1,11 @@ +/// Origin of the argument's value +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[non_exhaustive] +pub enum ValueSource { + /// Value came [`Arg::default_value`][crate::Arg::default_value] + DefaultValue, + /// Value came [`Arg::env`][crate::Arg::env] + EnvVariable, + /// Value was passed in on the command-line + CommandLine, +} diff --git a/vendor/clap-3.2.20/src/parser/mod.rs b/vendor/clap-3.2.20/src/parser/mod.rs new file mode 100644 index 000000000..da81648e1 --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/mod.rs @@ -0,0 +1,27 @@ +//! [`Command`][crate::Command] line argument parser + +mod arg_matcher; +mod error; +mod matches; +#[allow(clippy::module_inception)] +mod parser; +mod validator; + +pub(crate) mod features; + +pub(crate) use self::arg_matcher::ArgMatcher; +pub(crate) use self::matches::AnyValue; +pub(crate) use self::matches::AnyValueId; +pub(crate) use self::matches::{MatchedArg, SubCommand}; +pub(crate) use self::parser::Identifier; +pub(crate) use self::parser::PendingArg; +pub(crate) use self::parser::{ParseState, Parser}; +pub(crate) use self::validator::Validator; + +pub use self::matches::RawValues; +pub use self::matches::ValuesRef; +pub use self::matches::{ArgMatches, Indices, ValueSource}; +pub use error::MatchesError; + +#[allow(deprecated)] +pub use self::matches::{OsValues, Values}; diff --git a/vendor/clap-3.2.20/src/parser/parser.rs b/vendor/clap-3.2.20/src/parser/parser.rs new file mode 100644 index 000000000..ad2bc6e9c --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/parser.rs @@ -0,0 +1,1729 @@ +// Std +use std::{ + cell::Cell, + ffi::{OsStr, OsString}, +}; + +// Third Party +use clap_lex::RawOsStr; + +// Internal +use crate::builder::AppSettings as AS; +use crate::builder::{Arg, Command}; +use crate::error::Error as ClapError; +use crate::error::Result as ClapResult; +use crate::mkeymap::KeyType; +use crate::output::fmt::Stream; +use crate::output::{fmt::Colorizer, Usage}; +use crate::parser::features::suggestions; +use crate::parser::{ArgMatcher, SubCommand}; +use crate::parser::{Validator, ValueSource}; +use crate::util::Id; +use crate::ArgAction; +use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; + +pub(crate) struct Parser<'help, 'cmd> { + cmd: &'cmd mut Command<'help>, + cur_idx: Cell, + /// Index of the previous flag subcommand in a group of flags. + flag_subcmd_at: Option, + /// Counter indicating the number of items to skip + /// when revisiting the group of flags which includes the flag subcommand. + flag_subcmd_skip: usize, +} + +// Initializing Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd mut Command<'help>) -> Self { + Parser { + cmd, + cur_idx: Cell::new(0), + flag_subcmd_at: None, + flag_subcmd_skip: 0, + } + } +} + +// Parsing Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + // The actual parsing function + #[allow(clippy::cognitive_complexity)] + pub(crate) fn get_matches_with( + &mut self, + matcher: &mut ArgMatcher, + raw_args: &mut clap_lex::RawArgs, + mut args_cursor: clap_lex::ArgCursor, + ) -> ClapResult<()> { + debug!("Parser::get_matches_with"); + // Verify all positional assertions pass + + let mut subcmd_name: Option = None; + let mut keep_state = false; + let mut parse_state = ParseState::ValuesDone; + let mut pos_counter = 1; + + // Already met any valid arg(then we shouldn't expect subcommands after it). + let mut valid_arg_found = false; + // If the user already passed '--'. Meaning only positional args follow. + let mut trailing_values = false; + + // Count of positional args + let positional_count = self + .cmd + .get_keymap() + .keys() + .filter(|x| x.is_position()) + .count(); + // If any arg sets .last(true) + let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set()); + + while let Some(arg_os) = raw_args.next(&mut args_cursor) { + // Recover the replaced items if any. + if let Some(replaced_items) = arg_os + .to_value() + .ok() + .and_then(|a| self.cmd.get_replacement(a)) + { + debug!( + "Parser::get_matches_with: found replacer: {:?}, target: {:?}", + arg_os, replaced_items + ); + raw_args.insert(&args_cursor, replaced_items); + continue; + } + + debug!( + "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", + arg_os.to_value_os(), + arg_os.to_value_os().as_raw_bytes() + ); + + // Has the user already passed '--'? Meaning only positional args follow + if !trailing_values { + if self.cmd.is_subcommand_precedence_over_arg_set() + || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_)) + { + // Does the arg match a subcommand name, or any of its aliases (if defined) + let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found); + debug!("Parser::get_matches_with: sc={:?}", sc_name); + if let Some(sc_name) = sc_name { + #[allow(deprecated)] + if sc_name == "help" + && !self.is_set(AS::NoAutoHelp) + && !self.cmd.is_disable_help_subcommand_set() + { + self.parse_help_subcommand(raw_args.remaining(&mut args_cursor))?; + unreachable!("`parse_help_subcommand` always errors"); + } else { + subcmd_name = Some(sc_name.to_owned()); + } + break; + } + } + + if arg_os.is_escape() { + if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if + self.cmd[opt].is_allow_hyphen_values_set()) + { + // ParseResult::MaybeHyphenValue, do nothing + } else { + debug!("Parser::get_matches_with: setting TrailingVals=true"); + trailing_values = true; + continue; + } + } else if let Some((long_arg, long_value)) = arg_os.to_long() { + let parse_result = self.parse_long_arg( + matcher, + long_arg, + long_value, + &parse_state, + &mut valid_arg_found, + trailing_values, + )?; + debug!( + "Parser::get_matches_with: After parse_long_arg {:?}", + parse_result + ); + match parse_result { + ParseResult::NoArg => { + unreachable!("`to_long` always has the flag specified") + } + ParseResult::ValuesDone => { + parse_state = ParseState::ValuesDone; + continue; + } + ParseResult::Opt(id) => { + parse_state = ParseState::Opt(id); + continue; + } + ParseResult::FlagSubCommand(name) => { + debug!( + "Parser::get_matches_with: FlagSubCommand found in long arg {:?}", + &name + ); + subcmd_name = Some(name); + break; + } + ParseResult::EqualsNotProvided { arg } => { + let _ = self.resolve_pending(matcher); + return Err(ClapError::no_equals( + self.cmd, + arg, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + ParseResult::NoMatchingArg { arg } => { + let _ = self.resolve_pending(matcher); + let remaining_args: Vec<_> = raw_args + .remaining(&mut args_cursor) + .map(|x| x.to_str().expect(INVALID_UTF8)) + .collect(); + return Err(self.did_you_mean_error(&arg, matcher, &remaining_args)); + } + ParseResult::UnneededAttachedValue { rest, used, arg } => { + let _ = self.resolve_pending(matcher); + return Err(ClapError::too_many_values( + self.cmd, + rest, + arg, + Usage::new(self.cmd).create_usage_no_title(&used), + )); + } + ParseResult::MaybeHyphenValue => { + // Maybe a hyphen value, do nothing. + } + ParseResult::AttachedValueNotConsumed => { + unreachable!() + } + } + } else if let Some(short_arg) = arg_os.to_short() { + // Arg looks like a short flag, and not a possible number + + // Try to parse short args like normal, if allow_hyphen_values or + // AllowNegativeNumbers is set, parse_short_arg will *not* throw + // an error, and instead return Ok(None) + let parse_result = self.parse_short_arg( + matcher, + short_arg, + &parse_state, + pos_counter, + &mut valid_arg_found, + trailing_values, + )?; + // If it's None, we then check if one of those two AppSettings was set + debug!( + "Parser::get_matches_with: After parse_short_arg {:?}", + parse_result + ); + match parse_result { + ParseResult::NoArg => { + // Is a single dash `-`, try positional. + } + ParseResult::ValuesDone => { + parse_state = ParseState::ValuesDone; + continue; + } + ParseResult::Opt(id) => { + parse_state = ParseState::Opt(id); + continue; + } + ParseResult::FlagSubCommand(name) => { + // If there are more short flags to be processed, we should keep the state, and later + // revisit the current group of short flags skipping the subcommand. + keep_state = self + .flag_subcmd_at + .map(|at| { + raw_args + .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1)); + // Since we are now saving the current state, the number of flags to skip during state recovery should + // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position. + self.flag_subcmd_skip = self.cur_idx.get() - at + 1; + }) + .is_some(); + + debug!( + "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}", + name, + keep_state, + self.flag_subcmd_skip + ); + + subcmd_name = Some(name); + break; + } + ParseResult::EqualsNotProvided { arg } => { + let _ = self.resolve_pending(matcher); + return Err(ClapError::no_equals( + self.cmd, + arg, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + ParseResult::NoMatchingArg { arg } => { + let _ = self.resolve_pending(matcher); + return Err(ClapError::unknown_argument( + self.cmd, + arg, + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + ParseResult::MaybeHyphenValue => { + // Maybe a hyphen value, do nothing. + } + ParseResult::UnneededAttachedValue { .. } + | ParseResult::AttachedValueNotConsumed => unreachable!(), + } + } + + if let ParseState::Opt(id) = &parse_state { + // Assume this is a value of a previous arg. + + // get the option so we can check the settings + let arg_values = matcher.pending_values_mut(id, None); + let arg = &self.cmd[id]; + let parse_result = self.split_arg_values( + arg, + arg_os.to_value_os(), + trailing_values, + arg_values, + ); + let parse_result = parse_result.unwrap_or_else(|| { + if matcher.needs_more_vals(arg) { + ParseResult::Opt(arg.id.clone()) + } else { + ParseResult::ValuesDone + } + }); + parse_state = match parse_result { + ParseResult::Opt(id) => ParseState::Opt(id), + ParseResult::ValuesDone => ParseState::ValuesDone, + _ => unreachable!(), + }; + // get the next value from the iterator + continue; + } + } + + // Correct pos_counter. + pos_counter = { + let is_second_to_last = pos_counter + 1 == positional_count; + + // The last positional argument, or second to last positional + // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)` + let low_index_mults = is_second_to_last + && self + .cmd + .get_positionals() + .any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0))) + && self + .cmd + .get_positionals() + .last() + .map_or(false, |p_name| !p_name.is_last_set()); + + let missing_pos = self.cmd.is_allow_missing_positional_set() + && is_second_to_last + && !trailing_values; + + debug!( + "Parser::get_matches_with: Positional counter...{}", + pos_counter + ); + debug!( + "Parser::get_matches_with: Low index multiples...{:?}", + low_index_mults + ); + + if low_index_mults || missing_pos { + let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { + if let Some(arg) = self + .cmd + .get_positionals() + .find(|a| a.index == Some(pos_counter)) + { + // If next value looks like a new_arg or it's a + // subcommand, skip positional argument under current + // pos_counter(which means current value cannot be a + // positional argument with a value next to it), assume + // current value matches the next arg. + self.is_new_arg(&n, arg) + || self + .possible_subcommand(n.to_value(), valid_arg_found) + .is_some() + } else { + true + } + } else { + true + }; + + if skip_current { + debug!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter + 1 + } else { + pos_counter + } + } else if trailing_values + && (self.cmd.is_allow_missing_positional_set() || contains_last) + { + // Came to -- and one positional has .last(true) set, so we go immediately + // to the last (highest index) positional + debug!("Parser::get_matches_with: .last(true) and --, setting last pos"); + positional_count + } else { + pos_counter + } + }; + + if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) { + if arg.is_last_set() && !trailing_values { + let _ = self.resolve_pending(matcher); + return Err(ClapError::unknown_argument( + self.cmd, + arg_os.display().to_string(), + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + + if self.cmd.is_trailing_var_arg_set() && pos_counter == positional_count { + trailing_values = true; + } + + if matcher.pending_arg_id() != Some(&arg.id) || !arg.is_multiple_values_set() { + self.resolve_pending(matcher)?; + } + let arg_values = matcher.pending_values_mut(&arg.id, Some(Identifier::Index)); + let _parse_result = + self.split_arg_values(arg, arg_os.to_value_os(), trailing_values, arg_values); + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!( + "Parser::get_matches_with: Ignoring state {:?}; positionals do their own thing", + _parse_result + ); + } + } + + // Only increment the positional counter if it doesn't allow multiples + if !arg.is_multiple() { + pos_counter += 1; + parse_state = ParseState::ValuesDone; + } else { + parse_state = ParseState::Pos(arg.id.clone()); + } + valid_arg_found = true; + } else if let Some(external_parser) = + self.cmd.get_external_subcommand_value_parser().cloned() + { + // Get external subcommand name + let sc_name = match arg_os.to_value() { + Ok(s) => s.to_string(), + Err(_) => { + let _ = self.resolve_pending(matcher); + return Err(ClapError::invalid_utf8( + self.cmd, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + }; + + // Collect the external subcommand args + let mut sc_m = ArgMatcher::new(self.cmd); + if cfg!(feature = "unstable-v4") || !raw_args.is_end(&args_cursor) { + sc_m.start_occurrence_of_external(self.cmd); + } + + for raw_val in raw_args.remaining(&mut args_cursor) { + let val = external_parser.parse_ref(self.cmd, None, raw_val)?; + let external_id = &Id::empty_hash(); + sc_m.add_val_to(external_id, val, raw_val.to_os_string()); + } + + matcher.subcommand(SubCommand { + id: Id::from(&*sc_name), + name: sc_name, + matches: sc_m.into_inner(), + }); + + self.resolve_pending(matcher)?; + #[cfg(feature = "env")] + self.add_env(matcher)?; + self.add_defaults(matcher)?; + return Validator::new(self.cmd).validate(parse_state, matcher); + } else { + // Start error processing + let _ = self.resolve_pending(matcher); + return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values)); + } + } + + if let Some(ref pos_sc_name) = subcmd_name { + let sc_name = self + .cmd + .find_subcommand(pos_sc_name) + .expect(INTERNAL_ERROR_MSG) + .get_name() + .to_owned(); + self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state)?; + } + + self.resolve_pending(matcher)?; + #[cfg(feature = "env")] + self.add_env(matcher)?; + self.add_defaults(matcher)?; + Validator::new(self.cmd).validate(parse_state, matcher) + } + + fn match_arg_error( + &self, + arg_os: &clap_lex::ParsedArg<'_>, + valid_arg_found: bool, + trailing_values: bool, + ) -> ClapError { + // If argument follows a `--` + if trailing_values { + // If the arg matches a subcommand name, or any of its aliases (if defined) + if self + .possible_subcommand(arg_os.to_value(), valid_arg_found) + .is_some() + { + return ClapError::unnecessary_double_dash( + self.cmd, + arg_os.display().to_string(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + } + let candidates = suggestions::did_you_mean( + &arg_os.display().to_string(), + self.cmd.all_subcommand_names(), + ); + // If the argument looks like a subcommand. + if !candidates.is_empty() { + let candidates: Vec<_> = candidates + .iter() + .map(|candidate| format!("'{}'", candidate)) + .collect(); + return ClapError::invalid_subcommand( + self.cmd, + arg_os.display().to_string(), + candidates.join(" or "), + self.cmd + .get_bin_name() + .unwrap_or_else(|| self.cmd.get_name()) + .to_owned(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + // If the argument must be a subcommand. + if !self.cmd.has_args() || self.cmd.is_infer_subcommands_set() && self.cmd.has_subcommands() + { + return ClapError::unrecognized_subcommand( + self.cmd, + arg_os.display().to_string(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + ClapError::unknown_argument( + self.cmd, + arg_os.display().to_string(), + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + ) + } + + // Checks if the arg matches a subcommand name, or any of its aliases (if defined) + fn possible_subcommand( + &self, + arg: Result<&str, &RawOsStr>, + valid_arg_found: bool, + ) -> Option<&str> { + debug!("Parser::possible_subcommand: arg={:?}", arg); + let arg = arg.ok()?; + + if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) { + if self.cmd.is_infer_subcommands_set() { + // For subcommand `test`, we accepts it's prefix: `t`, `te`, + // `tes` and `test`. + let v = self + .cmd + .all_subcommand_names() + .filter(|s| s.starts_with(arg)) + .collect::>(); + + if v.len() == 1 { + return Some(v[0]); + } + + // If there is any ambiguity, fallback to non-infer subcommand + // search. + } + if let Some(sc) = self.cmd.find_subcommand(arg) { + return Some(sc.get_name()); + } + } + None + } + + // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined) + fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> { + debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg); + if self.cmd.is_infer_subcommands_set() { + let options = self + .cmd + .get_subcommands() + .fold(Vec::new(), |mut options, sc| { + if let Some(long) = sc.get_long_flag() { + if long.starts_with(arg) { + options.push(long); + } + options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg))) + } + options + }); + if options.len() == 1 { + return Some(options[0]); + } + + for sc in options { + if sc == arg { + return Some(sc); + } + } + } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) { + return Some(sc_name); + } + None + } + + fn parse_help_subcommand( + &self, + cmds: impl Iterator, + ) -> ClapResult { + debug!("Parser::parse_help_subcommand"); + + let mut cmd = self.cmd.clone(); + let sc = { + let mut sc = &mut cmd; + + for cmd in cmds { + sc = if let Some(sc_name) = + sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned()) + { + sc._build_subcommand(&sc_name).unwrap() + } else { + return Err(ClapError::unrecognized_subcommand( + sc, + cmd.to_string_lossy().into_owned(), + Usage::new(sc).create_usage_with_title(&[]), + )); + }; + } + + sc + }; + let parser = Parser::new(sc); + + Err(parser.help_err(true, Stream::Stdout)) + } + + fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool { + #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder + + debug!( + "Parser::is_new_arg: {:?}:{:?}", + next.to_value_os(), + current_positional.name + ); + + if self.cmd.is_allow_hyphen_values_set() + || self.cmd[¤t_positional.id].is_allow_hyphen_values_set() + || (self.cmd.is_allow_negative_numbers_set() && next.is_number()) + { + // If allow hyphen, this isn't a new arg. + debug!("Parser::is_new_arg: Allow hyphen"); + false + } else if next.is_long() { + // If this is a long flag, this is a new arg. + debug!("Parser::is_new_arg: -- found"); + true + } else if next.is_short() { + // If this is a short flag, this is a new arg. But a singe '-' by + // itself is a value and typically means "stdin" on unix systems. + debug!("Parser::is_new_arg: - found"); + true + } else { + // Nothing special, this is a value. + debug!("Parser::is_new_arg: value"); + false + } + } + + fn parse_subcommand( + &mut self, + sc_name: &str, + matcher: &mut ArgMatcher, + raw_args: &mut clap_lex::RawArgs, + args_cursor: clap_lex::ArgCursor, + keep_state: bool, + ) -> ClapResult<()> { + debug!("Parser::parse_subcommand"); + + let partial_parsing_enabled = self.cmd.is_ignore_errors_set(); + + if let Some(sc) = self.cmd._build_subcommand(sc_name) { + let mut sc_matcher = ArgMatcher::new(sc); + + debug!( + "Parser::parse_subcommand: About to parse sc={}", + sc.get_name() + ); + + { + let mut p = Parser::new(sc); + // HACK: maintain indexes between parsers + // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself + if keep_state { + p.cur_idx.set(self.cur_idx.get()); + p.flag_subcmd_at = self.flag_subcmd_at; + p.flag_subcmd_skip = self.flag_subcmd_skip; + } + if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) { + if partial_parsing_enabled { + debug!( + "Parser::parse_subcommand: ignored error in subcommand {}: {:?}", + sc_name, error + ); + } else { + return Err(error); + } + } + } + matcher.subcommand(SubCommand { + id: sc.get_id(), + name: sc.get_name().to_owned(), + matches: sc_matcher.into_inner(), + }); + } + Ok(()) + } + + fn parse_long_arg( + &mut self, + matcher: &mut ArgMatcher, + long_arg: Result<&str, &RawOsStr>, + long_value: Option<&RawOsStr>, + parse_state: &ParseState, + valid_arg_found: &mut bool, + trailing_values: bool, + ) -> ClapResult { + // maybe here lifetime should be 'a + debug!("Parser::parse_long_arg"); + + if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if + self.cmd[opt].is_allow_hyphen_values_set()) + { + return Ok(ParseResult::MaybeHyphenValue); + } + + debug!("Parser::parse_long_arg: Does it contain '='..."); + let long_arg = match long_arg { + Ok(long_arg) => long_arg, + Err(long_arg) => { + return Ok(ParseResult::NoMatchingArg { + arg: long_arg.to_str_lossy().into_owned(), + }); + } + }; + if long_arg.is_empty() { + debug_assert!( + long_value.is_some(), + "`--` should be filtered out before this point" + ); + } + + let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) { + debug!( + "Parser::parse_long_arg: Found valid arg or flag '{}'", + arg.to_string() + ); + Some((long_arg, arg)) + } else if self.cmd.is_infer_long_args_set() { + self.cmd.get_arguments().find_map(|a| { + if let Some(long) = a.long { + if long.starts_with(long_arg) { + return Some((long, a)); + } + } + a.aliases + .iter() + .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (*alias, a))) + }) + } else { + None + }; + + if let Some((_long_arg, arg)) = arg { + let ident = Identifier::Long; + *valid_arg_found = true; + if arg.is_takes_value_set() { + debug!( + "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'", + long_arg, &long_value + ); + let has_eq = long_value.is_some(); + self.parse_opt_value(ident, long_value, arg, matcher, trailing_values, has_eq) + } else if let Some(rest) = long_value { + let required = self.cmd.required_graph(); + debug!( + "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`", + long_arg, rest + ); + let used: Vec = matcher + .arg_ids() + .filter(|arg_id| { + matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) + }) + .filter(|&n| { + self.cmd + .find(n) + .map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id))) + }) + .cloned() + .collect(); + + Ok(ParseResult::UnneededAttachedValue { + rest: rest.to_str_lossy().into_owned(), + used, + arg: arg.to_string(), + }) + } else { + debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg); + self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher) + } + } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) { + Ok(ParseResult::FlagSubCommand(sc_name.to_string())) + } else if self.cmd.is_allow_hyphen_values_set() { + Ok(ParseResult::MaybeHyphenValue) + } else { + Ok(ParseResult::NoMatchingArg { + arg: long_arg.to_owned(), + }) + } + } + + fn parse_short_arg( + &mut self, + matcher: &mut ArgMatcher, + mut short_arg: clap_lex::ShortFlags<'_>, + parse_state: &ParseState, + // change this to possible pos_arg when removing the usage of &mut Parser. + pos_counter: usize, + valid_arg_found: &mut bool, + trailing_values: bool, + ) -> ClapResult { + debug!("Parser::parse_short_arg: short_arg={:?}", short_arg); + + #[allow(clippy::blocks_in_if_conditions)] + if self.cmd.is_allow_negative_numbers_set() && short_arg.is_number() { + debug!("Parser::parse_short_arg: negative number"); + return Ok(ParseResult::MaybeHyphenValue); + } else if self.cmd.is_allow_hyphen_values_set() + && short_arg + .clone() + .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default()) + { + debug!("Parser::parse_short_args: contains non-short flag"); + return Ok(ParseResult::MaybeHyphenValue); + } else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) + if self.cmd[opt].is_allow_hyphen_values_set()) + { + debug!("Parser::parse_short_args: prior arg accepts hyphenated values",); + return Ok(ParseResult::MaybeHyphenValue); + } else if self + .cmd + .get_keymap() + .get(&pos_counter) + .map_or(false, |arg| { + arg.is_allow_hyphen_values_set() && !arg.is_last_set() + }) + { + debug!( + "Parser::parse_short_args: positional at {} allows hyphens", + pos_counter + ); + return Ok(ParseResult::MaybeHyphenValue); + } + + let mut ret = ParseResult::NoArg; + + let skip = self.flag_subcmd_skip; + self.flag_subcmd_skip = 0; + let res = short_arg.advance_by(skip); + debug_assert_eq!( + res, + Ok(()), + "tracking of `flag_subcmd_skip` is off for `{:?}`", + short_arg + ); + while let Some(c) = short_arg.next_flag() { + let c = match c { + Ok(c) => c, + Err(rest) => { + return Ok(ParseResult::NoMatchingArg { + arg: format!("-{}", rest.to_str_lossy()), + }); + } + }; + debug!("Parser::parse_short_arg:iter:{}", c); + + // Check for matching short options, and return the name if there is no trailing + // concatenated value: -oval + // Option: -o + // Value: val + if let Some(arg) = self.cmd.get_keymap().get(&c) { + let ident = Identifier::Short; + debug!( + "Parser::parse_short_arg:iter:{}: Found valid opt or flag", + c + ); + *valid_arg_found = true; + if !arg.is_takes_value_set() { + ret = + self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher)?; + continue; + } + + // Check for trailing concatenated value + // + // Cloning the iterator, so we rollback if it isn't there. + let val = short_arg.clone().next_value_os().unwrap_or_default(); + debug!( + "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}", + c, val, val.as_raw_bytes(), short_arg + ); + let val = Some(val).filter(|v| !v.is_empty()); + + // Default to "we're expecting a value later". + // + // If attached value is not consumed, we may have more short + // flags to parse, continue. + // + // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't + // consume the `vf`, even if it's provided as value. + let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) { + (Some(val), true) + } else { + (val, false) + }; + match self.parse_opt_value(ident, val, arg, matcher, trailing_values, has_eq)? { + ParseResult::AttachedValueNotConsumed => continue, + x => return Ok(x), + } + } + + return if let Some(sc_name) = self.cmd.find_short_subcmd(c) { + debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name); + // Make sure indices get updated before reading `self.cur_idx` + self.resolve_pending(matcher)?; + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get()); + + let name = sc_name.to_string(); + // Get the index of the previously saved flag subcommand in the group of flags (if exists). + // If it is a new flag subcommand, then the formentioned index should be the current one + // (ie. `cur_idx`), and should be registered. + let cur_idx = self.cur_idx.get(); + self.flag_subcmd_at.get_or_insert(cur_idx); + let done_short_args = short_arg.is_empty(); + if done_short_args { + self.flag_subcmd_at = None; + } + Ok(ParseResult::FlagSubCommand(name)) + } else { + Ok(ParseResult::NoMatchingArg { + arg: format!("-{}", c), + }) + }; + } + Ok(ret) + } + + fn parse_opt_value( + &self, + ident: Identifier, + attached_value: Option<&RawOsStr>, + arg: &Arg<'help>, + matcher: &mut ArgMatcher, + trailing_values: bool, + has_eq: bool, + ) -> ClapResult { + debug!( + "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}", + arg.name, attached_value, has_eq + ); + debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings); + + debug!("Parser::parse_opt_value; Checking for val..."); + // require_equals is set, but no '=' is provided, try throwing error. + if arg.is_require_equals_set() && !has_eq { + if arg.min_vals == Some(0) { + debug!("Requires equals, but min_vals == 0"); + let mut arg_values = Vec::new(); + // We assume this case is valid: require equals, but min_vals == 0. + if !arg.default_missing_vals.is_empty() { + debug!("Parser::parse_opt_value: has default_missing_vals"); + for v in arg.default_missing_vals.iter() { + let trailing_values = false; // CLI should not be affecting default_missing_values + let _parse_result = self.split_arg_values( + arg, + &RawOsStr::new(v), + trailing_values, + &mut arg_values, + ); + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::parse_opt_value: Ignoring state {:?}; no values accepted after default_missing_values", _parse_result); + } + } + } + }; + let react_result = self.react( + Some(ident), + ValueSource::CommandLine, + arg, + arg_values, + matcher, + )?; + debug_assert_eq!(react_result, ParseResult::ValuesDone); + if attached_value.is_some() { + Ok(ParseResult::AttachedValueNotConsumed) + } else { + Ok(ParseResult::ValuesDone) + } + } else { + debug!("Requires equals but not provided. Error."); + Ok(ParseResult::EqualsNotProvided { + arg: arg.to_string(), + }) + } + } else if let Some(v) = attached_value { + let mut arg_values = Vec::new(); + let parse_result = self.split_arg_values(arg, v, trailing_values, &mut arg_values); + let react_result = self.react( + Some(ident), + ValueSource::CommandLine, + arg, + arg_values, + matcher, + )?; + debug_assert_eq!(react_result, ParseResult::ValuesDone); + let mut parse_result = parse_result.unwrap_or_else(|| { + if matcher.needs_more_vals(arg) { + ParseResult::Opt(arg.id.clone()) + } else { + ParseResult::ValuesDone + } + }); + if parse_result != ParseResult::ValuesDone { + debug!("Parser::parse_opt_value: Overriding state {:?}; no values accepted after attached", parse_result); + parse_result = ParseResult::ValuesDone; + } + Ok(parse_result) + } else { + debug!("Parser::parse_opt_value: More arg vals required..."); + self.resolve_pending(matcher)?; + matcher.pending_values_mut(&arg.id, Some(ident)); + Ok(ParseResult::Opt(arg.id.clone())) + } + } + + fn split_arg_values( + &self, + arg: &Arg<'help>, + val: &RawOsStr, + trailing_values: bool, + output: &mut Vec, + ) -> Option { + debug!("Parser::split_arg_values; arg={}, val={:?}", arg.name, val); + debug!( + "Parser::split_arg_values; trailing_values={:?}, DontDelimTrailingVals={:?}", + trailing_values, + self.cmd.is_dont_delimit_trailing_values_set() + ); + + let mut delim = arg.val_delim; + if trailing_values && self.cmd.is_dont_delimit_trailing_values_set() { + delim = None; + } + match delim { + Some(delim) if val.contains(delim) => { + let vals = val.split(delim).map(|x| x.to_os_str().into_owned()); + for raw_val in vals { + if Some(raw_val.as_os_str()) == arg.terminator.map(OsStr::new) { + return Some(ParseResult::ValuesDone); + } + output.push(raw_val); + } + // Delimited values are always considered the final value + Some(ParseResult::ValuesDone) + } + _ if Some(val) == arg.terminator.map(RawOsStr::from_str) => { + Some(ParseResult::ValuesDone) + } + _ => { + output.push(val.to_os_str().into_owned()); + if arg.is_require_value_delimiter_set() { + Some(ParseResult::ValuesDone) + } else { + None + } + } + } + } + + fn push_arg_values( + &self, + arg: &Arg<'help>, + raw_vals: Vec, + matcher: &mut ArgMatcher, + ) -> ClapResult<()> { + debug!("Parser::push_arg_values: {:?}", raw_vals); + + for raw_val in raw_vals { + // update the current index because each value is a distinct index to clap + self.cur_idx.set(self.cur_idx.get() + 1); + debug!( + "Parser::add_single_val_to_arg: cur_idx:={}", + self.cur_idx.get() + ); + let value_parser = arg.get_value_parser(); + let val = value_parser.parse_ref(self.cmd, Some(arg), &raw_val)?; + + // Increment or create the group "args" + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.add_val_to(&group, val.clone(), raw_val.clone()); + } + + matcher.add_val_to(&arg.id, val, raw_val); + matcher.add_index_to(&arg.id, self.cur_idx.get()); + } + + Ok(()) + } + + fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { + let pending = match matcher.take_pending() { + Some(pending) => pending, + None => { + return Ok(()); + } + }; + + debug!("Parser::resolve_pending: id={:?}", pending.id); + let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG); + let _ = self.react( + pending.ident, + ValueSource::CommandLine, + arg, + pending.raw_vals, + matcher, + )?; + + Ok(()) + } + + fn react( + &self, + ident: Option, + source: ValueSource, + arg: &Arg<'help>, + raw_vals: Vec, + matcher: &mut ArgMatcher, + ) -> ClapResult { + self.resolve_pending(matcher)?; + + debug!( + "Parser::react action={:?}, identifier={:?}, source={:?}", + arg.get_action(), + ident, + source + ); + match arg.get_action() { + ArgAction::Set => { + if source == ValueSource::CommandLine + && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) + { + // Record flag's index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); + } + matcher.remove(&arg.id); + self.start_custom_arg(matcher, arg, source); + self.push_arg_values(arg, raw_vals, matcher)?; + if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { + debug!( + "Parser::react not enough values passed in, leaving it to the validator to complain", + ); + } + Ok(ParseResult::ValuesDone) + } + ArgAction::Append => { + if source == ValueSource::CommandLine + && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) + { + // Record flag's index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); + } + self.start_custom_arg(matcher, arg, source); + self.push_arg_values(arg, raw_vals, matcher)?; + if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { + debug!( + "Parser::react not enough values passed in, leaving it to the validator to complain", + ); + } + Ok(ParseResult::ValuesDone) + } + #[allow(deprecated)] + ArgAction::StoreValue => { + if ident == Some(Identifier::Index) + && arg.is_multiple_values_set() + && matcher.contains(&arg.id) + { + // HACK: Reuse existing occurrence + } else if source == ValueSource::CommandLine { + if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) { + // Record flag's index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); + } + self.start_occurrence_of_arg(matcher, arg); + } else { + self.start_custom_arg(matcher, arg, source); + } + self.push_arg_values(arg, raw_vals, matcher)?; + if ident == Some(Identifier::Index) && arg.is_multiple_values_set() { + // HACK: Maintain existing occurrence behavior + let matched = matcher.get_mut(&arg.id).unwrap(); + #[allow(deprecated)] + matched.set_occurrences(matched.num_vals() as u64); + } + if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { + debug!( + "Parser::react not enough values passed in, leaving it to the validator to complain", + ); + } + Ok(ParseResult::ValuesDone) + } + #[allow(deprecated)] + ArgAction::IncOccurrence => { + debug_assert_eq!(raw_vals, Vec::::new()); + if source == ValueSource::CommandLine { + if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) { + // Record flag's index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); + } + self.start_occurrence_of_arg(matcher, arg); + } else { + self.start_custom_arg(matcher, arg, source); + } + matcher.add_index_to(&arg.id, self.cur_idx.get()); + Ok(ParseResult::ValuesDone) + } + ArgAction::SetTrue => { + let raw_vals = match raw_vals.len() { + 0 => { + vec![OsString::from("true")] + } + 1 => raw_vals, + _ => { + debug!("Parser::react ignoring trailing values: {:?}", raw_vals); + let mut raw_vals = raw_vals; + raw_vals.resize(1, Default::default()); + raw_vals + } + }; + + matcher.remove(&arg.id); + self.start_custom_arg(matcher, arg, source); + self.push_arg_values(arg, raw_vals, matcher)?; + Ok(ParseResult::ValuesDone) + } + ArgAction::SetFalse => { + let raw_vals = match raw_vals.len() { + 0 => { + vec![OsString::from("false")] + } + 1 => raw_vals, + _ => { + debug!("Parser::react ignoring trailing values: {:?}", raw_vals); + let mut raw_vals = raw_vals; + raw_vals.resize(1, Default::default()); + raw_vals + } + }; + + matcher.remove(&arg.id); + self.start_custom_arg(matcher, arg, source); + self.push_arg_values(arg, raw_vals, matcher)?; + Ok(ParseResult::ValuesDone) + } + ArgAction::Count => { + let raw_vals = match raw_vals.len() { + 0 => { + let existing_value = *matcher + .get_one::(arg.get_id()) + .unwrap_or(&0); + let next_value = existing_value.saturating_add(1); + vec![OsString::from(next_value.to_string())] + } + 1 => raw_vals, + _ => { + debug!("Parser::react ignoring trailing values: {:?}", raw_vals); + let mut raw_vals = raw_vals; + raw_vals.resize(1, Default::default()); + raw_vals + } + }; + + matcher.remove(&arg.id); + self.start_custom_arg(matcher, arg, source); + self.push_arg_values(arg, raw_vals, matcher)?; + Ok(ParseResult::ValuesDone) + } + ArgAction::Help => { + debug_assert_eq!(raw_vals, Vec::::new()); + let use_long = match ident { + Some(Identifier::Long) => true, + Some(Identifier::Short) => false, + Some(Identifier::Index) => true, + None => true, + }; + debug!("Help: use_long={}", use_long); + Err(self.help_err(use_long, Stream::Stdout)) + } + ArgAction::Version => { + debug_assert_eq!(raw_vals, Vec::::new()); + let use_long = match ident { + Some(Identifier::Long) => true, + Some(Identifier::Short) => false, + Some(Identifier::Index) => true, + None => true, + }; + debug!("Version: use_long={}", use_long); + Err(self.version_err(use_long)) + } + } + } + + fn remove_overrides(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) { + debug!("Parser::remove_overrides: id={:?}", arg.id); + for override_id in &arg.overrides { + debug!("Parser::remove_overrides:iter:{:?}: removing", override_id); + matcher.remove(override_id); + } + + // Override anything that can override us + let mut transitive = Vec::new(); + for arg_id in matcher.arg_ids() { + if let Some(overrider) = self.cmd.find(arg_id) { + if overrider.overrides.contains(&arg.id) { + transitive.push(&overrider.id); + } + } + } + for overrider_id in transitive { + debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id); + matcher.remove(overrider_id); + } + } + + #[cfg(feature = "env")] + fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> { + debug!("Parser::add_env"); + use crate::util::str_to_bool; + + let trailing_values = false; // defaults are independent of the commandline + for arg in self.cmd.get_arguments() { + // Use env only if the arg was absent among command line args, + // early return if this is not the case. + if matcher.contains(&arg.id) { + debug!("Parser::add_env: Skipping existing arg `{}`", arg); + continue; + } + + debug!("Parser::add_env: Checking arg `{}`", arg); + if let Some((_, Some(ref val))) = arg.env { + let val = RawOsStr::new(val); + + if arg.is_takes_value_set() { + debug!( + "Parser::add_env: Found an opt with value={:?}, trailing={:?}", + val, trailing_values + ); + let mut arg_values = Vec::new(); + let _parse_result = + self.split_arg_values(arg, &val, trailing_values, &mut arg_values); + let _ = self.react(None, ValueSource::EnvVariable, arg, arg_values, matcher)?; + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result); + } + } + } else { + match arg.get_action() { + #[allow(deprecated)] + ArgAction::StoreValue => unreachable!("{:?} is not a flag", arg.get_id()), + #[allow(deprecated)] + ArgAction::IncOccurrence => { + debug!("Parser::add_env: Found a flag with value `{:?}`", val); + let predicate = str_to_bool(val.to_str_lossy()); + debug!("Parser::add_env: Found boolean literal `{:?}`", predicate); + if predicate.unwrap_or(true) { + let _ = self.react( + None, + ValueSource::EnvVariable, + arg, + vec![], + matcher, + )?; + } + } + ArgAction::Set + | ArgAction::Append + | ArgAction::SetTrue + | ArgAction::SetFalse + | ArgAction::Count => { + let mut arg_values = Vec::new(); + let _parse_result = + self.split_arg_values(arg, &val, trailing_values, &mut arg_values); + let _ = self.react( + None, + ValueSource::EnvVariable, + arg, + arg_values, + matcher, + )?; + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result); + } + } + } + // Early return on `Help` or `Version`. + ArgAction::Help | ArgAction::Version => { + let _ = + self.react(None, ValueSource::EnvVariable, arg, vec![], matcher)?; + } + } + } + } + } + + Ok(()) + } + + fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { + debug!("Parser::add_defaults"); + + for arg in self.cmd.get_arguments() { + debug!("Parser::add_defaults:iter:{}:", arg.name); + self.add_default_value(arg, matcher)?; + } + + Ok(()) + } + + fn add_default_value(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) -> ClapResult<()> { + let trailing_values = false; // defaults are independent of the commandline + + if !arg.default_missing_vals.is_empty() { + debug!( + "Parser::add_default_value:iter:{}: has default missing vals", + arg.name + ); + match matcher.get(&arg.id) { + Some(ma) if ma.all_val_groups_empty() => { + debug!( + "Parser::add_default_value:iter:{}: has no user defined vals", + arg.name + ); + // The flag occurred, we just want to add the val groups + let mut arg_values = Vec::new(); + for v in arg.default_missing_vals.iter() { + let _parse_result = self.split_arg_values( + arg, + &RawOsStr::new(v), + trailing_values, + &mut arg_values, + ); + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); + } + } + } + self.start_custom_arg(matcher, arg, ValueSource::CommandLine); + self.push_arg_values(arg, arg_values, matcher)?; + } + None => { + debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name); + // do nothing + } + _ => { + debug!( + "Parser::add_default_value:iter:{}: has user defined vals", + arg.name + ); + // do nothing + } + } + } else { + debug!( + "Parser::add_default_value:iter:{}: doesn't have default missing vals", + arg.name + ); + // do nothing + } + + if !arg.default_vals_ifs.is_empty() { + debug!("Parser::add_default_value: has conditional defaults"); + if !matcher.contains(&arg.id) { + for (id, val, default) in arg.default_vals_ifs.iter() { + let add = if let Some(a) = matcher.get(id) { + match val { + crate::builder::ArgPredicate::Equals(v) => { + a.raw_vals_flatten().any(|value| v == value) + } + crate::builder::ArgPredicate::IsPresent => true, + } + } else { + false + }; + + if add { + if let Some(default) = default { + let mut arg_values = Vec::new(); + let _parse_result = self.split_arg_values( + arg, + &RawOsStr::new(default), + trailing_values, + &mut arg_values, + ); + let _ = self.react( + None, + ValueSource::DefaultValue, + arg, + arg_values, + matcher, + )?; + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); + } + } + } + return Ok(()); + } + } + } + } else { + debug!("Parser::add_default_value: doesn't have conditional defaults"); + } + + if !arg.default_vals.is_empty() { + debug!( + "Parser::add_default_value:iter:{}: has default vals", + arg.name + ); + if matcher.contains(&arg.id) { + debug!("Parser::add_default_value:iter:{}: was used", arg.name); + // do nothing + } else { + debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name); + let mut arg_values = Vec::new(); + for v in arg.default_vals.iter() { + let _parse_result = self.split_arg_values( + arg, + &RawOsStr::new(v), + trailing_values, + &mut arg_values, + ); + if let Some(_parse_result) = _parse_result { + if _parse_result != ParseResult::ValuesDone { + debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result); + } + } + } + let _ = self.react(None, ValueSource::DefaultValue, arg, arg_values, matcher)?; + } + } else { + debug!( + "Parser::add_default_value:iter:{}: doesn't have default vals", + arg.name + ); + + // do nothing + } + + Ok(()) + } + + fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>, source: ValueSource) { + if source == ValueSource::CommandLine { + // With each new occurrence, remove overrides from prior occurrences + self.remove_overrides(arg, matcher); + } + matcher.start_custom_arg(arg, source); + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.start_custom_group(&group, source); + } + } + + /// Increase occurrence of specific argument and the grouped arg it's in. + fn start_occurrence_of_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) { + // With each new occurrence, remove overrides from prior occurrences + self.remove_overrides(arg, matcher); + + matcher.start_occurrence_of_arg(arg); + // Increment or create the group "args" + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.start_occurrence_of_group(&group); + } + } +} + +// Error, Help, and Version Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + /// Is only used for the long flag(which is the only one needs fuzzy searching) + fn did_you_mean_error( + &mut self, + arg: &str, + matcher: &mut ArgMatcher, + remaining_args: &[&str], + ) -> ClapError { + debug!("Parser::did_you_mean_error: arg={}", arg); + // Didn't match a flag or option + let longs = self + .cmd + .get_keymap() + .keys() + .filter_map(|x| match x { + KeyType::Long(l) => Some(l.to_string_lossy().into_owned()), + _ => None, + }) + .collect::>(); + debug!("Parser::did_you_mean_error: longs={:?}", longs); + + let did_you_mean = suggestions::did_you_mean_flag( + arg, + remaining_args, + longs.iter().map(|x| &x[..]), + self.cmd.get_subcommands_mut(), + ); + + // Add the arg to the matches to build a proper usage string + if let Some((name, _)) = did_you_mean.as_ref() { + if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) { + self.start_occurrence_of_arg(matcher, arg); + } + } + + let required = self.cmd.required_graph(); + let used: Vec = matcher + .arg_ids() + .filter(|arg_id| { + matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) + }) + .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set())) + .cloned() + .collect(); + + ClapError::unknown_argument( + self.cmd, + format!("--{}", arg), + did_you_mean, + Usage::new(self.cmd) + .required(&required) + .create_usage_with_title(&*used), + ) + } + + fn help_err(&self, use_long: bool, stream: Stream) -> ClapError { + match self.cmd.write_help_err(use_long, stream) { + Ok(c) => ClapError::display_help(self.cmd, c), + Err(e) => e, + } + } + + fn version_err(&self, use_long: bool) -> ClapError { + debug!("Parser::version_err"); + + let msg = self.cmd._render_version(use_long); + let mut c = Colorizer::new(Stream::Stdout, self.cmd.color_help()); + c.none(msg); + ClapError::display_version(self.cmd, c) + } +} + +// Query Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + pub(crate) fn is_set(&self, s: AS) -> bool { + self.cmd.is_set(s) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum ParseState { + ValuesDone, + Opt(Id), + Pos(Id), +} + +/// Recoverable Parsing results. +#[derive(Debug, PartialEq, Clone)] +#[must_use] +enum ParseResult { + FlagSubCommand(String), + Opt(Id), + ValuesDone, + /// Value attached to the short flag is not consumed(e.g. 'u' for `-cu` is + /// not consumed). + AttachedValueNotConsumed, + /// This long flag doesn't need a value but is provided one. + UnneededAttachedValue { + rest: String, + used: Vec, + arg: String, + }, + /// This flag might be an hyphen Value. + MaybeHyphenValue, + /// Equals required but not provided. + EqualsNotProvided { + arg: String, + }, + /// Failed to match a Arg. + NoMatchingArg { + arg: String, + }, + /// No argument found e.g. parser is given `-` when parsing a flag. + NoArg, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PendingArg { + pub(crate) id: Id, + pub(crate) ident: Option, + pub(crate) raw_vals: Vec, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Identifier { + Short, + Long, + Index, +} diff --git a/vendor/clap-3.2.20/src/parser/validator.rs b/vendor/clap-3.2.20/src/parser/validator.rs new file mode 100644 index 000000000..ebf2b234d --- /dev/null +++ b/vendor/clap-3.2.20/src/parser/validator.rs @@ -0,0 +1,692 @@ +// Internal +use crate::builder::{AppSettings, Arg, ArgPredicate, Command, PossibleValue}; +use crate::error::{Error, Result as ClapResult}; +use crate::output::fmt::Stream; +use crate::output::Usage; +use crate::parser::{ArgMatcher, MatchedArg, ParseState}; +use crate::util::ChildGraph; +use crate::util::Id; +use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; + +pub(crate) struct Validator<'help, 'cmd> { + cmd: &'cmd Command<'help>, + required: ChildGraph, +} + +impl<'help, 'cmd> Validator<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { + let required = cmd.required_graph(); + Validator { cmd, required } + } + + pub(crate) fn validate( + &mut self, + parse_state: ParseState, + matcher: &mut ArgMatcher, + ) -> ClapResult<()> { + debug!("Validator::validate"); + let mut conflicts = Conflicts::new(); + let has_subcmd = matcher.subcommand_name().is_some(); + + if let ParseState::Opt(a) = parse_state { + debug!("Validator::validate: needs_val_of={:?}", a); + + let o = &self.cmd[&a]; + let should_err = if let Some(v) = matcher.args.get(&o.id) { + v.all_val_groups_empty() && !(o.min_vals.is_some() && o.min_vals.unwrap() == 0) + } else { + true + }; + if should_err { + return Err(Error::empty_value( + self.cmd, + &get_possible_values(o) + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::>(), + o.to_string(), + )); + } + } + + if !has_subcmd && self.cmd.is_arg_required_else_help_set() { + let num_user_values = matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .count(); + if num_user_values == 0 { + let message = self.cmd.write_help_err(false, Stream::Stderr)?; + return Err(Error::display_help_error(self.cmd, message)); + } + } + #[allow(deprecated)] + if !has_subcmd && self.cmd.is_subcommand_required_set() { + let bn = self + .cmd + .get_bin_name() + .unwrap_or_else(|| self.cmd.get_name()); + return Err(Error::missing_subcommand( + self.cmd, + bn.to_string(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } else if !has_subcmd && self.cmd.is_set(AppSettings::SubcommandRequiredElseHelp) { + debug!("Validator::new::get_matches_with: SubcommandRequiredElseHelp=true"); + let message = self.cmd.write_help_err(false, Stream::Stderr)?; + return Err(Error::display_help_error(self.cmd, message)); + } + + self.validate_conflicts(matcher, &mut conflicts)?; + if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) { + self.validate_required(matcher, &mut conflicts)?; + } + self.validate_matched_args(matcher)?; + + Ok(()) + } + + fn validate_arg_values(&self, arg: &Arg, ma: &MatchedArg) -> ClapResult<()> { + debug!("Validator::validate_arg_values: arg={:?}", arg.name); + for val in ma.raw_vals_flatten() { + if !arg.possible_vals.is_empty() { + debug!( + "Validator::validate_arg_values: possible_vals={:?}", + arg.possible_vals + ); + let val_str = val.to_string_lossy(); + let ok = arg + .possible_vals + .iter() + .any(|pv| pv.matches(&val_str, arg.is_ignore_case_set())); + if !ok { + return Err(Error::invalid_value( + self.cmd, + val_str.into_owned(), + &arg.possible_vals + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::>(), + arg.to_string(), + )); + } + } + { + #![allow(deprecated)] + if arg.is_forbid_empty_values_set() && val.is_empty() { + debug!("Validator::validate_arg_values: illegal empty val found"); + return Err(Error::empty_value( + self.cmd, + &get_possible_values(arg) + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::>(), + arg.to_string(), + )); + } + } + + if let Some(ref vtor) = arg.validator { + debug!("Validator::validate_arg_values: checking validator..."); + let mut vtor = vtor.lock().unwrap(); + if let Err(e) = vtor(&*val.to_string_lossy()) { + debug!("error"); + return Err(Error::value_validation( + arg.to_string(), + val.to_string_lossy().into_owned(), + e, + ) + .with_cmd(self.cmd)); + } else { + debug!("good"); + } + } + if let Some(ref vtor) = arg.validator_os { + debug!("Validator::validate_arg_values: checking validator_os..."); + let mut vtor = vtor.lock().unwrap(); + if let Err(e) = vtor(val) { + debug!("error"); + return Err(Error::value_validation( + arg.to_string(), + val.to_string_lossy().into(), + e, + ) + .with_cmd(self.cmd)); + } else { + debug!("good"); + } + } + } + Ok(()) + } + + fn validate_conflicts( + &mut self, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> ClapResult<()> { + debug!("Validator::validate_conflicts"); + + self.validate_exclusive(matcher)?; + + for arg_id in matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|arg_id| self.cmd.find(arg_id).is_some()) + { + debug!("Validator::validate_conflicts::iter: id={:?}", arg_id); + let conflicts = conflicts.gather_conflicts(self.cmd, matcher, arg_id); + self.build_conflict_err(arg_id, &conflicts, matcher)?; + } + + Ok(()) + } + + fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_exclusive"); + let args_count = matcher + .arg_ids() + .filter(|arg_id| { + matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) + }) + .count(); + if args_count <= 1 { + // Nothing present to conflict with + return Ok(()); + } + + matcher + .arg_ids() + .filter(|arg_id| { + matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent) + }) + .filter_map(|name| { + debug!("Validator::validate_exclusive:iter:{:?}", name); + self.cmd + .find(name) + // Find `arg`s which are exclusive but also appear with other args. + .filter(|&arg| arg.is_exclusive_set() && args_count > 1) + }) + // Throw an error for the first conflict found. + .try_for_each(|arg| { + Err(Error::argument_conflict( + self.cmd, + arg.to_string(), + Vec::new(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )) + }) + } + + fn build_conflict_err( + &self, + name: &Id, + conflict_ids: &[Id], + matcher: &ArgMatcher, + ) -> ClapResult<()> { + if conflict_ids.is_empty() { + return Ok(()); + } + + debug!("Validator::build_conflict_err: name={:?}", name); + let mut seen = std::collections::HashSet::new(); + let conflicts = conflict_ids + .iter() + .flat_map(|c_id| { + if self.cmd.find_group(c_id).is_some() { + self.cmd.unroll_args_in_group(c_id) + } else { + vec![c_id.clone()] + } + }) + .filter_map(|c_id| { + seen.insert(c_id.clone()).then(|| { + let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG); + c_arg.to_string() + }) + }) + .collect(); + + let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG); + let usg = self.build_conflict_err_usage(matcher, conflict_ids); + Err(Error::argument_conflict( + self.cmd, + former_arg.to_string(), + conflicts, + usg, + )) + } + + fn build_conflict_err_usage(&self, matcher: &ArgMatcher, conflicting_keys: &[Id]) -> String { + let used_filtered: Vec = matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|n| { + // Filter out the args we don't want to specify. + self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) + }) + .filter(|key| !conflicting_keys.contains(key)) + .cloned() + .collect(); + let required: Vec = used_filtered + .iter() + .filter_map(|key| self.cmd.find(key)) + .flat_map(|arg| arg.requires.iter().map(|item| &item.1)) + .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key)) + .chain(used_filtered.iter()) + .cloned() + .collect(); + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&required) + } + + fn gather_requires(&mut self, matcher: &ArgMatcher) { + debug!("Validator::gather_requires"); + for name in matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + { + debug!("Validator::gather_requires:iter:{:?}", name); + if let Some(arg) = self.cmd.find(name) { + let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option { + let required = matcher.check_explicit(&arg.id, *val); + required.then(|| req_arg.clone()) + }; + + for req in self.cmd.unroll_arg_requires(is_relevant, &arg.id) { + self.required.insert(req); + } + } else if let Some(g) = self.cmd.find_group(name) { + debug!("Validator::gather_requires:iter:{:?}:group", name); + for r in &g.requires { + self.required.insert(r.clone()); + } + } + } + } + + fn validate_matched_args(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_matched_args"); + matcher.iter().try_for_each(|(name, ma)| { + debug!( + "Validator::validate_matched_args:iter:{:?}: vals={:#?}", + name, + ma.vals_flatten() + ); + if let Some(arg) = self.cmd.find(name) { + self.validate_arg_num_vals(arg, ma)?; + self.validate_arg_values(arg, ma)?; + self.validate_arg_num_occurs(arg, ma)?; + } + Ok(()) + }) + } + + fn validate_arg_num_occurs(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { + #![allow(deprecated)] + debug!( + "Validator::validate_arg_num_occurs: {:?}={}", + a.name, + ma.get_occurrences() + ); + // Occurrence of positional argument equals to number of values rather + // than number of grouped values. + if ma.get_occurrences() > 1 && !a.is_multiple_occurrences_set() && !a.is_positional() { + // Not the first time, and we don't allow multiples + return Err(Error::unexpected_multiple_usage( + self.cmd, + a.to_string(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + if let Some(max_occurs) = a.max_occurs { + debug!( + "Validator::validate_arg_num_occurs: max_occurs set...{}", + max_occurs + ); + let occurs = ma.get_occurrences() as usize; + if occurs > max_occurs { + return Err(Error::too_many_occurrences( + self.cmd, + a.to_string(), + max_occurs, + occurs, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + + Ok(()) + } + + fn validate_arg_num_vals(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { + debug!("Validator::validate_arg_num_vals"); + if let Some(num) = a.num_vals { + let total_num = ma.num_vals(); + debug!("Validator::validate_arg_num_vals: num_vals set...{}", num); + #[allow(deprecated)] + let should_err = if a.is_multiple_occurrences_set() { + total_num % num != 0 + } else { + num != total_num + }; + if should_err { + debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); + return Err(Error::wrong_number_of_values( + self.cmd, + a.to_string(), + num, + #[allow(deprecated)] + if a.is_multiple_occurrences_set() { + total_num % num + } else { + total_num + }, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + if let Some(num) = a.max_vals { + debug!("Validator::validate_arg_num_vals: max_vals set...{}", num); + if ma.num_vals() > num { + debug!("Validator::validate_arg_num_vals: Sending error TooManyValues"); + return Err(Error::too_many_values( + self.cmd, + ma.raw_vals_flatten() + .last() + .expect(INTERNAL_ERROR_MSG) + .to_str() + .expect(INVALID_UTF8) + .to_string(), + a.to_string(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + let min_vals_zero = if let Some(num) = a.min_vals { + debug!("Validator::validate_arg_num_vals: min_vals set: {}", num); + if ma.num_vals() < num && num != 0 { + debug!("Validator::validate_arg_num_vals: Sending error TooFewValues"); + return Err(Error::too_few_values( + self.cmd, + a.to_string(), + num, + ma.num_vals(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + num == 0 + } else { + false + }; + // Issue 665 (https://github.com/clap-rs/clap/issues/665) + // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) + if a.is_takes_value_set() && !min_vals_zero && ma.all_val_groups_empty() { + return Err(Error::empty_value( + self.cmd, + &get_possible_values(a) + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::>(), + a.to_string(), + )); + } + Ok(()) + } + + fn validate_required( + &mut self, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> ClapResult<()> { + debug!("Validator::validate_required: required={:?}", self.required); + self.gather_requires(matcher); + + let is_exclusive_present = matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .any(|id| { + self.cmd + .find(id) + .map(|arg| arg.is_exclusive_set()) + .unwrap_or_default() + }); + debug!( + "Validator::validate_required: is_exclusive_present={}", + is_exclusive_present + ); + + for arg_or_group in self + .required + .iter() + .filter(|r| !matcher.check_explicit(r, ArgPredicate::IsPresent)) + { + debug!("Validator::validate_required:iter:aog={:?}", arg_or_group); + if let Some(arg) = self.cmd.find(arg_or_group) { + debug!("Validator::validate_required:iter: This is an arg"); + if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) { + return self.missing_required_error(matcher, vec![]); + } + } else if let Some(group) = self.cmd.find_group(arg_or_group) { + debug!("Validator::validate_required:iter: This is a group"); + if !self + .cmd + .unroll_args_in_group(&group.id) + .iter() + .any(|a| matcher.check_explicit(a, ArgPredicate::IsPresent)) + { + return self.missing_required_error(matcher, vec![]); + } + } + } + + // Validate the conditionally required args + for a in self.cmd.get_arguments() { + for (other, val) in &a.r_ifs { + if matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) + && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) + { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + + let match_all = a.r_ifs_all.iter().all(|(other, val)| { + matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) + }); + if match_all + && !a.r_ifs_all.is_empty() + && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) + { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + + self.validate_required_unless(matcher)?; + + Ok(()) + } + + fn is_missing_required_ok( + &self, + a: &Arg<'help>, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> bool { + debug!("Validator::is_missing_required_ok: {}", a.name); + let conflicts = conflicts.gather_conflicts(self.cmd, matcher, &a.id); + !conflicts.is_empty() + } + + fn validate_required_unless(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_required_unless"); + let failed_args: Vec<_> = self + .cmd + .get_arguments() + .filter(|&a| { + (!a.r_unless.is_empty() || !a.r_unless_all.is_empty()) + && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent) + && self.fails_arg_required_unless(a, matcher) + }) + .map(|a| a.id.clone()) + .collect(); + if failed_args.is_empty() { + Ok(()) + } else { + self.missing_required_error(matcher, failed_args) + } + } + + // Failing a required unless means, the arg's "unless" wasn't present, and neither were they + fn fails_arg_required_unless(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool { + debug!("Validator::fails_arg_required_unless: a={:?}", a.name); + let exists = |id| matcher.check_explicit(id, ArgPredicate::IsPresent); + + (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists)) + && !a.r_unless.iter().any(exists) + } + + // `incl`: an arg to include in the error even if not used + fn missing_required_error(&self, matcher: &ArgMatcher, incl: Vec) -> ClapResult<()> { + debug!("Validator::missing_required_error; incl={:?}", incl); + debug!( + "Validator::missing_required_error: reqs={:?}", + self.required + ); + + let usg = Usage::new(self.cmd).required(&self.required); + + let req_args = usg + .get_required_usage_from(&incl, Some(matcher), true) + .into_iter() + .collect::>(); + + debug!( + "Validator::missing_required_error: req_args={:#?}", + req_args + ); + + let used: Vec = matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|n| { + // Filter out the args we don't want to specify. + self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) + }) + .cloned() + .chain(incl) + .collect(); + + Err(Error::missing_required_argument( + self.cmd, + req_args, + usg.create_usage_with_title(&used), + )) + } +} + +#[derive(Default, Clone, Debug)] +struct Conflicts { + potential: std::collections::HashMap>, +} + +impl Conflicts { + fn new() -> Self { + Self::default() + } + + fn gather_conflicts(&mut self, cmd: &Command, matcher: &ArgMatcher, arg_id: &Id) -> Vec { + debug!("Conflicts::gather_conflicts: arg={:?}", arg_id); + let mut conflicts = Vec::new(); + for other_arg_id in matcher + .arg_ids() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + { + if arg_id == other_arg_id { + continue; + } + + if self + .gather_direct_conflicts(cmd, arg_id) + .contains(other_arg_id) + { + conflicts.push(other_arg_id.clone()); + } + if self + .gather_direct_conflicts(cmd, other_arg_id) + .contains(arg_id) + { + conflicts.push(other_arg_id.clone()); + } + } + debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts); + conflicts + } + + fn gather_direct_conflicts(&mut self, cmd: &Command, arg_id: &Id) -> &[Id] { + self.potential.entry(arg_id.clone()).or_insert_with(|| { + let conf = if let Some(arg) = cmd.find(arg_id) { + let mut conf = arg.blacklist.clone(); + for group_id in cmd.groups_for_arg(arg_id) { + let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG); + conf.extend(group.conflicts.iter().cloned()); + if !group.multiple { + for member_id in &group.args { + if member_id != arg_id { + conf.push(member_id.clone()); + } + } + } + } + + // Overrides are implicitly conflicts + conf.extend(arg.overrides.iter().cloned()); + + conf + } else if let Some(group) = cmd.find_group(arg_id) { + group.conflicts.clone() + } else { + debug_assert!(false, "id={:?} is unknown", arg_id); + Vec::new() + }; + debug!( + "Conflicts::gather_direct_conflicts id={:?}, conflicts={:?}", + arg_id, conf + ); + conf + }) + } +} + +fn get_possible_values<'help>(a: &Arg<'help>) -> Vec> { + #![allow(deprecated)] + if !a.is_takes_value_set() { + vec![] + } else if let Some(pvs) = a.get_possible_values() { + // Check old first in case the user explicitly set possible values and the derive inferred + // a `ValueParser` with some. + pvs.to_vec() + } else { + a.get_value_parser() + .possible_values() + .map(|pvs| pvs.collect()) + .unwrap_or_default() + } +} diff --git a/vendor/clap-3.2.20/src/util/color.rs b/vendor/clap-3.2.20/src/util/color.rs new file mode 100644 index 000000000..15c9901a0 --- /dev/null +++ b/vendor/clap-3.2.20/src/util/color.rs @@ -0,0 +1,62 @@ +/// Represents the color preferences for program output +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ColorChoice { + /// Enables colored output only when the output is going to a terminal or TTY. + /// + /// **NOTE:** This is the default behavior of `clap`. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Auto) + /// .get_matches(); + /// ``` + Auto, + + /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Always) + /// .get_matches(); + /// ``` + Always, + + /// Disables colored output no matter if the output is going to a terminal/TTY, or not. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Never) + /// .get_matches(); + /// ``` + Never, +} + +impl Default for ColorChoice { + fn default() -> Self { + Self::Auto + } +} diff --git a/vendor/clap-3.2.20/src/util/fnv.rs b/vendor/clap-3.2.20/src/util/fnv.rs new file mode 100644 index 000000000..4602300a4 --- /dev/null +++ b/vendor/clap-3.2.20/src/util/fnv.rs @@ -0,0 +1,46 @@ +use std::{ + fmt::Display, + hash::{Hash, Hasher}, +}; + +const MAGIC_INIT: u64 = 0x811C_9DC5; + +// TODO: Docs +pub trait Key: Hash + Display { + fn key(&self) -> u64; +} + +impl Key for T +where + T: Hash + Display, +{ + fn key(&self) -> u64 { + let mut hasher = FnvHasher::new(); + self.hash(&mut hasher); + hasher.finish() + } +} + +pub(crate) struct FnvHasher(u64); + +impl FnvHasher { + pub(crate) fn new() -> Self { + FnvHasher(MAGIC_INIT) + } +} + +impl Hasher for FnvHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + let FnvHasher(mut hash) = *self; + + for byte in bytes.iter() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0100_0000_01b3); + } + + *self = FnvHasher(hash); + } +} diff --git a/vendor/clap-3.2.20/src/util/graph.rs b/vendor/clap-3.2.20/src/util/graph.rs new file mode 100644 index 000000000..d646400b0 --- /dev/null +++ b/vendor/clap-3.2.20/src/util/graph.rs @@ -0,0 +1,49 @@ +#[derive(Debug)] +struct Child { + id: T, + children: Vec, +} + +impl Child { + fn new(id: T) -> Self { + Child { + id, + children: vec![], + } + } +} + +#[derive(Debug)] +pub(crate) struct ChildGraph(Vec>); + +impl ChildGraph +where + T: Sized + PartialEq + Clone, +{ + pub(crate) fn with_capacity(s: usize) -> Self { + ChildGraph(Vec::with_capacity(s)) + } + + pub(crate) fn insert(&mut self, req: T) -> usize { + self.0.iter().position(|e| e.id == req).unwrap_or_else(|| { + let idx = self.0.len(); + self.0.push(Child::new(req)); + idx + }) + } + + pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize { + let c_idx = self.0.len(); + self.0.push(Child::new(child)); + self.0[parent].children.push(c_idx); + c_idx + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.0.iter().map(|r| &r.id) + } + + pub(crate) fn contains(&self, req: &T) -> bool { + self.0.iter().any(|r| r.id == *req) + } +} diff --git a/vendor/clap-3.2.20/src/util/id.rs b/vendor/clap-3.2.20/src/util/id.rs new file mode 100644 index 000000000..63a7e003e --- /dev/null +++ b/vendor/clap-3.2.20/src/util/id.rs @@ -0,0 +1,92 @@ +use crate::util::fnv::Key; + +use std::{ + fmt::{Debug, Formatter, Result}, + hash::{Hash, Hasher}, + ops::Deref, +}; + +#[derive(Clone, Eq, Default)] +#[cfg_attr(not(debug_assertions), repr(transparent))] +pub(crate) struct Id { + #[cfg(debug_assertions)] + name: String, + id: u64, +} + +macro_rules! precomputed_hashes { + ($($fn_name:ident, $const:expr, $name:expr;)*) => { + impl Id { + $( + pub(crate) fn $fn_name() -> Self { + Id { + #[cfg(debug_assertions)] + name: $name.into(), + id: $const, + } + } + )* + } + }; +} + +// precompute some common values +precomputed_hashes! { + empty_hash, 0x1C9D_3ADB_639F_298E, ""; + help_hash, 0x5963_6393_CFFB_FE5F, "help"; + version_hash, 0x30FF_0B7C_4D07_9478, "version"; +} + +impl Id { + pub(crate) fn from_ref(val: T) -> Self { + Id { + #[cfg(debug_assertions)] + name: val.to_string(), + id: val.key(), + } + } +} + +impl Debug for Id { + fn fmt(&self, f: &mut Formatter) -> Result { + #[cfg(debug_assertions)] + write!(f, "{}", self.name)?; + #[cfg(not(debug_assertions))] + write!(f, "[hash: {:X}]", self.id)?; + + Ok(()) + } +} + +impl Deref for Id { + type Target = u64; + + fn deref(&self) -> &Self::Target { + &self.id + } +} + +impl From for Id { + fn from(val: T) -> Self { + Id { + #[cfg(debug_assertions)] + name: val.to_string(), + id: val.key(), + } + } +} + +impl Hash for Id { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + self.id.hash(state) + } +} + +impl PartialEq for Id { + fn eq(&self, other: &Id) -> bool { + self.id == other.id + } +} diff --git a/vendor/clap-3.2.20/src/util/mod.rs b/vendor/clap-3.2.20/src/util/mod.rs new file mode 100644 index 000000000..8adc8db17 --- /dev/null +++ b/vendor/clap-3.2.20/src/util/mod.rs @@ -0,0 +1,40 @@ +#![allow(clippy::single_component_path_imports)] + +mod fnv; +mod graph; +mod id; +mod str_to_bool; + +pub use self::fnv::Key; + +pub(crate) use self::str_to_bool::str_to_bool; +pub(crate) use self::str_to_bool::FALSE_LITERALS; +pub(crate) use self::str_to_bool::TRUE_LITERALS; +pub(crate) use self::{graph::ChildGraph, id::Id}; + +pub(crate) mod color; + +pub(crate) const SUCCESS_CODE: i32 = 0; +// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but +// instead 2 seems to be frequently used. +// Examples +// - GNU `ls` returns 2 +// - Python's `argparse` returns 2 +pub(crate) const USAGE_CODE: i32 = 2; + +pub(crate) fn safe_exit(code: i32) -> ! { + use std::io::Write; + + let _ = std::io::stdout().lock().flush(); + let _ = std::io::stderr().lock().flush(); + + std::process::exit(code) +} + +#[cfg(not(feature = "unicode"))] +pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool { + left.eq_ignore_ascii_case(right) +} + +#[cfg(feature = "unicode")] +pub(crate) use unicase::eq as eq_ignore_case; diff --git a/vendor/clap-3.2.20/src/util/str_to_bool.rs b/vendor/clap-3.2.20/src/util/str_to_bool.rs new file mode 100644 index 000000000..1fbdc7531 --- /dev/null +++ b/vendor/clap-3.2.20/src/util/str_to_bool.rs @@ -0,0 +1,21 @@ +/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`. +pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"]; + +/// False values are `n`, `no`, `f`, `false`, `off`, and `0`. +pub(crate) const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"]; + +/// Converts a string literal representation of truth to true or false. +/// +/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive). +/// +/// Any other value will be considered as `true`. +pub(crate) fn str_to_bool(val: impl AsRef) -> Option { + let pat: &str = &val.as_ref().to_lowercase(); + if TRUE_LITERALS.contains(&pat) { + Some(true) + } else if FALSE_LITERALS.contains(&pat) { + Some(false) + } else { + None + } +} diff --git a/vendor/clap/.cargo-checksum.json b/vendor/clap/.cargo-checksum.json deleted file mode 100644 index 729aee79b..000000000 --- a/vendor/clap/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.lock":"6d96d441076749454963df06d637e5680e5ecdcdd36026f160c2d181aaca3bdc","Cargo.toml":"cb59c1e945c5606119203d907c01a40606070414b8913440f32e250c5db8c211","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"b5d5ba727e9f1a8797016bb041bc7888a209099d7dc42e445a89b1f8d3ac510d","examples/README.md":"9d19f6dfb53aadbe18aca773136d34bd28352b8efd69dfee217f26ee0eb9269a","examples/cargo-example-derive.md":"53a35e48cd04dfa10d70f99eb6d97d0d74110958f7f9e4ffc460fca87a256a73","examples/cargo-example-derive.rs":"627a74b7dc6d829b8facd314d0de46418b2420c6998e883f71a3cb7639d3a22d","examples/cargo-example.md":"1f270b0a0ac9122feb9cdac0887c1c1bcf1b654fed27147871c9cfe71851a4d9","examples/cargo-example.rs":"66293c7e200a87fceca691ab858293142c8a1536ef1d2c0dd14a6056289866a2","examples/demo.md":"3e986afca0863142fdd4cc092b5969fba32a70fac8adf84a55bd652f4b30eedb","examples/demo.rs":"5361cac70b662dd6d4d785738b99cfadf1f838c90507f19ea1aeef05aba0ee72","examples/derive_ref/README.md":"be2cfd81b9e2dc5e5910243f4b2f032e0b2c8af0592dcd050705e8718be8038d","examples/derive_ref/augment_args.rs":"69057536807ceb08e35802f8cf65c0f6ddd260a66a90000c8c6294031d466be3","examples/derive_ref/augment_subcommands.rs":"5535f8ca1893101acb5eba8edc311497431ff9aa26f62f1d9743bdc147bef7a4","examples/derive_ref/custom-bool.md":"d92e441199c7584d4b888c45124366cc4802ec8ea67cdcbb3423ffaa3c5268ac","examples/derive_ref/custom-bool.rs":"f88e9c68d2447a24bc98e05124fea17836155f32cff30a2b8a03ad254383247c","examples/derive_ref/flatten_hand_args.rs":"c09b751eb4e89e825af4de25a67d735c7b4794536bcff96b0ab8ee816c34413a","examples/derive_ref/hand_subcommand.rs":"1a5464b9c5791361930b5591adeb6fcf6f14b83abdfa6443d2c80bcf0c097b3e","examples/derive_ref/interop_tests.md":"3a357e82cfc155f71e0348be33f78295aa77839c3e3a5b7c1783cbd1259e6a61","examples/escaped-positional-derive.md":"b2190ada5ad2634c3ceb7f9d98293512628762545f9519579cbee9867c6a406a","examples/escaped-positional-derive.rs":"ac3127e8cc7a8953886778824a4d6e12470488546f10eeac6f9817ecaef1532e","examples/escaped-positional.md":"b6a5c103f5cea1464b5ac8e63e1964f032a4dbb4a908e45b9b391f4857fe2684","examples/escaped-positional.rs":"aaf106cdbe8f1eb5d9f3032df485d5661885f95402f026a34c42431f98a08323","examples/git-derive.md":"1a20f30d1c6df28d7e48b527b0726e9440f54d55a1e0b9e059b2322a7960ee72","examples/git-derive.rs":"225a33b0cd84840de2ba623b6b506b2fa4b02a9f5fbf62cdc2b2626e661501bd","examples/git.md":"acb3a44f954a6e2160f8989952981fb4baea8b97b921e4227c67896bc64d5e4a","examples/git.rs":"293b1289550ea38eabf1af7c6a855065170ff785e97be113928f045c50c1a3e9","examples/multicall-busybox.md":"3cb9d00ad110fc99c298dac4aa471e2f7a304aecef51d2eda67f5fbf36c41293","examples/multicall-busybox.rs":"709f71a82295a539d0a239371d35d1eeb517eaa3bb0a4db406bb7e5d3541a4a5","examples/multicall-hostname.md":"8c2d95fa8b940d4f788f96cf6b08b81bb2541bf12adff63bdff90dfc24567c7e","examples/multicall-hostname.rs":"cc58a924dd2e57281f36e30481a1cbc8186952adbf149f9e1e13f9c673614fd9","examples/pacman.md":"e583ef465e55fa2fffef3b121e4a90835b8905ef3ffe2ec9ae91702832b7392d","examples/pacman.rs":"4aea4eed4408458d57d3ff91f0e7f8833eeee30dd71043f5a6d06968c6c9712e","examples/repl.rs":"d50c1da634c237b26989994b1efa6fd1a087874a82d1fc8c1863be4ea8deaa8c","examples/tutorial_builder/01_quick.rs":"2734001dc1f67842f8ff3486397738f10dcbdf4bdd15326c13aebd5fafe0dabd","examples/tutorial_builder/02_app_settings.rs":"ca7e0b49019a444053ed13a7df8108d460430819b4fb04c4c6097225dc630293","examples/tutorial_builder/02_apps.rs":"a7016469d10259ae0025fb6ad5b9d3c732cf082869348005d4774d2bb0722d2d","examples/tutorial_builder/02_crate.rs":"5d7397901ebf82e3975626b3737fca3a95868cde42ce74d41bb3c96429878906","examples/tutorial_builder/03_01_flag_bool.rs":"1e904b39c7aaafc407a841ab8b549152263073a1af11773d13dc04d43fd541ef","examples/tutorial_builder/03_01_flag_count.rs":"02778a53afd6170c7ef7d358909237d4fe548adc5d7e650916d26f765040c25b","examples/tutorial_builder/03_02_option.rs":"7bca1c12b4904f89516ebdb88019c959c5adcf2a84244047f988b71f82760bd4","examples/tutorial_builder/03_03_positional.rs":"290921224b17df7f77326df06421b2100462da143e7b5dbe014f7e8b6d727d2b","examples/tutorial_builder/03_04_subcommands.rs":"1d5769847403661b1bb82d7a39713c52e1decbe4027dfc3866d63f5cf6ae8a55","examples/tutorial_builder/03_05_default_values.rs":"5a4768214c57996b27989cd5af57c7b79cbccfab2f285a88a415c2b67b589e4b","examples/tutorial_builder/04_01_enum.rs":"813ce1cf91e2cacd7eb5bd7018b1125d41cd9b29970dfa3638a7cf73c06659a0","examples/tutorial_builder/04_01_possible.rs":"2ccba0ab59f6339bcd761160d17a1c7ec935716fbe137408338694c7d3ee56f0","examples/tutorial_builder/04_02_parse.rs":"9d022cb3a3af3e00fd6c7d647ee0915a275ce79e379676e98bebcd3484be344b","examples/tutorial_builder/04_02_validate.rs":"4450e7e1af3581be631ffe9afa363c88b44ee20a90ecbb4608246972d3f7fd93","examples/tutorial_builder/04_03_relations.rs":"90db469ca8a3f1c5eb90548e8c1c0afe796d163891bdac90f2d307949a400047","examples/tutorial_builder/04_04_custom.rs":"461a06cae62f5972937f71b42d04df44240dabd62e23058322f04026beceaec5","examples/tutorial_builder/05_01_assert.rs":"73c57b051550366ed412c8986f40549fd43dacf3894df7751313c5de16f46af1","examples/tutorial_builder/README.md":"027d95d9f951d4ffed9ec54a3950919ea4a3d9fd471bbda721151ed6ff6c5731","examples/tutorial_derive/01_quick.rs":"e17262c915199c4507d8950d5eafb73f3047e09b6dee2abbfe9f82ebf1b7ddd5","examples/tutorial_derive/02_app_settings.rs":"7e81f4c1640b0bfbd87aedd3eda79ae7c47c669dee79b643b35e54c1dc076ee8","examples/tutorial_derive/02_apps.rs":"e8cd02b5983b2203f1585b96858fade4cedfb124e366171d6b21fcb3f05b514e","examples/tutorial_derive/02_crate.rs":"c156589c36a8b21654b1a41f5f10240411053d3273e7af3797e91ca53fa61d28","examples/tutorial_derive/03_01_flag_bool.rs":"07c31218d0332d7437d80e19c7e3c7be711bf0f56bee3ffb1c4d6f7f253b9304","examples/tutorial_derive/03_01_flag_count.rs":"945be42994845145b9c579b3834f8c6375f239293ded84fba35754bbe9fdcf9b","examples/tutorial_derive/03_02_option.rs":"48be4cf49b498173200ad86d5d3cd64ce9381f86fdaaab70f05fc471f64a2185","examples/tutorial_derive/03_03_positional.rs":"f368ab1465ee4d84b84d175b97af6f64ce0676bec2482adef3ce966d2d8de26a","examples/tutorial_derive/03_04_subcommands.rs":"b25c8aec8f3816923b1154be91caafe0c2d2841fc1af5f0ef048f03d1273879e","examples/tutorial_derive/03_04_subcommands_alt.rs":"7ba6e81c2af6085b7e2721254500b34ee3e8622e20790b3c6f2786e165151b70","examples/tutorial_derive/03_05_default_values.rs":"0ba14153a3c72a2435ac3688b990171a1670eb3f2f7cef21886732e489fad435","examples/tutorial_derive/04_01_enum.rs":"a665af77196af86ba87f1725703011392fc27f24e3d442bbb5dfc4c0d4892c15","examples/tutorial_derive/04_02_parse.rs":"fbb23ef2d98d3cb401cec9dd29d5818e4c189cc9f54fe961a2fbd08632a9634c","examples/tutorial_derive/04_02_validate.rs":"87d9c465f912b69e5839ea87404a221a39421404012c1a7fd6e327b03ceb12f0","examples/tutorial_derive/04_03_relations.rs":"bfc12e66ad9c17182bed2ef86cd668242e6e87ab4ee20fa9bf3d2aa99385d61a","examples/tutorial_derive/04_04_custom.rs":"0e745c6dab0881c62190e82e01409b70cf3286dd0983db4a612f1be88fdd1a8d","examples/tutorial_derive/05_01_assert.rs":"4742d883a3446f32068d96c142ed18df40a50ad6ed4989e39980011f3d1adbdf","examples/tutorial_derive/README.md":"7902da25a153aa0032184e4ca54185d1a5d4c6aa53686b10a210b4decc276791","examples/typed-derive.md":"cf3ee8313709937cc9c5462e3826cca8679946a658d684e8a36e66b0950100a7","examples/typed-derive.rs":"67034bd557c0efb2a0b61ced263cab3ddddb4e4a2bff2f2901d4832f6961e17d","src/bin/stdio-fixture.rs":"e8f10afbfe1857bcf986d2f55be0ca19a50c905d9f650c6e1fd42dbacf219b04","src/builder/action.rs":"64633d218202f799a08fb43ce7f1fae6105ae5ed43386caf4aca2d8ac5352fc1","src/builder/app_settings.rs":"5a27df52d765b50f83ad1173525b66f92b156415aee62b238306b3b57c086e50","src/builder/arg.rs":"808037bb9e7084c27f9f136059653ab049630d07d9851e5e700c8a775655bd05","src/builder/arg_group.rs":"263d9c79e03015fe4e2fab4616fc73089be60fb2ec17aa2a06f3d6a24740432c","src/builder/arg_predicate.rs":"8c9fd14780cd42465f32f2e8927b97c06e686d09b5927ba3cd5bbd792af7a13d","src/builder/arg_settings.rs":"af739627b9b1451c633eb66b09536008d8b095cba518a4f28b82ea480e9400d6","src/builder/command.rs":"72d0031bce35aa6d6ebd6a2006fe26a9b222852fe5a58a23854d9ab7f27150c5","src/builder/debug_asserts.rs":"d1d5adc82cb8269445b2ef197f1e566f61e7f13d6a24afaad928e45e95aed170","src/builder/macros.rs":"904e42e72c49107ae324f45d5df24fbff13b9c7d4589f1a4ae38594add704434","src/builder/mod.rs":"205367cb5ba5d5ba7894091535ce3a5dd23b35fd436e003196d89523e7705566","src/builder/possible_value.rs":"62268b9da9eec8f4d1904ebfbd3a288fb78cfa71c357efadced28f0378bcfb93","src/builder/regex.rs":"b18891310186ecdcca9bb611833b7188cc80fe72e9fef27b63fa076b880a1acb","src/builder/tests.rs":"995c7d6be608b94c6f392f1356eba0cb8adb9ca661ffeebf7ebe6e8ad01a868c","src/builder/usage_parser.rs":"91d1af89196116aac2c0fb021f42f43f954aa3252df264e19a02a0cf5911d16b","src/builder/value_hint.rs":"0dd974d495c313430898d28b79991a70983c9aa44e88fa9aa1776d3308935438","src/builder/value_parser.rs":"1d731b5bf4e25344ae1de23c474255a310852721ecf66a98c5ef2cbca1452437","src/derive.rs":"cf3e108adf7022ef4a269a0ede687d19f8f549168e1f36c3592fbee40da51e61","src/error/context.rs":"1dc561c7877d7f9b90f04bb7915744f0b3cc4ac2aa928ae100b2825a97077142","src/error/kind.rs":"deba40c24adf04e67e87e383463d103907b7f8cc69f842fd3a5d8d81015d33c1","src/error/mod.rs":"c7bdd28240ee2fac6d9ae2c3d849483fabc3c64d5d577c0bc297c996f122a217","src/lib.rs":"9522f2b17cd505623468c5ff847f5aa906a40ae19dde0329c459a417c2b82a2b","src/macros.rs":"d39619976c3cf3b2b28eef3dfffd449080f4fcfbaa164b01901bf3e10d1a5a07","src/mkeymap.rs":"3565a5bae5d6cdcf8ba41a24eb602c510a14e150c4a6d3085ad72a35778e9c5f","src/output/fmt.rs":"efb741b5854500d946c6c09763ece1badc2b9cd3efa616cb58012039836c2b7f","src/output/help.rs":"ebdd123d6b70279c25af4b08432b547498834853adf99821ff6c6cd65dd87d4e","src/output/mod.rs":"3a61f89a4568e95114a3ab839da8f3c4c92de2a228549308f5d1be076a474917","src/output/usage.rs":"370d3544cf58a09f8d3b0bcc2d894531d7152d716eaffa745a858c6ba2e03b7c","src/parser/arg_matcher.rs":"79ab36a164df07e565d2c44b836f647ee2009463d0d55bd2e822cb72b5e009a7","src/parser/error.rs":"4568fb6b8bb05b43e81c5df4fba5f4cb8b19bfa06e6b8fc6b5af6ca4074766cf","src/parser/features/mod.rs":"6ed075e97af56bff22f22ed1ee83ff6479360e05f9d3661a3145f822c242b694","src/parser/features/suggestions.rs":"79127956b2f1adb9d658925e2779ebebfe9ddea434408762fefb60afdb545f47","src/parser/matches/any_value.rs":"7b6e711fe205e8808394c562dd6a260b56ce350cf9298a308ba9727ab012b664","src/parser/matches/arg_matches.rs":"a24fa086537ef72951821fbf1dc455a04270606ee411685991e79aaae509558c","src/parser/matches/matched_arg.rs":"fb12eb2afaf631bb60aa8c4e42b0f510a877d35a9eaa07a7afd253280c27c251","src/parser/matches/mod.rs":"1467aa752cb1c79d30e4aeaaa55e10a0bb9dcf6f3980496234251431c79c49e6","src/parser/matches/value_source.rs":"e6a477ae36f2f7155960239a97b7d142eef4eb227c41c9eefea147289547d713","src/parser/mod.rs":"358f46d3b7f43dec2563d4c35bd2536fab2491f28e300a9bcdeaf6ca0513ce12","src/parser/parser.rs":"c1339fdf44253b6cbf81fcf71f99bb68300f8d5eb5ab7f0d0d02d222ee63a873","src/parser/validator.rs":"30066cb41ab23800231fb6b028cbce57d118570859659ebc67affbe5226f31f9","src/util/color.rs":"63df5e1cda1001b4c536dc0b04e09dd85dae6d317e34e660abbe3c71e17eaa29","src/util/fnv.rs":"82492d91d990f38b62de8b3c3e67f1fad55919117b1f448aa28acf6d21919fd7","src/util/graph.rs":"f35396b6e2a427377dcbbca69b1b98737d89684a3834cfda98cbf8cc70ff9c2f","src/util/id.rs":"fc498c65887385d92a51359a2f72556c2e508ee49b8cac4b3f827512795d690d","src/util/mod.rs":"8d328a15ef06989d0ce5e65cf3b7ec79c083984b25c0b31ba177bdb22df28a10","src/util/str_to_bool.rs":"1ce90b4939a884eeefc73392722bdfcf906e3070c4398e1557c586c10c684cd0"},"package":"d53da17d37dba964b9b3ecb5c5a1f193a2762c700e6829201e645b9381c99dc7"} \ No newline at end of file diff --git a/vendor/clap/Cargo.lock b/vendor/clap/Cargo.lock deleted file mode 100644 index 269dea5ad..000000000 --- a/vendor/clap/Cargo.lock +++ /dev/null @@ -1,745 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "addr2line" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "backtrace" -version = "0.3.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a17d453482a265fd5f8479f2a3f405566e6ca627837aaddb85af8b1ab8ef61" -dependencies = [ - "addr2line", - "cc", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bytes" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "clap" -version = "3.2.5" -dependencies = [ - "atty", - "backtrace", - "bitflags", - "clap_derive", - "clap_lex", - "humantime", - "indexmap", - "once_cell", - "regex", - "rustversion", - "shlex", - "snapbox", - "strsim", - "termcolor", - "terminal_size", - "textwrap", - "trybuild", - "trycmd", - "unicase", - "yaml-rust", -] - -[[package]] -name = "clap_derive" -version = "3.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c11d40217d16aee8508cc8e5fde8b4ff24639758608e5374e731b53f85749fb9" -dependencies = [ - "heck", - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613" -dependencies = [ - "os_str_bytes", -] - -[[package]] -name = "combine" -version = "4.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a604e93b79d1808327a6fca85a6f2d69de66461e7620f5a4cbf5fb4d1d7c948" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "concolor" -version = "0.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "015267563b1df20adccdd00cb05257b1dfbea70a04928e9cf88ffb850c1a40af" -dependencies = [ - "atty", - "bitflags", - "concolor-query", -] - -[[package]] -name = "concolor-query" -version = "0.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6417fe6fc03a8b533fd2177742eeb39a90c7233eedec7bac96d4d6b69a09449" - -[[package]] -name = "crossbeam-channel" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" -dependencies = [ - "cfg-if", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if", - "lazy_static", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "escargot" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5584ba17d7ab26a8a7284f13e5bd196294dd2f2d79773cff29b9e9edef601a6" -dependencies = [ - "log", - "once_cell", - "serde", - "serde_json", -] - -[[package]] -name = "gimli" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "heck" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - -[[package]] -name = "humantime-serde" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" -dependencies = [ - "humantime", - "serde", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.125" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "log" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "memchr" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "miniz_oxide" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082" -dependencies = [ - "adler", -] - -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "object" -version = "0.28.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40bec70ba014595f99f7aa110b84331ffe1ee9aece7fe6f387cc7e3ecda4d456" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" - -[[package]] -name = "os_pipe" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c92f2b54f081d635c77e7120862d48db8e91f7f21cef23ab1b4fe9971c59f55" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "os_str_bytes" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro2" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rayon" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd249e82c21598a9a426a4e00dd7adc1d640b22445ec8545feef801d1a74c221" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f51245e1e62e1f1629cbfec37b5793bbabcaeb90f30e94d2ba03564687353e4" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - -[[package]] -name = "regex" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.6.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" - -[[package]] -name = "rustc-demangle" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" - -[[package]] -name = "rustversion" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" - -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "serde" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "shlex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" - -[[package]] -name = "similar" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e24979f63a11545f5f2c60141afe249d4f19f84581ea2138065e400941d83d3" - -[[package]] -name = "snapbox" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "767a1d5da232b6959cd1bd5c9e8db8a7cce09c3038e89deedb49a549a2aefd93" -dependencies = [ - "concolor", - "normalize-line-endings", - "os_pipe", - "similar", - "snapbox-macros", - "wait-timeout", - "yansi", -] - -[[package]] -name = "snapbox-macros" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c01dea7e04cbb27ef4c86e9922184608185f7cd95c1763bc30d727cda4a5e930" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "syn" -version = "1.0.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "terminal_size" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "textwrap" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" -dependencies = [ - "terminal_size", - "unicode-width", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba98375fd631b83696f87c64e4ed8e29e6a1f3404d6aed95fa95163bad38e705" -dependencies = [ - "combine", - "indexmap", - "itertools", - "serde", -] - -[[package]] -name = "trybuild" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fc92f558afb6d1d7c6f175eb8d615b8ef49c227543e68e19c123d4ee43d8a7d" -dependencies = [ - "glob", - "once_cell", - "serde", - "serde_derive", - "serde_json", - "termcolor", - "toml", -] - -[[package]] -name = "trycmd" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb4185126cc904642173a54c185083f410c86d1202ada6761aacf7c40829f13" -dependencies = [ - "escargot", - "glob", - "humantime", - "humantime-serde", - "rayon", - "serde", - "shlex", - "snapbox", - "toml_edit", -] - -[[package]] -name = "unicase" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" -dependencies = [ - "version_check", -] - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wait-timeout" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" -dependencies = [ - "libc", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "yansi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" diff --git a/vendor/clap/Cargo.toml b/vendor/clap/Cargo.toml deleted file mode 100644 index aba082f3a..000000000 --- a/vendor/clap/Cargo.toml +++ /dev/null @@ -1,493 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2021" -rust-version = "1.56.0" -name = "clap" -version = "3.2.5" -include = [ - "build.rs", - "src/**/*", - "Cargo.toml", - "LICENSE*", - "README.md", - "benches/**/*", - "examples/**/*", -] -description = "A simple to use, efficient, and full-featured Command Line Argument Parser" -documentation = "https://docs.rs/clap/" -readme = "README.md" -keywords = [ - "argument", - "cli", - "arg", - "parser", - "parse", -] -categories = ["command-line-interface"] -license = "MIT OR Apache-2.0" -repository = "https://github.com/clap-rs/clap" -resolver = "2" - -[package.metadata.docs.rs] -features = ["unstable-doc"] -rustdoc-args = [ - "--cfg", - "docsrs", -] -cargo-args = [ - "-Zunstable-options", - "-Zrustdoc-scrape-examples=examples", -] - -[package.metadata.playground] -features = ["unstable-doc"] - -[package.metadata.release] -shared-version = true -tag-name = "v{{version}}" - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "Unreleased" -replace = "{{version}}" -min = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = '\.\.\.HEAD' -replace = "...{{tag_name}}" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "ReleaseDate" -replace = "{{date}}" -min = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "" -replace = """ - -## [Unreleased] - ReleaseDate -""" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "CHANGELOG.md" -search = "" -replace = """ - -[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" -exactly = 1 - -[[package.metadata.release.pre-release-replacements]] -file = "README.md" -search = "github.com/clap-rs/clap/blob/[^/]+/" -replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" -exactly = 13 -prerelease = true - -[[package.metadata.release.pre-release-replacements]] -file = "README.md" -search = 'version = "[a-z0-9\.-]+"' -replace = "version = \"{{version}}\"" -exactly = 1 -prerelease = true - -[[package.metadata.release.pre-release-replacements]] -file = "src/derive.rs" -search = "github.com/clap-rs/clap/blob/[^/]+/" -replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" -exactly = 4 -prerelease = true - -[profile.bench] -lto = true -codegen-units = 1 - -[profile.test] -opt-level = 1 - -[lib] -bench = false - -[[example]] -name = "demo" -required-features = ["derive"] - -[[example]] -name = "cargo-example" -required-features = ["cargo"] - -[[example]] -name = "cargo-example-derive" -required-features = ["derive"] - -[[example]] -name = "escaped-positional" -required-features = ["cargo"] - -[[example]] -name = "escaped-positional-derive" -required-features = ["derive"] - -[[example]] -name = "git-derive" -required-features = ["derive"] - -[[example]] -name = "typed-derive" -required-features = ["derive"] - -[[example]] -name = "busybox" -path = "examples/multicall-busybox.rs" - -[[example]] -name = "hostname" -path = "examples/multicall-hostname.rs" - -[[example]] -name = "repl" -path = "examples/repl.rs" - -[[example]] -name = "01_quick" -path = "examples/tutorial_builder/01_quick.rs" -required-features = ["cargo"] - -[[example]] -name = "02_apps" -path = "examples/tutorial_builder/02_apps.rs" - -[[example]] -name = "02_crate" -path = "examples/tutorial_builder/02_crate.rs" -required-features = ["cargo"] - -[[example]] -name = "02_app_settings" -path = "examples/tutorial_builder/02_app_settings.rs" -required-features = ["cargo"] - -[[example]] -name = "03_01_flag_bool" -path = "examples/tutorial_builder/03_01_flag_bool.rs" -required-features = ["cargo"] - -[[example]] -name = "03_01_flag_count" -path = "examples/tutorial_builder/03_01_flag_count.rs" -required-features = ["cargo"] - -[[example]] -name = "03_02_option" -path = "examples/tutorial_builder/03_02_option.rs" -required-features = ["cargo"] - -[[example]] -name = "03_03_positional" -path = "examples/tutorial_builder/03_03_positional.rs" -required-features = ["cargo"] - -[[example]] -name = "03_04_subcommands" -path = "examples/tutorial_builder/03_04_subcommands.rs" -required-features = ["cargo"] - -[[example]] -name = "03_05_default_values" -path = "examples/tutorial_builder/03_05_default_values.rs" -required-features = ["cargo"] - -[[example]] -name = "04_01_possible" -path = "examples/tutorial_builder/04_01_possible.rs" -required-features = ["cargo"] - -[[example]] -name = "04_01_enum" -path = "examples/tutorial_builder/04_01_enum.rs" -required-features = [ - "cargo", - "derive", -] - -[[example]] -name = "04_02_parse" -path = "examples/tutorial_builder/04_02_parse.rs" -required-features = ["cargo"] - -[[example]] -name = "04_02_validate" -path = "examples/tutorial_builder/04_02_validate.rs" -required-features = ["cargo"] - -[[example]] -name = "04_03_relations" -path = "examples/tutorial_builder/04_03_relations.rs" -required-features = ["cargo"] - -[[example]] -name = "04_04_custom" -path = "examples/tutorial_builder/04_04_custom.rs" -required-features = ["cargo"] - -[[example]] -name = "05_01_assert" -path = "examples/tutorial_builder/05_01_assert.rs" -test = true -required-features = ["cargo"] - -[[example]] -name = "01_quick_derive" -path = "examples/tutorial_derive/01_quick.rs" -required-features = ["derive"] - -[[example]] -name = "02_apps_derive" -path = "examples/tutorial_derive/02_apps.rs" -required-features = ["derive"] - -[[example]] -name = "02_crate_derive" -path = "examples/tutorial_derive/02_crate.rs" -required-features = ["derive"] - -[[example]] -name = "02_app_settings_derive" -path = "examples/tutorial_derive/02_app_settings.rs" -required-features = ["derive"] - -[[example]] -name = "03_01_flag_bool_derive" -path = "examples/tutorial_derive/03_01_flag_bool.rs" -required-features = ["derive"] - -[[example]] -name = "03_01_flag_count_derive" -path = "examples/tutorial_derive/03_01_flag_count.rs" -required-features = ["derive"] - -[[example]] -name = "03_02_option_derive" -path = "examples/tutorial_derive/03_02_option.rs" -required-features = ["derive"] - -[[example]] -name = "03_03_positional_derive" -path = "examples/tutorial_derive/03_03_positional.rs" -required-features = ["derive"] - -[[example]] -name = "03_04_subcommands_derive" -path = "examples/tutorial_derive/03_04_subcommands.rs" -required-features = ["derive"] - -[[example]] -name = "03_04_subcommands_alt_derive" -path = "examples/tutorial_derive/03_04_subcommands_alt.rs" -required-features = ["derive"] - -[[example]] -name = "03_05_default_values_derive" -path = "examples/tutorial_derive/03_05_default_values.rs" -required-features = ["derive"] - -[[example]] -name = "04_01_enum_derive" -path = "examples/tutorial_derive/04_01_enum.rs" -required-features = ["derive"] - -[[example]] -name = "04_02_parse_derive" -path = "examples/tutorial_derive/04_02_parse.rs" -required-features = ["derive"] - -[[example]] -name = "04_02_validate_derive" -path = "examples/tutorial_derive/04_02_validate.rs" -required-features = ["derive"] - -[[example]] -name = "04_03_relations_derive" -path = "examples/tutorial_derive/04_03_relations.rs" -required-features = ["derive"] - -[[example]] -name = "04_04_custom_derive" -path = "examples/tutorial_derive/04_04_custom.rs" -required-features = ["derive"] - -[[example]] -name = "05_01_assert_derive" -path = "examples/tutorial_derive/05_01_assert.rs" -test = true -required-features = ["derive"] - -[[example]] -name = "custom-bool" -path = "examples/derive_ref/custom-bool.rs" -required-features = ["derive"] - -[[example]] -name = "interop_augment_args" -path = "examples/derive_ref/augment_args.rs" -required-features = ["derive"] - -[[example]] -name = "interop_augment_subcommands" -path = "examples/derive_ref/augment_subcommands.rs" -required-features = ["derive"] - -[[example]] -name = "interop_hand_subcommand" -path = "examples/derive_ref/hand_subcommand.rs" -required-features = ["derive"] - -[[example]] -name = "interop_flatten_hand_args" -path = "examples/derive_ref/flatten_hand_args.rs" -required-features = ["derive"] - -[dependencies.atty] -version = "0.2" -optional = true - -[dependencies.backtrace] -version = "0.3" -optional = true - -[dependencies.bitflags] -version = "1.2" - -[dependencies.clap_derive] -version = "=3.2.5" -optional = true - -[dependencies.clap_lex] -version = "0.2.2" - -[dependencies.indexmap] -version = "1.0" - -[dependencies.once_cell] -version = "1.12.0" -optional = true - -[dependencies.regex] -version = "1.0" -optional = true - -[dependencies.strsim] -version = "0.10" -optional = true - -[dependencies.termcolor] -version = "1.1.1" -optional = true - -[dependencies.terminal_size] -version = "0.1.12" -optional = true - -[dependencies.textwrap] -version = "0.15.0" -features = [] -default-features = false - -[dependencies.unicase] -version = "2.6" -optional = true - -[dependencies.yaml-rust] -version = "0.4.1" -optional = true - -[dev-dependencies.humantime] -version = "2" - -[dev-dependencies.regex] -version = "1.0" - -[dev-dependencies.rustversion] -version = "1" - -[dev-dependencies.shlex] -version = "1.1.0" - -[dev-dependencies.snapbox] -version = "0.2.9" - -[dev-dependencies.trybuild] -version = "1.0.18" - -[dev-dependencies.trycmd] -version = "0.13" -features = [ - "color-auto", - "diff", - "examples", -] -default-features = false - -[features] -cargo = ["once_cell"] -color = [ - "atty", - "termcolor", -] -debug = [ - "clap_derive/debug", - "backtrace", -] -default = [ - "std", - "color", - "suggestions", -] -deprecated = ["clap_derive/deprecated"] -derive = [ - "clap_derive", - "once_cell", -] -env = [] -std = ["indexmap/std"] -suggestions = ["strsim"] -unicode = [ - "textwrap/unicode-width", - "unicase", -] -unstable-doc = [ - "derive", - "cargo", - "wrap_help", - "yaml", - "env", - "unicode", - "regex", - "unstable-replace", - "unstable-grouped", -] -unstable-grouped = [] -unstable-replace = [] -unstable-v4 = [ - "clap_derive/unstable-v4", - "deprecated", -] -wrap_help = [ - "terminal_size", - "textwrap/terminal_size", -] -yaml = ["yaml-rust"] diff --git a/vendor/clap/LICENSE-APACHE b/vendor/clap/LICENSE-APACHE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/clap/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/clap/LICENSE-MIT b/vendor/clap/LICENSE-MIT deleted file mode 100644 index 5acedf041..000000000 --- a/vendor/clap/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2016 Kevin B. Knapp - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/clap/README.md b/vendor/clap/README.md deleted file mode 100644 index 48b7a3cbd..000000000 --- a/vendor/clap/README.md +++ /dev/null @@ -1,179 +0,0 @@ - -# clap - -> **Command Line Argument Parser for Rust** - -[![Crates.io](https://img.shields.io/crates/v/clap?style=flat-square)](https://crates.io/crates/clap) -[![Crates.io](https://img.shields.io/crates/d/clap?style=flat-square)](https://crates.io/crates/clap) -[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/v3.2.5/LICENSE-APACHE) -[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/v3.2.5/LICENSE-MIT) -[![Build Status](https://img.shields.io/github/workflow/status/clap-rs/clap/CI/staging?style=flat-square)](https://github.com/clap-rs/clap/actions/workflows/ci.yml?query=branch%3Astaging) -[![Coverage Status](https://img.shields.io/coveralls/github/clap-rs/clap/master?style=flat-square)](https://coveralls.io/github/clap-rs/clap?branch=master) -[![Contributors](https://img.shields.io/github/contributors/clap-rs/clap?style=flat-square)](https://github.com/clap-rs/clap/graphs/contributors) - -Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). - -1. [About](#about) -2. Tutorial: [Builder API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_builder/README.md), [Derive API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_derive/README.md) -3. [Examples](https://github.com/clap-rs/clap/blob/v3.2.5/examples/README.md) -4. [API Reference](https://docs.rs/clap) - - [Derive Reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) - - [Feature Flags](#feature-flags) -5. [CHANGELOG](https://github.com/clap-rs/clap/blob/v3.2.5/CHANGELOG.md) -6. [FAQ](https://github.com/clap-rs/clap/blob/v3.2.5/docs/FAQ.md) -7. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) -8. [Contributing](https://github.com/clap-rs/clap/blob/v3.2.5/CONTRIBUTING.md) -8. [Sponsors](#sponsors) - -## About - -Create your command-line parser, with all of the bells and whistles, declaratively or procedurally. - -### Example - -This uses our -[Derive API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_derive/README.md) -which provides access to the [Builder API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_builder/README.md) as attributes on a `struct`: - - -```rust,no_run -use clap::Parser; - -/// Simple program to greet a person -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - /// Name of the person to greet - #[clap(short, long, value_parser)] - name: String, - - /// Number of times to greet - #[clap(short, long, value_parser, default_value_t = 1)] - count: u8, -} - -fn main() { - let args = Args::parse(); - - for _ in 0..args.count { - println!("Hello {}!", args.name) - } -} -``` -Add this to `Cargo.toml`: -```toml -[dependencies] -clap = { version = "3.2.5", features = ["derive"] } -``` -```bash -$ demo --help -clap [..] -Simple program to greet a person - -USAGE: - demo[EXE] [OPTIONS] --name - -OPTIONS: - -c, --count Number of times to greet [default: 1] - -h, --help Print help information - -n, --name Name of the person to greet - -V, --version Print version information -``` -*(version number and `.exe` extension on windows replaced by placeholders)* - -### Aspirations - -- Out of the box, users get a polished CLI experience - - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc -- Flexible enough to port your existing CLI interface - - However, we won't necessarily streamline support for each use case -- Reasonable parse performance -- Resilient maintainership, including - - Willing to break compatibility rather than batching up breaking changes in large releases - - Leverage feature flags to keep to one active branch - - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor -- We follow semver and will wait about 6-9 months between major breaking changes -- We will support the last two minor Rust releases (MSRV, currently 1.56.0) - -While these aspirations can be at odds with fast build times and low binary -size, we will still strive to keep these reasonable for the flexibility you -get. Check out the -[argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for -CLI parsers optimized for other use cases. - -### Selecting an API - -Why use the declarative [Derive API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_derive/README.md): -- Easier to read, write, and modify -- Easier to keep the argument declaration and reading of argument in sync -- Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) - -Why use the procedural [Builder API](https://github.com/clap-rs/clap/blob/v3.2.5/examples/tutorial_builder/README.md): -- Faster compile times if you aren't already using other procedural macros -- More flexible, e.g. you can look up how many times an argument showed up, - what its values were, and what were the indexes of those values. The Derive - API can only report presence, number of occurrences, or values but no indices - or combinations of data. - -### Related Projects - -- [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux -- [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files) -- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version` -- [clap_lex](https://crates.io/crates/clap_lex) for a lighter-weight, battle-tested CLI parser -- [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff) -- [clap_complete](https://crates.io/crates/clap_complete) for shell completion support -- [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) -- [clap-cargo](https://crates.io/crates/clap-cargo) -- [concolor-clap](https://crates.io/crates/concolor-clap) -- [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book -- [`trycmd`](https://crates.io/crates/trycmd): Snapshot testing - - Or for more control, [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs) - -## Feature Flags - -### Default Features - -* **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner. -* **color**: Turns on colored error messages. -* **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. - -#### Optional features - -* **deprecated**: Guided experience to prepare for next breaking release (at different stages of development, this may become default) -* **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above. -* **cargo**: Turns on macros that read values from `CARGO_*` environment variables. -* **env**: Turns on the usage of environment variables during parsing. -* **regex**: Enables regex validators. -* **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. -* **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. - -#### Experimental features - -**Warning:** These may contain breaking changes between minor releases. - -* **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) -* **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) -* **unstable-v4**: Preview features which will be stable on the v4.0 release - -## Sponsors - - -### Gold - -[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) - - -### Silver - -[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) - - -### Bronze - -[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) - - -### Backer - -[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) diff --git a/vendor/clap/examples/README.md b/vendor/clap/examples/README.md deleted file mode 100644 index 2034ab80e..000000000 --- a/vendor/clap/examples/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Examples - -- Basic demo: [derive](demo.md) -- Typed arguments: [derive](typed-derive.md) - - Topics: - - Custom `parse()` -- Custom cargo command: [builder](cargo-example.md), [derive](cargo-example-derive.md) - - Topics: - - Subcommands - - Cargo plugins -- git-like interface: [builder](git.md), [derive](git-derive.md) - - Topics: - - Subcommands - - External subcommands - - Optional subcommands - - Default subcommands -- pacman-like interface: [builder](pacman.md) - - Topics: - - Flag subcommands - - Conflicting arguments -- Escaped positionals with `--`: [builder](escaped-positional.md), [derive](escaped-positional-derive.md) -- Multi-call - - busybox: [builder](multicall-busybox.md) - - Topics: - - Subcommands - - hostname: [builder](multicall-hostname.md) - - Topics: - - Subcommands -- repl: [builder](repl.rs) - - Topics: - - Read-Eval-Print Loops / Custom command lines - -## Contributing - -New examples: -- Building: They must be added to [Cargo.toml](../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax -- Link the `.md` file from here - -See also the general [CONTRIBUTING](../CONTRIBUTING.md). diff --git a/vendor/clap/examples/cargo-example-derive.md b/vendor/clap/examples/cargo-example-derive.md deleted file mode 100644 index 994c6d4d8..000000000 --- a/vendor/clap/examples/cargo-example-derive.md +++ /dev/null @@ -1,45 +0,0 @@ -*Jump to [source](cargo-example-derive.rs)* - -For more on creating a custom subcommand, see [the cargo -book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). -The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in -mimicking cargo's interface. - -The help looks like: -```console -$ cargo-example-derive --help -cargo - -USAGE: - cargo - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - example-derive A simple to use, efficient, and full-featured Command Line Argument Parser - help Print this message or the help of the given subcommand(s) - -$ cargo-example-derive example-derive --help -cargo-example-derive [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - cargo example-derive [OPTIONS] - -OPTIONS: - -h, --help Print help information - --manifest-path - -V, --version Print version information - -``` - -Then to directly invoke the command, run: -```console -$ cargo-example-derive example-derive -None - -$ cargo-example-derive example-derive --manifest-path Cargo.toml -Some("Cargo.toml") - -``` diff --git a/vendor/clap/examples/cargo-example-derive.rs b/vendor/clap/examples/cargo-example-derive.rs deleted file mode 100644 index 6667a4a7d..000000000 --- a/vendor/clap/examples/cargo-example-derive.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Note: this requires the `derive` feature - -use clap::Parser; - -#[derive(Parser)] -#[clap(name = "cargo")] -#[clap(bin_name = "cargo")] -enum Cargo { - ExampleDerive(ExampleDerive), -} - -#[derive(clap::Args)] -#[clap(author, version, about, long_about = None)] -struct ExampleDerive { - #[clap(long, value_parser)] - manifest_path: Option, -} - -fn main() { - let Cargo::ExampleDerive(args) = Cargo::parse(); - println!("{:?}", args.manifest_path); -} diff --git a/vendor/clap/examples/cargo-example.md b/vendor/clap/examples/cargo-example.md deleted file mode 100644 index 9279cc492..000000000 --- a/vendor/clap/examples/cargo-example.md +++ /dev/null @@ -1,45 +0,0 @@ -*Jump to [source](cargo-example.rs)* - -For more on creating a custom subcommand, see [the cargo -book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). -The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in -mimicking cargo's interface. - -The help looks like: -```console -$ cargo-example --help -cargo - -USAGE: - cargo - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - example A simple to use, efficient, and full-featured Command Line Argument Parser - help Print this message or the help of the given subcommand(s) - -$ cargo-example example --help -cargo-example [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - cargo example [OPTIONS] - -OPTIONS: - -h, --help Print help information - --manifest-path - -V, --version Print version information - -``` - -Then to directly invoke the command, run: -```console -$ cargo-example example -None - -$ cargo-example example --manifest-path Cargo.toml -Some("Cargo.toml") - -``` diff --git a/vendor/clap/examples/cargo-example.rs b/vendor/clap/examples/cargo-example.rs deleted file mode 100644 index 45ae67c81..000000000 --- a/vendor/clap/examples/cargo-example.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Note: this requires the `cargo` feature - -fn main() { - let cmd = clap::Command::new("cargo") - .bin_name("cargo") - .subcommand_required(true) - .subcommand( - clap::command!("example").arg( - clap::arg!(--"manifest-path" ) - .required(false) - .value_parser(clap::value_parser!(std::path::PathBuf)), - ), - ); - let matches = cmd.get_matches(); - let matches = match matches.subcommand() { - Some(("example", matches)) => matches, - _ => unreachable!("clap should ensure we don't get here"), - }; - let manifest_path = matches.get_one::("manifest-path"); - println!("{:?}", manifest_path); -} diff --git a/vendor/clap/examples/demo.md b/vendor/clap/examples/demo.md deleted file mode 100644 index 9b0e7e260..000000000 --- a/vendor/clap/examples/demo.md +++ /dev/null @@ -1,20 +0,0 @@ -*Jump to [source](demo.rs)* - -**This requires enabling the `derive` feature flag.** - -Used to validate README.md's content -```console -$ demo --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - demo[EXE] [OPTIONS] --name - -OPTIONS: - -c, --count Number of times to greet [default: 1] - -h, --help Print help information - -n, --name Name of the person to greet - -V, --version Print version information - -``` diff --git a/vendor/clap/examples/demo.rs b/vendor/clap/examples/demo.rs deleted file mode 100644 index 957489724..000000000 --- a/vendor/clap/examples/demo.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Note: this requires the `derive` feature - -use clap::Parser; - -/// Simple program to greet a person -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - /// Name of the person to greet - #[clap(short, long, value_parser)] - name: String, - - /// Number of times to greet - #[clap(short, long, value_parser, default_value_t = 1)] - count: u8, -} - -fn main() { - let args = Args::parse(); - - for _ in 0..args.count { - println!("Hello {}!", args.name) - } -} diff --git a/vendor/clap/examples/derive_ref/README.md b/vendor/clap/examples/derive_ref/README.md deleted file mode 100644 index a3b0c084d..000000000 --- a/vendor/clap/examples/derive_ref/README.md +++ /dev/null @@ -1,440 +0,0 @@ -# Derive Reference - -1. [Overview](#overview) -2. [Attributes](#attributes) - 1. [Terminology](#terminology) - 2. [Command Attributes](#command-attributes) - 3. [Arg Attributes](#arg-attributes) - 4. [Arg Enum Attributes](#arg-enum-attributes) - 5. [Possible Value Attributes](#possible-value-attributes) -3. [Arg Types](#arg-types) -4. [Doc Comments](#doc-comments) -5. [Tips](#tips) -6. [Mixing Builder and Derive APIS](#mixing-builder-and-derive-apis) - -## Overview - -To derive `clap` types, you need to enable the `derive` feature flag. - -See [demo.rs](../demo.rs) and [demo.md](../demo.md) for a brief example. - -Let's start by breaking down the anatomy of the derive attributes: -```rust -use clap::{Parser, Args, Subcommand, ValueEnum}; - -/// Doc comment -#[derive(Parser)] -#[clap(APP ATTRIBUTE)] -struct Cli { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, - - #[clap(value_enum, ARG ATTRIBUTE...)] - field: EnumValues, - - #[clap(flatten)] - delegate: Struct, - - #[clap(subcommand)] - command: Command, -} - -/// Doc comment -#[derive(Args)] -#[clap(PARENT APP ATTRIBUTE)] -struct Struct { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, -} - -/// Doc comment -#[derive(Subcommand)] -#[clap(PARENT APP ATTRIBUTE)] -enum Command { - /// Doc comment - #[clap(APP ATTRIBUTE)] - Variant1(Struct), - - /// Doc comment - #[clap(APP ATTRIBUTE)] - Variant2 { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, - } -} - -/// Doc comment -#[derive(ValueEnum)] -#[clap(ARG ENUM ATTRIBUTE)] -enum EnumValues { - /// Doc comment - #[clap(POSSIBLE VALUE ATTRIBUTE)] - Variant1, -} - -fn main() { - let cli = Cli::parse(); -} -``` - -- `Parser` parses arguments into a `struct` (arguments) or `enum` (subcommands). -- `Args` allows defining a set of re-usable arguments that get merged into their parent container. -- `Subcommand` defines available subcommands. - - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant. -- `ValueEnum` allows parsing a value directly into an `enum`, erroring on unsupported values. - - The derive doesn't work on enums that contain non-unit variants, unless they are skipped - -See also the [tutorial](../tutorial_derive/README.md) and [examples](../README.md). - -## Attributes - -### Terminology - -**Raw attributes** are forwarded directly to the underlying `clap` builder. Any -`Command`, `Arg`, or `PossibleValue` method can be used as an attribute. - -Raw attributes come in two different syntaxes: -```rust -#[clap( - global = true, // name = arg form, neat for one-arg methods - required_if_eq("out", "file") // name(arg1, arg2, ...) form. -)] -``` - -- `method = arg` can only be used for methods which take only one argument. -- `method(arg1, arg2)` can be used with any method. - -As long as `method_name` is not one of the magical methods - it will be -translated into a mere method call. - -**Magic attributes** have post-processing done to them, whether that is -- Providing of defaults -- Special behavior is triggered off of it - -Magic attributes are more constrained in the syntax they support, usually just -` = ` though some use `()` instead. See the specific -magic attributes documentation for details. This allows users to access the -raw behavior of an attribute via `()` syntax. - -**NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc -Comments](#doc-comments). Explicit attributes take precedence over inferred -attributes. - -### Command Attributes - -These correspond to a `clap::Command` which is used for both top-level parsers and -when defining subcommands. - -**Raw attributes:** Any [`Command` method](https://docs.rs/clap/latest/clap/type.Command.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` - -**Magic attributes:** -- `name = `: `clap::Command::name` - - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (`Parser` container), variant name (`Subcommand` variant) -- `version [= ]`: `clap::Command::version` - - When not present: no version set - - Without ``: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field) -- `author [= ]`: `clap::Command::author` - - When not present: no author set - - Without ``: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field) -- `about [= ]`: `clap::Command::about` - - When not present: [Doc comment summary](#doc-comments) - - Without ``: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) (`Parser` container) - - **TIP:** When a doc comment is also present, you most likely want to add - `#[clap(long_about = None)]` to clear the doc comment so only `about` - gets shown with both `-h` and `--help`. -- `long_about = `: `clap::Command::long_about` - - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing -- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `about` / `long_about` -- `next_display_order`: `clap::Command::next_display_order` -- `next_help_heading`: `clap::Command::next_help_heading` - - When `flatten`ing `Args`, this is scoped to just the args in this struct and any struct `flatten`ed into it -- `rename_all = `: Override default field / variant name case conversion for `Command::name` / `Arg::name` - - When not present: `kebab-case` - - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` -- `rename_all_env = `: Override default field name case conversion for env variables for `clap::Arg::env` - - When not present: `SCREAMING_SNAKE_CASE` - - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` - -And for `Subcommand` variants: -- `skip`: Ignore this variant -- `flatten`: Delegates to the variant for more subcommands (must implement `Subcommand`) -- `subcommand`: Nest subcommands under the current set of subcommands (must implement `Subcommand`) -- `external_subcommand`: `clap::Command::allow_external_subcommand(true)` - - Variant must be either `Variant(Vec)` or `Variant(Vec)` - -### Arg Attributes - -These correspond to a `clap::Arg`. - -**Raw attributes:** Any [`Arg` method](https://docs.rs/clap/latest/clap/struct.Arg.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(max_values(3))]` would translate to `arg.max_values(3)` - -**Magic attributes**: -- `name = `: `clap::Arg::new` - - When not present: case-converted field name is used -- `value_parser [= ]`: `clap::Arg::value_parser` - - When not present: will auto-select an implementation based on the field type - - To register a custom type's `ValueParser`, implement `ValueParserFactory` - - When present, implies `#[clap(action)]` -- `action [= ]`: `clap::Arg::action` - - When not present: will auto-select an action based on the field type - - When present, implies `#[clap(value_parser)]` -- `help = `: `clap::Arg::help` - - When not present: [Doc comment summary](#doc-comments) -- `long_help = `: `clap::Arg::long_help` - - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing -- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `help` / `long_help` -- `short [= ]`: `clap::Arg::short` - - When not present: no short set - - Without ``: defaults to first character in the case-converted field name -- `long [= ]`: `clap::Arg::long` - - When not present: no long set - - Without ``: defaults to the case-converted field name -- `env [= ]`: `clap::Arg::env` (needs `env` feature enabled) - - When not present: no env set - - Without ``: defaults to the case-converted field name -- `flatten`: Delegates to the field for more arguments (must implement `Args`) - - Only `help_heading` can be used with `flatten`. See - [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why - arg attributes are not generally supported. - - **Tip:** Though we do apply a flattened `Args`'s Parent Command Attributes, this - makes reuse harder. Generally prefer putting the cmd attributes on the `Parser` - or on the flattened field. -- `subcommand`: Delegates definition of subcommands to the field (must implement `Subcommand`) - - When `Option`, the subcommand becomes optional -- `from_global`: Read a `clap::Arg::global` argument (raw attribute), regardless of what subcommand you are in -- `parse( [= ])`: `clap::Arg::validator` and `clap::ArgMatches::values_of_t` - - **Deprecated:** - - Use `value_parser(...)` for `from_str`, `try_from_str`, `from_os_str`, and `try_from_os_str` - - Use `action(ArgAction::Count` for `from_occurrences` - - Use `action(ArgAction::SetTrue` for `from_flag` - - Default: `try_from_str` - - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` - - See [Arg Types](#arg-types) for more details -- `value_enum`: Parse the value using the `ValueEnum` trait -- `skip [= ]`: Ignore this field, filling in with `` - - Without ``: fills the field with `Default::default()` -- `default_value = `: `clap::Arg::default_value` and `clap::Arg::required(false)` -- `default_value_t [= ]`: `clap::Arg::default_value` and `clap::Arg::required(false)` - - Requires `std::fmt::Display` or `#[clap(value_enum)]` - - Without ``, relies on `Default::default()` -- `default_value_os_t [= ]`: `clap::Arg::default_value_os` and `clap::Arg::required(false)` - - Requires `std::convert::Into` or `#[clap(value_enum)]` - - Without ``, relies on `Default::default()` - -### Arg Enum Attributes - -- `rename_all = `: Override default field / variant name case conversion for `PossibleValue::new` - - When not present: `kebab-case` - - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` - -### Possible Value Attributes - -These correspond to a `clap::PossibleValue`. - -**Raw attributes:** Any [`PossibleValue` method](https://docs.rs/clap/latest/clap/struct.PossibleValue.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")` - -**Magic attributes**: -- `name = `: `clap::PossibleValue::new` - - When not present: case-converted field name is used -- `help = `: `clap::PossibleValue::help` - - When not present: [Doc comment summary](#doc-comments) - -## Arg Types - -`clap` assumes some intent based on the type used: - -| Type | Effect | Implies | -|---------------------|--------------------------------------|------------------------------------------------------------------| -| `bool` | flag | `#[clap(parse(from_flag))]` | -| `Option` | optional argument | `.takes_value(true).required(false)` | -| `Option>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` | -| `T` | required argument | `.takes_value(true).required(!has_default)` | -| `Vec` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | -| `Option>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | - -Notes: -- For custom type behavior, you can override the implied attributes/settings and/or set additional ones - - For example, see [custom-bool](./custom-bool.md) -- `Option>` will be `None` instead of `vec![]` if no arguments are provided. - - This gives the user some flexibility in designing their argument, like with `min_values(0)` - -You can then support your custom type with `#[clap(parse( [= ]))]`: - -| `` | Signature | Default `` | -|--------------------------|---------------------------------------|---------------------------------| -| `from_str` | `fn(&str) -> T` | `::std::convert::From::from` | -| `try_from_str` (default) | `fn(&str) -> Result` | `::std::str::FromStr::from_str` | -| `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` | -| `try_from_os_str` | `fn(&OsStr) -> Result` | (no default function) | -| `from_occurrences` | `fn(u64) -> T` | `value as T` | -| `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` | - -Notes: -- `from_os_str`: - - Implies `arg.takes_value(true).allow_invalid_utf8(true)` -- `try_from_os_str`: - - Implies `arg.takes_value(true).allow_invalid_utf8(true)` -- `from_occurrences`: - - Implies `arg.takes_value(false).multiple_occurrences(true)` - - Reads from `clap::ArgMatches::occurrences_of` rather than a `get_one` function - - Note: operations on values, like `default_value`, are unlikely to do what you want -- `from_flag` - - Implies `arg.takes_value(false)` - - Reads from `clap::ArgMatches::is_present` rather than a `get_one` function - - Note: operations on values, like `default_value`, are unlikely to do what you want - -**Warning:** -- To support non-UTF8 paths, you should use `#[clap(value_parser)]` otherwise - `clap` will parse it as a `String` which will fail on some paths. - -## Doc Comments - -In clap, help messages for the whole binary can be specified -via [`Command::about`] and [`Command::long_about`] while help messages -for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]". - -`long_*` variants are used when user calls the program with -`--help` and "short" variants are used with `-h` flag. - -```rust -# use clap::Parser; - -#[derive(Parser)] -#[clap(about = "I am a program and I work, just pass `-h`", long_about = None)] -struct Foo { - #[clap(short, help = "Pass `-h` and you'll see me!")] - bar: String, -} -``` - -For convenience, doc comments can be used instead of raw methods -(this example works exactly like the one above): - -```rust -# use clap::Parser; - -#[derive(Parser)] -/// I am a program and I work, just pass `-h` -struct Foo { - /// Pass `-h` and you'll see me! - bar: String, -} -``` - -**NOTE:** Attributes have priority over doc comments! - -**Top level doc comments always generate `Command::about/long_about` calls!** -If you really want to use the `Command::about/long_about` methods (you likely don't), -use the `about` / `long_about` attributes to override the calls generated from -the doc comment. To clear `long_about`, you can use -`#[clap(long_about = None)]`. - -**TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time. - -### Pre-processing - -```rust -# use clap::Parser; -#[derive(Parser)] -/// Hi there, I'm Robo! -/// -/// I like beeping, stumbling, eating your electricity, -/// and making records of you singing in a shower. -/// Pay up, or I'll upload it to youtube! -struct Robo { - /// Call my brother SkyNet. - /// - /// I am artificial superintelligence. I won't rest - /// until I'll have destroyed humanity. Enjoy your - /// pathetic existence, you mere mortals. - #[clap(long, action)] - kill_all_humans: bool, -} -``` - -A doc comment consists of three parts: -- Short summary -- A blank line (whitespace only) -- Detailed description, all the rest - -The summary corresponds with `Command::about` / `Arg::help`. When a blank line is -present, the whole doc comment will be passed to `Command::long_about` / -`Arg::long_help`. Or in other words, a doc may result in just a `Command::about` / -`Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` / -`Arg::long_help` - -In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including: - -- Strip leading and trailing whitespace from every line, if present. - -- Strip leading and trailing blank lines, if present. - -- Interpret each group of non-empty lines as a word-wrapped paragraph. - - We replace newlines within paragraphs with spaces to allow the output - to be re-wrapped to the terminal width. - -- Strip any excess blank lines so that there is exactly one per paragraph break. - -- If the first paragraph ends in exactly one period, - remove the trailing period (i.e. strip trailing periods but not trailing ellipses). - -Sometimes you don't want this preprocessing to apply, for example the comment contains -some ASCII art or markdown tables, you would need to preserve LFs along with -blank lines and the leading/trailing whitespace. When you pass use the -`verbatim_doc_comment` magic attribute, you preserve -them. - -**Note:** Keep in mind that `verbatim_doc_comment` will *still* -- Remove one leading space from each line, even if this attribute is present, - to allow for a space between `///` and the content. -- Remove leading and trailing blank lines - -## Tips - -- To get access to a `Command` call `CommandFactory::command` (implemented when deriving `Parser`) -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](../tutorial_derive/05_01_assert.rs)) - -## Mixing Builder and Derive APIs - -The builder and derive APIs do not live in isolation. They can work together, which is especially helpful if some arguments can be specified at compile-time while others must be specified at runtime. - -### Using derived arguments in a builder application - -*[Jump to source](augment_args.rs)* - -When using the derive API, you can `#[clap(flatten)]` a struct deriving `Args` into a struct deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance created using the builder API with `Args` created using the derive API. - -It uses the `Args::augment_args` method to add the arguments to the `Command` instance. - -Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide structs that implement `Args` or `Parser`. Without the technique shown in this example, it would not be possible to use such crates with the builder API. `augment_args` to the rescue! - -### Using derived subcommands in a builder application - -*[Jump to source](augment_subcommands.rs)* - -When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also add the subcommands in that enum to a `Command` instance created with the builder API. - -It uses the `Subcommand::augment_subcommands` method to add the subcommands to the `Command` instance. - -### Adding hand-implemented subcommands to a derived application - -*[Jump to source](hand_subcommand.rs)* - -When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also implement the `Subcommand` trait manually on this enum (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance created behind the scenes for you by the derive API. - -Notice how in the previous example we used `augment_subcommands` on an enum that derived `Parser`, whereas now we implement `augment_subcommands` ourselves, but the derive API calls it automatically since we used the `#[clap(subcommand)]` attribute. - -### Flattening hand-implemented args into a derived application - -*[Jump to source](flatten_hand_args.rs)* - -When using the derive API, you can use `#[clap(flatten)]` inside the struct to add arguments as if they were added directly to the containing struct. The type of the field is usually an struct that derived `Args`. However, you can also implement the `Args` trait manually on this struct (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Args` trait will use the builder API to add the arguments to the `Command` instance created behind the scenes for you by the derive API. - -Notice how in the example 1 we used `augment_args` on the struct that derived `Parser`, whereas now we implement `augment_args` ourselves, but the derive API calls it automatically since we used the `#[clap(flatten)]` attribute. diff --git a/vendor/clap/examples/derive_ref/augment_args.rs b/vendor/clap/examples/derive_ref/augment_args.rs deleted file mode 100644 index 390c72f4a..000000000 --- a/vendor/clap/examples/derive_ref/augment_args.rs +++ /dev/null @@ -1,30 +0,0 @@ -use clap::{arg, Args as _, Command, FromArgMatches as _, Parser}; - -#[derive(Parser, Debug)] -struct DerivedArgs { - #[clap(short, long, action)] - derived: bool, -} - -fn main() { - let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue)); - // Augment built args with derived args - let cli = DerivedArgs::augment_args(cli); - - let matches = cli.get_matches(); - println!( - "Value of built: {:?}", - *matches.get_one::("built").unwrap() - ); - println!( - "Value of derived via ArgMatches: {:?}", - *matches.get_one::("derived").unwrap() - ); - - // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches. - // This is the main benefit of using derived arguments. - let derived_matches = DerivedArgs::from_arg_matches(&matches) - .map_err(|err| err.exit()) - .unwrap(); - println!("Value of derived: {:#?}", derived_matches); -} diff --git a/vendor/clap/examples/derive_ref/augment_subcommands.rs b/vendor/clap/examples/derive_ref/augment_subcommands.rs deleted file mode 100644 index 199da98b4..000000000 --- a/vendor/clap/examples/derive_ref/augment_subcommands.rs +++ /dev/null @@ -1,21 +0,0 @@ -use clap::{Command, FromArgMatches as _, Parser, Subcommand as _}; - -#[derive(Parser, Debug)] -enum Subcommands { - Derived { - #[clap(short, long, action)] - derived_flag: bool, - }, -} - -fn main() { - let cli = Command::new("Built CLI"); - // Augment with derived subcommands - let cli = Subcommands::augment_subcommands(cli); - - let matches = cli.get_matches(); - let derived_subcommands = Subcommands::from_arg_matches(&matches) - .map_err(|err| err.exit()) - .unwrap(); - println!("Derived subcommands: {:#?}", derived_subcommands); -} diff --git a/vendor/clap/examples/derive_ref/custom-bool.md b/vendor/clap/examples/derive_ref/custom-bool.md deleted file mode 100644 index 619f9ba8e..000000000 --- a/vendor/clap/examples/derive_ref/custom-bool.md +++ /dev/null @@ -1,47 +0,0 @@ -*Jump to [source](custom-bool.rs)* - -Example of overriding the magic `bool` behavior - -```console -$ custom-bool --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - custom-bool[EXE] [OPTIONS] --foo - -ARGS: - [possible values: true, false] - -OPTIONS: - --bar [default: false] - --foo [possible values: true, false] - -h, --help Print help information - -V, --version Print version information - -$ custom-bool -? failed -error: The following required arguments were not provided: - --foo - - -USAGE: - custom-bool[EXE] [OPTIONS] --foo - -For more information try --help - -$ custom-bool --foo true false -[examples/derive_ref/custom-bool.rs:31] opt = Opt { - foo: true, - bar: false, - boom: false, -} - -$ custom-bool --foo true --bar true false -[examples/derive_ref/custom-bool.rs:31] opt = Opt { - foo: true, - bar: true, - boom: false, -} - -``` diff --git a/vendor/clap/examples/derive_ref/custom-bool.rs b/vendor/clap/examples/derive_ref/custom-bool.rs deleted file mode 100644 index d3c321e72..000000000 --- a/vendor/clap/examples/derive_ref/custom-bool.rs +++ /dev/null @@ -1,32 +0,0 @@ -use clap::Parser; - -#[derive(Parser, Debug, PartialEq)] -#[clap(author, version, about, long_about = None)] -struct Opt { - // Default parser for `Set` is FromStr::from_str. - // `impl FromStr for bool` parses `true` or `false` so this - // works as expected. - #[clap(long, action = clap::ArgAction::Set)] - foo: bool, - - // Of course, this could be done with an explicit parser function. - #[clap(long, action = clap::ArgAction::Set, value_parser = true_or_false, default_value_t)] - bar: bool, - - // `bool` can be positional only with explicit `action` annotation - #[clap(action = clap::ArgAction::Set)] - boom: bool, -} - -fn true_or_false(s: &str) -> Result { - match s { - "true" => Ok(true), - "false" => Ok(false), - _ => Err("expected `true` or `false`"), - } -} - -fn main() { - let opt = Opt::parse(); - dbg!(opt); -} diff --git a/vendor/clap/examples/derive_ref/flatten_hand_args.rs b/vendor/clap/examples/derive_ref/flatten_hand_args.rs deleted file mode 100644 index 74d10edec..000000000 --- a/vendor/clap/examples/derive_ref/flatten_hand_args.rs +++ /dev/null @@ -1,81 +0,0 @@ -use clap::error::Error; -use clap::{Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches, Parser}; - -#[derive(Debug)] -struct CliArgs { - foo: bool, - bar: bool, - quuz: Option, -} - -impl FromArgMatches for CliArgs { - fn from_arg_matches(matches: &ArgMatches) -> Result { - let mut matches = matches.clone(); - Self::from_arg_matches_mut(&mut matches) - } - fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { - Ok(Self { - foo: *matches.get_one::("foo").expect("defaulted by clap"), - bar: *matches.get_one::("bar").expect("defaulted by clap"), - quuz: matches.remove_one::("quuz"), - }) - } - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { - let mut matches = matches.clone(); - self.update_from_arg_matches_mut(&mut matches) - } - fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { - self.foo |= *matches.get_one::("foo").expect("defaulted by clap"); - self.bar |= *matches.get_one::("bar").expect("defaulted by clap"); - if let Some(quuz) = matches.remove_one::("quuz") { - self.quuz = Some(quuz); - } - Ok(()) - } -} - -impl Args for CliArgs { - fn augment_args(cmd: Command<'_>) -> Command<'_> { - cmd.arg( - Arg::new("foo") - .short('f') - .long("foo") - .action(ArgAction::SetTrue), - ) - .arg( - Arg::new("bar") - .short('b') - .long("bar") - .action(ArgAction::SetTrue), - ) - .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) - } - fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> { - cmd.arg( - Arg::new("foo") - .short('f') - .long("foo") - .action(ArgAction::SetTrue), - ) - .arg( - Arg::new("bar") - .short('b') - .long("bar") - .action(ArgAction::SetTrue), - ) - .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) - } -} - -#[derive(Parser, Debug)] -struct Cli { - #[clap(short, long, action)] - top_level: bool, - #[clap(flatten)] - more_args: CliArgs, -} - -fn main() { - let args = Cli::parse(); - println!("{:#?}", args); -} diff --git a/vendor/clap/examples/derive_ref/hand_subcommand.rs b/vendor/clap/examples/derive_ref/hand_subcommand.rs deleted file mode 100644 index e9423bdc0..000000000 --- a/vendor/clap/examples/derive_ref/hand_subcommand.rs +++ /dev/null @@ -1,81 +0,0 @@ -use clap::error::{Error, ErrorKind}; -use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand}; - -#[derive(Parser, Debug)] -struct AddArgs { - #[clap(value_parser)] - name: Vec, -} -#[derive(Parser, Debug)] -struct RemoveArgs { - #[clap(short, long, action)] - force: bool, - #[clap(value_parser)] - name: Vec, -} - -#[derive(Debug)] -enum CliSub { - Add(AddArgs), - Remove(RemoveArgs), -} - -impl FromArgMatches for CliSub { - fn from_arg_matches(matches: &ArgMatches) -> Result { - match matches.subcommand() { - Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)), - Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)), - Some((_, _)) => Err(Error::raw( - ErrorKind::UnrecognizedSubcommand, - "Valid subcommands are `add` and `remove`", - )), - None => Err(Error::raw( - ErrorKind::MissingSubcommand, - "Valid subcommands are `add` and `remove`", - )), - } - } - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { - match matches.subcommand() { - Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?), - Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?), - Some((_, _)) => { - return Err(Error::raw( - ErrorKind::UnrecognizedSubcommand, - "Valid subcommands are `add` and `remove`", - )) - } - None => (), - }; - Ok(()) - } -} - -impl Subcommand for CliSub { - fn augment_subcommands(cmd: Command<'_>) -> Command<'_> { - cmd.subcommand(AddArgs::augment_args(Command::new("add"))) - .subcommand(RemoveArgs::augment_args(Command::new("remove"))) - .subcommand_required(true) - } - fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> { - cmd.subcommand(AddArgs::augment_args(Command::new("add"))) - .subcommand(RemoveArgs::augment_args(Command::new("remove"))) - .subcommand_required(true) - } - fn has_subcommand(name: &str) -> bool { - matches!(name, "add" | "remove") - } -} - -#[derive(Parser, Debug)] -struct Cli { - #[clap(short, long, action)] - top_level: bool, - #[clap(subcommand)] - subcommand: CliSub, -} - -fn main() { - let args = Cli::parse(); - println!("{:#?}", args); -} diff --git a/vendor/clap/examples/derive_ref/interop_tests.md b/vendor/clap/examples/derive_ref/interop_tests.md deleted file mode 100644 index 746fe1878..000000000 --- a/vendor/clap/examples/derive_ref/interop_tests.md +++ /dev/null @@ -1,256 +0,0 @@ -Following are tests for the interop examples in this directory. - -## Augment Args - -```console -$ interop_augment_args -Value of built: false -Value of derived via ArgMatches: false -Value of derived: DerivedArgs { - derived: false, -} - -``` - -```console -$ interop_augment_args -b --derived -Value of built: true -Value of derived via ArgMatches: true -Value of derived: DerivedArgs { - derived: true, -} - -``` - -```console -$ interop_augment_args -d --built -Value of built: true -Value of derived via ArgMatches: true -Value of derived: DerivedArgs { - derived: true, -} - -``` - -```console -$ interop_augment_args --unknown -? failed -error: Found argument '--unknown' which wasn't expected, or isn't valid in this context - - If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` - -USAGE: - interop_augment_args[EXE] [OPTIONS] - -For more information try --help - -``` - -## Augment Subcommands - -```console -$ interop_augment_subcommands -? failed -error: A subcommand is required but one was not provided. -``` - -```console -$ interop_augment_subcommands derived -Derived subcommands: Derived { - derived_flag: false, -} - -``` - -```console -$ interop_augment_subcommands derived --derived-flag -Derived subcommands: Derived { - derived_flag: true, -} - -``` - -```console -$ interop_augment_subcommands derived --unknown -? failed -error: Found argument '--unknown' which wasn't expected, or isn't valid in this context - - If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` - -USAGE: - interop_augment_subcommands[EXE] derived [OPTIONS] - -For more information try --help - -``` - -```console -$ interop_augment_subcommands unknown -? failed -error: Found argument 'unknown' which wasn't expected, or isn't valid in this context - -USAGE: - interop_augment_subcommands[EXE] [SUBCOMMAND] - -For more information try --help - -``` - -## Hand-Implemented Subcommand - -```console -$ interop_hand_subcommand -? failed -error: 'interop_hand_subcommand[EXE]' requires a subcommand but one was not provided - -USAGE: - interop_hand_subcommand[EXE] [OPTIONS] - -For more information try --help - -``` - -```console -$ interop_hand_subcommand add -Cli { - top_level: false, - subcommand: Add( - AddArgs { - name: [], - }, - ), -} - -``` - -```console -$ interop_hand_subcommand add a b c -Cli { - top_level: false, - subcommand: Add( - AddArgs { - name: [ - "a", - "b", - "c", - ], - }, - ), -} - -``` - -```console -$ interop_hand_subcommand add --unknown -? failed -error: Found argument '--unknown' which wasn't expected, or isn't valid in this context - - If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` - -USAGE: - interop_hand_subcommand[EXE] add [NAME]... - -For more information try --help - -``` - -```console -$ interop_hand_subcommand remove -Cli { - top_level: false, - subcommand: Remove( - RemoveArgs { - force: false, - name: [], - }, - ), -} - -``` - -```console -$ interop_hand_subcommand remove --force a b c -Cli { - top_level: false, - subcommand: Remove( - RemoveArgs { - force: true, - name: [ - "a", - "b", - "c", - ], - }, - ), -} - -``` - -```console -$ interop_hand_subcommand unknown -? failed -error: Found argument 'unknown' which wasn't expected, or isn't valid in this context - -USAGE: - interop_hand_subcommand[EXE] [OPTIONS] - -For more information try --help - -``` - -## Flatten Hand-Implemented Args - -```console -$ interop_flatten_hand_args -Cli { - top_level: false, - more_args: CliArgs { - foo: false, - bar: false, - quuz: None, - }, -} - -``` - -```console -$ interop_flatten_hand_args -f --bar -Cli { - top_level: false, - more_args: CliArgs { - foo: true, - bar: true, - quuz: None, - }, -} - -``` - -```console -$ interop_flatten_hand_args --quuz abc -Cli { - top_level: false, - more_args: CliArgs { - foo: false, - bar: false, - quuz: Some( - "abc", - ), - }, -} - -``` - -```console -$ interop_flatten_hand_args --unknown -? failed -error: Found argument '--unknown' which wasn't expected, or isn't valid in this context - - If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` - -USAGE: - interop_flatten_hand_args[EXE] [OPTIONS] - -For more information try --help - -``` diff --git a/vendor/clap/examples/escaped-positional-derive.md b/vendor/clap/examples/escaped-positional-derive.md deleted file mode 100644 index 3b5f8fe56..000000000 --- a/vendor/clap/examples/escaped-positional-derive.md +++ /dev/null @@ -1,65 +0,0 @@ -*Jump to [source](escaped-positional-derive.rs)* - -**This requires enabling the `derive` feature flag.** - -You can use `--` to escape further arguments. - -Let's see what this looks like in the help: -```console -$ escaped-positional-derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - escaped-positional-derive[EXE] [OPTIONS] [-- ...] - -ARGS: - ... - -OPTIONS: - -f - -h, --help Print help information - -p - -V, --version Print version information - -``` - -Here is a baseline without any arguments: -```console -$ escaped-positional-derive --f used: false --p's value: None -'slops' values: [] - -``` - -Notice that we can't pass positional arguments before `--`: -```console -$ escaped-positional-derive foo bar -? failed -error: Found argument 'foo' which wasn't expected, or isn't valid in this context - -USAGE: - escaped-positional-derive[EXE] [OPTIONS] [-- ...] - -For more information try --help - -``` - -But you can after: -```console -$ escaped-positional-derive -f -p=bob -- sloppy slop slop --f used: true --p's value: Some("bob") -'slops' values: ["sloppy", "slop", "slop"] - -``` - -As mentioned, the parser will directly pass everything through: -```console -$ escaped-positional-derive -- -f -p=bob sloppy slop slop --f used: false --p's value: None -'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] - -``` diff --git a/vendor/clap/examples/escaped-positional-derive.rs b/vendor/clap/examples/escaped-positional-derive.rs deleted file mode 100644 index 54dbc853b..000000000 --- a/vendor/clap/examples/escaped-positional-derive.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Note: this requires the `derive` feature - -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(short = 'f', action)] - eff: bool, - - #[clap(short = 'p', value_name = "PEAR", value_parser)] - pea: Option, - - #[clap(last = true, value_parser)] - slop: Vec, -} - -fn main() { - let args = Cli::parse(); - - // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... - println!("-f used: {:?}", args.eff); // -f used: true - println!("-p's value: {:?}", args.pea); // -p's value: Some("bob") - println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"]) - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/escaped-positional.md b/vendor/clap/examples/escaped-positional.md deleted file mode 100644 index 1f71a8736..000000000 --- a/vendor/clap/examples/escaped-positional.md +++ /dev/null @@ -1,65 +0,0 @@ -*Jump to [source](escaped-positional.rs)* - -**This requires enabling the `cargo` feature flag.** - -You can use `--` to escape further arguments. - -Let's see what this looks like in the help: -```console -$ escaped-positional --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - escaped-positional[EXE] [OPTIONS] [-- ...] - -ARGS: - ... - -OPTIONS: - -f - -h, --help Print help information - -p - -V, --version Print version information - -``` - -Here is a baseline without any arguments: -```console -$ escaped-positional --f used: false --p's value: None -'slops' values: [] - -``` - -Notice that we can't pass positional arguments before `--`: -```console -$ escaped-positional foo bar -? failed -error: Found argument 'foo' which wasn't expected, or isn't valid in this context - -USAGE: - escaped-positional[EXE] [OPTIONS] [-- ...] - -For more information try --help - -``` - -But you can after: -```console -$ escaped-positional -f -p=bob -- sloppy slop slop --f used: true --p's value: Some("bob") -'slops' values: ["sloppy", "slop", "slop"] - -``` - -As mentioned, the parser will directly pass everything through: -```console -$ escaped-positional -- -f -p=bob sloppy slop slop --f used: false --p's value: None -'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] - -``` diff --git a/vendor/clap/examples/escaped-positional.rs b/vendor/clap/examples/escaped-positional.rs deleted file mode 100644 index a0fff790b..000000000 --- a/vendor/clap/examples/escaped-positional.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, value_parser, ArgAction}; - -fn main() { - let matches = command!() - .arg(arg!(eff: -f).action(ArgAction::SetTrue)) - .arg( - arg!(pea: -p ) - .required(false) - .value_parser(value_parser!(String)), - ) - .arg( - // Indicates that `slop` is only accessible after `--`. - arg!(slop: [SLOP]) - .multiple_values(true) - .last(true) - .value_parser(value_parser!(String)), - ) - .get_matches(); - - // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... - - // -f used: true - println!( - "-f used: {:?}", - *matches.get_one::("eff").expect("defaulted by clap") - ); - // -p's value: Some("bob") - println!("-p's value: {:?}", matches.get_one::("pea")); - // 'slops' values: Some(["sloppy", "slop", "slop"]) - println!( - "'slops' values: {:?}", - matches - .get_many::("slop") - .map(|vals| vals.collect::>()) - .unwrap_or_default() - ); - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/git-derive.md b/vendor/clap/examples/git-derive.md deleted file mode 100644 index dc27776f5..000000000 --- a/vendor/clap/examples/git-derive.md +++ /dev/null @@ -1,140 +0,0 @@ -*Jump to [source](git-derive.rs)* - -**This requires enabling the `derive` feature flag.** - -Git is an example of several common subcommand patterns. - -Help: -```console -$ git-derive -? failed -git -A fictional versioning CLI - -USAGE: - git-derive[EXE] - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - add adds things - clone Clones repos - help Print this message or the help of the given subcommand(s) - push pushes things - stash - -$ git-derive help -git -A fictional versioning CLI - -USAGE: - git-derive[EXE] - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - add adds things - clone Clones repos - help Print this message or the help of the given subcommand(s) - push pushes things - stash - -$ git-derive help add -git-derive[EXE]-add -adds things - -USAGE: - git-derive[EXE] add ... - -ARGS: - ... Stuff to add - -OPTIONS: - -h, --help Print help information - -``` - -A basic argument: -```console -$ git-derive add -? failed -git-derive[EXE]-add -adds things - -USAGE: - git-derive[EXE] add ... - -ARGS: - ... Stuff to add - -OPTIONS: - -h, --help Print help information - -$ git-derive add Cargo.toml Cargo.lock -Adding ["Cargo.toml", "Cargo.lock"] - -``` - -Default subcommand: -```console -$ git-derive stash -h -git-derive[EXE]-stash - -USAGE: - git-derive[EXE] stash [OPTIONS] - git-derive[EXE] stash - -OPTIONS: - -h, --help Print help information - -m, --message - -SUBCOMMANDS: - apply - help Print this message or the help of the given subcommand(s) - pop - push - -$ git-derive stash push -h -git-derive[EXE]-stash-push - -USAGE: - git-derive[EXE] stash push [OPTIONS] - -OPTIONS: - -h, --help Print help information - -m, --message - -$ git-derive stash pop -h -git-derive[EXE]-stash-pop - -USAGE: - git-derive[EXE] stash pop [STASH] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -$ git-derive stash -m "Prototype" -Pushing StashPush { message: Some("Prototype") } - -$ git-derive stash pop -Popping None - -$ git-derive stash push -m "Prototype" -Pushing StashPush { message: Some("Prototype") } - -$ git-derive stash pop -Popping None - -``` - -External subcommands: -```console -$ git-derive custom-tool arg1 --foo bar -Calling out to "custom-tool" with ["arg1", "--foo", "bar"] - -``` diff --git a/vendor/clap/examples/git-derive.rs b/vendor/clap/examples/git-derive.rs deleted file mode 100644 index ecbda3fe9..000000000 --- a/vendor/clap/examples/git-derive.rs +++ /dev/null @@ -1,107 +0,0 @@ -// Note: this requires the `derive` feature - -use std::ffi::OsString; -use std::path::PathBuf; - -use clap::{Args, Parser, Subcommand}; - -/// A fictional versioning CLI -#[derive(Debug, Parser)] -#[clap(name = "git")] -#[clap(about = "A fictional versioning CLI", long_about = None)] -struct Cli { - #[clap(subcommand)] - command: Commands, -} - -#[derive(Debug, Subcommand)] -enum Commands { - /// Clones repos - #[clap(arg_required_else_help = true)] - Clone { - /// The remote to clone - #[clap(value_parser)] - remote: String, - }, - /// pushes things - #[clap(arg_required_else_help = true)] - Push { - /// The remote to target - #[clap(value_parser)] - remote: String, - }, - /// adds things - #[clap(arg_required_else_help = true)] - Add { - /// Stuff to add - #[clap(required = true, value_parser)] - path: Vec, - }, - Stash(Stash), - #[clap(external_subcommand)] - External(Vec), -} - -#[derive(Debug, Args)] -#[clap(args_conflicts_with_subcommands = true)] -struct Stash { - #[clap(subcommand)] - command: Option, - - #[clap(flatten)] - push: StashPush, -} - -#[derive(Debug, Subcommand)] -enum StashCommands { - Push(StashPush), - Pop { - #[clap(value_parser)] - stash: Option, - }, - Apply { - #[clap(value_parser)] - stash: Option, - }, -} - -#[derive(Debug, Args)] -struct StashPush { - #[clap(short, long, value_parser)] - message: Option, -} - -fn main() { - let args = Cli::parse(); - - match args.command { - Commands::Clone { remote } => { - println!("Cloning {}", remote); - } - Commands::Push { remote } => { - println!("Pushing to {}", remote); - } - Commands::Add { path } => { - println!("Adding {:?}", path); - } - Commands::Stash(stash) => { - let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push)); - match stash_cmd { - StashCommands::Push(push) => { - println!("Pushing {:?}", push); - } - StashCommands::Pop { stash } => { - println!("Popping {:?}", stash); - } - StashCommands::Apply { stash } => { - println!("Applying {:?}", stash); - } - } - } - Commands::External(args) => { - println!("Calling out to {:?} with {:?}", &args[0], &args[1..]); - } - } - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/git.md b/vendor/clap/examples/git.md deleted file mode 100644 index 2cdfe653b..000000000 --- a/vendor/clap/examples/git.md +++ /dev/null @@ -1,138 +0,0 @@ -*Jump to [source](git.rs)* - -Git is an example of several common subcommand patterns. - -Help: -```console -$ git -? failed -git -A fictional versioning CLI - -USAGE: - git[EXE] - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - add adds things - clone Clones repos - help Print this message or the help of the given subcommand(s) - push pushes things - stash - -$ git help -git -A fictional versioning CLI - -USAGE: - git[EXE] - -OPTIONS: - -h, --help Print help information - -SUBCOMMANDS: - add adds things - clone Clones repos - help Print this message or the help of the given subcommand(s) - push pushes things - stash - -$ git help add -git[EXE]-add -adds things - -USAGE: - git[EXE] add ... - -ARGS: - ... Stuff to add - -OPTIONS: - -h, --help Print help information - -``` - -A basic argument: -```console -$ git add -? failed -git[EXE]-add -adds things - -USAGE: - git[EXE] add ... - -ARGS: - ... Stuff to add - -OPTIONS: - -h, --help Print help information - -$ git add Cargo.toml Cargo.lock -Adding ["Cargo.toml", "Cargo.lock"] - -``` - -Default subcommand: -```console -$ git stash -h -git[EXE]-stash - -USAGE: - git[EXE] stash [OPTIONS] - git[EXE] stash - -OPTIONS: - -h, --help Print help information - -m, --message - -SUBCOMMANDS: - apply - help Print this message or the help of the given subcommand(s) - pop - push - -$ git stash push -h -git[EXE]-stash-push - -USAGE: - git[EXE] stash push [OPTIONS] - -OPTIONS: - -h, --help Print help information - -m, --message - -$ git stash pop -h -git[EXE]-stash-pop - -USAGE: - git[EXE] stash pop [STASH] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -$ git stash -m "Prototype" -Pushing Some("Prototype") - -$ git stash pop -Popping None - -$ git stash push -m "Prototype" -Pushing Some("Prototype") - -$ git stash pop -Popping None - -``` - -External subcommands: -```console -$ git custom-tool arg1 --foo bar -Calling out to "custom-tool" with ["arg1", "--foo", "bar"] - -``` diff --git a/vendor/clap/examples/git.rs b/vendor/clap/examples/git.rs deleted file mode 100644 index 5536f1487..000000000 --- a/vendor/clap/examples/git.rs +++ /dev/null @@ -1,103 +0,0 @@ -// Note: this requires the `cargo` feature - -use std::ffi::OsString; -use std::path::PathBuf; - -use clap::{arg, Command}; - -fn cli() -> Command<'static> { - Command::new("git") - .about("A fictional versioning CLI") - .subcommand_required(true) - .arg_required_else_help(true) - .allow_external_subcommands(true) - .allow_invalid_utf8_for_external_subcommands(true) - .subcommand( - Command::new("clone") - .about("Clones repos") - .arg(arg!( "The remote to clone")) - .arg_required_else_help(true), - ) - .subcommand( - Command::new("push") - .about("pushes things") - .arg(arg!( "The remote to target")) - .arg_required_else_help(true), - ) - .subcommand( - Command::new("add") - .about("adds things") - .arg_required_else_help(true) - .arg(arg!( ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))), - ) - .subcommand( - Command::new("stash") - .args_conflicts_with_subcommands(true) - .args(push_args()) - .subcommand(Command::new("push").args(push_args())) - .subcommand(Command::new("pop").arg(arg!([STASH]))) - .subcommand(Command::new("apply").arg(arg!([STASH]))), - ) -} - -fn push_args() -> Vec> { - vec![arg!(-m --message ).required(false)] -} - -fn main() { - let matches = cli().get_matches(); - - match matches.subcommand() { - Some(("clone", sub_matches)) => { - println!( - "Cloning {}", - sub_matches.get_one::("REMOTE").expect("required") - ); - } - Some(("push", sub_matches)) => { - println!( - "Pushing to {}", - sub_matches.get_one::("REMOTE").expect("required") - ); - } - Some(("add", sub_matches)) => { - let paths = sub_matches - .get_many::("PATH") - .into_iter() - .flatten() - .collect::>(); - println!("Adding {:?}", paths); - } - Some(("stash", sub_matches)) => { - let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches)); - match stash_command { - ("apply", sub_matches) => { - let stash = sub_matches.get_one::("STASH"); - println!("Applying {:?}", stash); - } - ("pop", sub_matches) => { - let stash = sub_matches.get_one::("STASH"); - println!("Popping {:?}", stash); - } - ("push", sub_matches) => { - let message = sub_matches.get_one::("message"); - println!("Pushing {:?}", message); - } - (name, _) => { - unreachable!("Unsupported subcommand `{}`", name) - } - } - } - Some((ext, sub_matches)) => { - let args = sub_matches - .get_many::("") - .into_iter() - .flatten() - .collect::>(); - println!("Calling out to {:?} with {:?}", ext, args); - } - _ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!() - } - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/multicall-busybox.md b/vendor/clap/examples/multicall-busybox.md deleted file mode 100644 index a09418403..000000000 --- a/vendor/clap/examples/multicall-busybox.md +++ /dev/null @@ -1,46 +0,0 @@ -*Jump to [source](multicall-busybox.rs)* - -Example of a busybox-style multicall program - -See the documentation for `clap::Command::multicall` for rationale. - -This example omits every command except true and false, -which are the most trivial to implement, -```console -$ busybox true -? 0 - -$ busybox false -? 1 - -``` -*Note: without the links setup, we can't demonstrate the multicall behavior* - -But includes the `--install` option as an example of why it can be useful -for the main program to take arguments that aren't applet subcommands. -```console -$ busybox --install -? failed -... - -``` - -Though users must pass something: -```console -$ busybox -? failed -busybox - -USAGE: - busybox [OPTIONS] [APPLET] - -OPTIONS: - -h, --help Print help information - --install Install hardlinks for all subcommands in path - -APPLETS: - false does nothing unsuccessfully - help Print this message or the help of the given subcommand(s) - true does nothing successfully - -``` diff --git a/vendor/clap/examples/multicall-busybox.rs b/vendor/clap/examples/multicall-busybox.rs deleted file mode 100644 index 2e7f976c1..000000000 --- a/vendor/clap/examples/multicall-busybox.rs +++ /dev/null @@ -1,48 +0,0 @@ -use std::path::PathBuf; -use std::process::exit; - -use clap::{value_parser, Arg, Command}; - -fn applet_commands() -> [Command<'static>; 2] { - [ - Command::new("true").about("does nothing successfully"), - Command::new("false").about("does nothing unsuccessfully"), - ] -} - -fn main() { - let cmd = Command::new(env!("CARGO_CRATE_NAME")) - .multicall(true) - .subcommand( - Command::new("busybox") - .arg_required_else_help(true) - .subcommand_value_name("APPLET") - .subcommand_help_heading("APPLETS") - .arg( - Arg::new("install") - .long("install") - .help("Install hardlinks for all subcommands in path") - .exclusive(true) - .takes_value(true) - .default_missing_value("/usr/local/bin") - .value_parser(value_parser!(PathBuf)) - .use_value_delimiter(false), - ) - .subcommands(applet_commands()), - ) - .subcommands(applet_commands()); - - let matches = cmd.get_matches(); - let mut subcommand = matches.subcommand(); - if let Some(("busybox", cmd)) = subcommand { - if cmd.contains_id("install") { - unimplemented!("Make hardlinks to the executable here"); - } - subcommand = cmd.subcommand(); - } - match subcommand { - Some(("false", _)) => exit(1), - Some(("true", _)) => exit(0), - _ => unreachable!("parser should ensure only valid subcommand names are used"), - } -} diff --git a/vendor/clap/examples/multicall-hostname.md b/vendor/clap/examples/multicall-hostname.md deleted file mode 100644 index 9e17ca16c..000000000 --- a/vendor/clap/examples/multicall-hostname.md +++ /dev/null @@ -1,14 +0,0 @@ -*Jump to [source](multicall-hostname.rs)* - -Example of a `hostname-style` multicall program - -See the documentation for `clap::Command::multicall` for rationale. - -This example omits the implementation of displaying address config - -```console -$ hostname -www - -``` -*Note: without the links setup, we can't demonstrate the multicall behavior* diff --git a/vendor/clap/examples/multicall-hostname.rs b/vendor/clap/examples/multicall-hostname.rs deleted file mode 100644 index b57680a5c..000000000 --- a/vendor/clap/examples/multicall-hostname.rs +++ /dev/null @@ -1,17 +0,0 @@ -use clap::Command; - -fn main() { - let cmd = Command::new(env!("CARGO_CRATE_NAME")) - .multicall(true) - .arg_required_else_help(true) - .subcommand_value_name("APPLET") - .subcommand_help_heading("APPLETS") - .subcommand(Command::new("hostname").about("show hostname part of FQDN")) - .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN")); - - match cmd.get_matches().subcommand_name() { - Some("hostname") => println!("www"), - Some("dnsdomainname") => println!("example.com"), - _ => unreachable!("parser should ensure only valid subcommand names are used"), - } -} diff --git a/vendor/clap/examples/pacman.md b/vendor/clap/examples/pacman.md deleted file mode 100644 index 7f6c5a7d3..000000000 --- a/vendor/clap/examples/pacman.md +++ /dev/null @@ -1,87 +0,0 @@ -*Jump to [source](pacman.rs)* - -[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags. - -Here, `-S` is a short flag subcommand: -```console -$ pacman -S package -Installing package... - -``` - -Here `--sync` is a long flag subcommand: -```console -$ pacman --sync package -Installing package... - -``` - -Now the short flag subcommand (`-S`) with a long flag: -```console -$ pacman -S --search name -Searching for name... - -``` - -And the various forms of short flags that work: -```console -$ pacman -S -s name -Searching for name... - -$ pacman -Ss name -Searching for name... - -``` -*(users can "stack" short subcommands with short flags or with other short flag subcommands)* - -In the help, this looks like: -```console -$ pacman -h -pacman 5.2.1 -Pacman Development Team -package manager utility - -USAGE: - pacman[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - help Print this message or the help of the given subcommand(s) - query -Q --query Query the package database. - sync -S --sync Synchronize packages. - -$ pacman -S -h -pacman[EXE]-sync -Synchronize packages. - -USAGE: - pacman[EXE] {sync|--sync|-S} [OPTIONS] [--] [package]... - -ARGS: - ... packages - -OPTIONS: - -h, --help Print help information - -i, --info view package information - -s, --search ... search remote repositories for matching strings - -``` - -And errors: -```console -$ pacman -S -s foo -i bar -? failed -error: The argument '--search ...' cannot be used with '--info' - -USAGE: - pacman[EXE] {sync|--sync|-S} --search ... ... - -For more information try --help - -``` - -**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated. -Let's make a quick program to illustrate. diff --git a/vendor/clap/examples/pacman.rs b/vendor/clap/examples/pacman.rs deleted file mode 100644 index 6a60a8bf5..000000000 --- a/vendor/clap/examples/pacman.rs +++ /dev/null @@ -1,114 +0,0 @@ -use clap::{Arg, ArgAction, Command}; - -fn main() { - let matches = Command::new("pacman") - .about("package manager utility") - .version("5.2.1") - .subcommand_required(true) - .arg_required_else_help(true) - .author("Pacman Development Team") - // Query subcommand - // - // Only a few of its arguments are implemented below. - .subcommand( - Command::new("query") - .short_flag('Q') - .long_flag("query") - .about("Query the package database.") - .arg( - Arg::new("search") - .short('s') - .long("search") - .help("search locally installed packages for matching strings") - .conflicts_with("info") - .takes_value(true) - .multiple_values(true), - ) - .arg( - Arg::new("info") - .long("info") - .short('i') - .conflicts_with("search") - .help("view package information") - .takes_value(true) - .multiple_values(true), - ), - ) - // Sync subcommand - // - // Only a few of its arguments are implemented below. - .subcommand( - Command::new("sync") - .short_flag('S') - .long_flag("sync") - .about("Synchronize packages.") - .arg( - Arg::new("search") - .short('s') - .long("search") - .conflicts_with("info") - .takes_value(true) - .multiple_values(true) - .help("search remote repositories for matching strings"), - ) - .arg( - Arg::new("info") - .long("info") - .conflicts_with("search") - .short('i') - .action(ArgAction::SetTrue) - .help("view package information"), - ) - .arg( - Arg::new("package") - .help("packages") - .required_unless_present("search") - .takes_value(true) - .multiple_values(true), - ), - ) - .get_matches(); - - match matches.subcommand() { - Some(("sync", sync_matches)) => { - if sync_matches.contains_id("search") { - let packages: Vec<_> = sync_matches - .get_many::("search") - .expect("contains_id") - .map(|s| s.as_str()) - .collect(); - let values = packages.join(", "); - println!("Searching for {}...", values); - return; - } - - let packages: Vec<_> = sync_matches - .get_many::("package") - .expect("is present") - .map(|s| s.as_str()) - .collect(); - let values = packages.join(", "); - - if *sync_matches - .get_one::("info") - .expect("defaulted by clap") - { - println!("Retrieving info for {}...", values); - } else { - println!("Installing {}...", values); - } - } - Some(("query", query_matches)) => { - if let Some(packages) = query_matches.get_many::("info") { - let comma_sep = packages.map(|s| s.as_str()).collect::>().join(", "); - println!("Retrieving info for {}...", comma_sep); - } else if let Some(queries) = query_matches.get_many::("search") { - let comma_sep = queries.map(|s| s.as_str()).collect::>().join(", "); - println!("Searching Locally for {}...", comma_sep); - } else { - println!("Displaying all locally installed packages..."); - } - } - _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable - } -} diff --git a/vendor/clap/examples/repl.rs b/vendor/clap/examples/repl.rs deleted file mode 100644 index c509adee6..000000000 --- a/vendor/clap/examples/repl.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::io::Write; - -use clap::Command; - -fn main() -> Result<(), String> { - loop { - let line = readline()?; - let line = line.trim(); - if line.is_empty() { - continue; - } - - match respond(line) { - Ok(quit) => { - if quit { - break; - } - } - Err(err) => { - write!(std::io::stdout(), "{}", err).map_err(|e| e.to_string())?; - std::io::stdout().flush().map_err(|e| e.to_string())?; - } - } - } - - Ok(()) -} - -fn respond(line: &str) -> Result { - let args = shlex::split(line).ok_or("error: Invalid quoting")?; - let matches = cli() - .try_get_matches_from(&args) - .map_err(|e| e.to_string())?; - match matches.subcommand() { - Some(("ping", _matches)) => { - write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?; - std::io::stdout().flush().map_err(|e| e.to_string())?; - } - Some(("quit", _matches)) => { - write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?; - std::io::stdout().flush().map_err(|e| e.to_string())?; - return Ok(true); - } - Some((name, _matches)) => unimplemented!("{}", name), - None => unreachable!("subcommand required"), - } - - Ok(false) -} - -fn cli() -> Command<'static> { - // strip out usage - const PARSER_TEMPLATE: &str = "\ - {all-args} - "; - // strip out name/version - const APPLET_TEMPLATE: &str = "\ - {about-with-newline}\n\ - {usage-heading}\n {usage}\n\ - \n\ - {all-args}{after-help}\ - "; - - Command::new("repl") - .multicall(true) - .arg_required_else_help(true) - .subcommand_required(true) - .subcommand_value_name("APPLET") - .subcommand_help_heading("APPLETS") - .help_template(PARSER_TEMPLATE) - .subcommand( - Command::new("ping") - .about("Get a response") - .help_template(APPLET_TEMPLATE), - ) - .subcommand( - Command::new("quit") - .alias("exit") - .about("Quit the REPL") - .help_template(APPLET_TEMPLATE), - ) -} - -fn readline() -> Result { - write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?; - std::io::stdout().flush().map_err(|e| e.to_string())?; - let mut buffer = String::new(); - std::io::stdin() - .read_line(&mut buffer) - .map_err(|e| e.to_string())?; - Ok(buffer) -} diff --git a/vendor/clap/examples/tutorial_builder/01_quick.rs b/vendor/clap/examples/tutorial_builder/01_quick.rs deleted file mode 100644 index 61cc3432d..000000000 --- a/vendor/clap/examples/tutorial_builder/01_quick.rs +++ /dev/null @@ -1,65 +0,0 @@ -// Note: this requires the `cargo` feature - -use std::path::PathBuf; - -use clap::{arg, command, value_parser, ArgAction, Command}; - -fn main() { - let matches = command!() - .arg(arg!([name] "Optional name to operate on")) - .arg( - arg!( - -c --config "Sets a custom config file" - ) - // We don't have syntax yet for optional options, so manually calling `required` - .required(false) - .value_parser(value_parser!(PathBuf)), - ) - .arg( - arg!( - -d --debug "Turn debugging information on" - ) - .action(ArgAction::Count), - ) - .subcommand( - Command::new("test") - .about("does testing things") - .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)), - ) - .get_matches(); - - // You can check the value provided by positional arguments, or option arguments - if let Some(name) = matches.get_one::("name") { - println!("Value for name: {}", name); - } - - if let Some(config_path) = matches.get_one::("config") { - println!("Value for config: {}", config_path.display()); - } - - // You can see how many times a particular flag or argument occurred - // Note, only flags can have multiple occurrences - match matches - .get_one::("debug") - .expect("Count's are defaulted") - { - 0 => println!("Debug mode is off"), - 1 => println!("Debug mode is kind of on"), - 2 => println!("Debug mode is on"), - _ => println!("Don't be crazy"), - } - - // You can check for the existence of subcommands, and if found use their - // matches just as you would the top level cmd - if let Some(matches) = matches.subcommand_matches("test") { - // "$ myapp test" was run - if *matches.get_one::("list").expect("defaulted by clap") { - // "$ myapp test -l" was run - println!("Printing testing lists..."); - } else { - println!("Not printing testing lists..."); - } - } - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/tutorial_builder/02_app_settings.rs b/vendor/clap/examples/tutorial_builder/02_app_settings.rs deleted file mode 100644 index 7bbedd3eb..000000000 --- a/vendor/clap/examples/tutorial_builder/02_app_settings.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, AppSettings, ArgAction}; - -fn main() { - let matches = command!() - .global_setting(AppSettings::DeriveDisplayOrder) - .allow_negative_numbers(true) - .arg(arg!(--two ).action(ArgAction::Set)) - .arg(arg!(--one ).action(ArgAction::Set)) - .get_matches(); - - println!( - "two: {:?}", - matches.get_one::("two").expect("required") - ); - println!( - "one: {:?}", - matches.get_one::("one").expect("required") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/02_apps.rs b/vendor/clap/examples/tutorial_builder/02_apps.rs deleted file mode 100644 index db9da18f9..000000000 --- a/vendor/clap/examples/tutorial_builder/02_apps.rs +++ /dev/null @@ -1,20 +0,0 @@ -use clap::{arg, Command}; - -fn main() { - let matches = Command::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .arg(arg!(--two )) - .arg(arg!(--one )) - .get_matches(); - - println!( - "two: {:?}", - matches.get_one::("two").expect("required") - ); - println!( - "one: {:?}", - matches.get_one::("one").expect("required") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/02_crate.rs b/vendor/clap/examples/tutorial_builder/02_crate.rs deleted file mode 100644 index 16b7e7ee0..000000000 --- a/vendor/clap/examples/tutorial_builder/02_crate.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command}; - -fn main() { - let matches = command!() - .arg(arg!(--two )) - .arg(arg!(--one )) - .get_matches(); - - println!( - "two: {:?}", - matches.get_one::("two").expect("required") - ); - println!( - "one: {:?}", - matches.get_one::("one").expect("required") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs b/vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs deleted file mode 100644 index 41ecbb1d7..000000000 --- a/vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{command, Arg, ArgAction}; - -fn main() { - let matches = command!() - .arg( - Arg::new("verbose") - .short('v') - .long("verbose") - .action(ArgAction::SetTrue), - ) - .get_matches(); - - println!( - "verbose: {:?}", - *matches - .get_one::("verbose") - .expect("defaulted by clap") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/03_01_flag_count.rs b/vendor/clap/examples/tutorial_builder/03_01_flag_count.rs deleted file mode 100644 index 764affbd8..000000000 --- a/vendor/clap/examples/tutorial_builder/03_01_flag_count.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, ArgAction}; - -fn main() { - let matches = command!() - .arg(arg!(-v - -verbose).action(ArgAction::Count)) - .get_matches(); - - println!( - "verbose: {:?}", - matches - .get_one::("verbose") - .expect("Count always defaulted") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/03_02_option.rs b/vendor/clap/examples/tutorial_builder/03_02_option.rs deleted file mode 100644 index 80e2b9159..000000000 --- a/vendor/clap/examples/tutorial_builder/03_02_option.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command}; - -fn main() { - let matches = command!() - .arg(arg!(-n --name ).required(false)) - .get_matches(); - - println!("name: {:?}", matches.get_one::("name")); -} diff --git a/vendor/clap/examples/tutorial_builder/03_03_positional.rs b/vendor/clap/examples/tutorial_builder/03_03_positional.rs deleted file mode 100644 index c6579409a..000000000 --- a/vendor/clap/examples/tutorial_builder/03_03_positional.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command}; - -fn main() { - let matches = command!().arg(arg!([NAME])).get_matches(); - - println!("NAME: {:?}", matches.get_one::("NAME")); -} diff --git a/vendor/clap/examples/tutorial_builder/03_04_subcommands.rs b/vendor/clap/examples/tutorial_builder/03_04_subcommands.rs deleted file mode 100644 index 1dd1cbf09..000000000 --- a/vendor/clap/examples/tutorial_builder/03_04_subcommands.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, Command}; - -fn main() { - let matches = command!() - .propagate_version(true) - .subcommand_required(true) - .arg_required_else_help(true) - .subcommand( - Command::new("add") - .about("Adds files to myapp") - .arg(arg!([NAME])), - ) - .get_matches(); - - match matches.subcommand() { - Some(("add", sub_matches)) => println!( - "'myapp add' was used, name is: {:?}", - sub_matches.get_one::("NAME") - ), - _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"), - } -} diff --git a/vendor/clap/examples/tutorial_builder/03_05_default_values.rs b/vendor/clap/examples/tutorial_builder/03_05_default_values.rs deleted file mode 100644 index c68e87973..000000000 --- a/vendor/clap/examples/tutorial_builder/03_05_default_values.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command}; - -fn main() { - let matches = command!() - .arg(arg!([NAME]).default_value("alice")) - .get_matches(); - - println!( - "NAME: {:?}", - matches - .get_one::("NAME") - .expect("default ensures there is always a value") - ); -} diff --git a/vendor/clap/examples/tutorial_builder/04_01_enum.rs b/vendor/clap/examples/tutorial_builder/04_01_enum.rs deleted file mode 100644 index ad2177c23..000000000 --- a/vendor/clap/examples/tutorial_builder/04_01_enum.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, value_parser, ValueEnum}; - -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] -enum Mode { - Fast, - Slow, -} - -fn main() { - let matches = command!() - .arg( - arg!() - .help("What mode to run the program in") - .value_parser(value_parser!(Mode)), - ) - .get_matches(); - - // Note, it's safe to call unwrap() because the arg is required - match matches - .get_one::("MODE") - .expect("'MODE' is required and parsing will fail if its missing") - { - Mode::Fast => { - println!("Hare"); - } - Mode::Slow => { - println!("Tortoise"); - } - } -} diff --git a/vendor/clap/examples/tutorial_builder/04_01_possible.rs b/vendor/clap/examples/tutorial_builder/04_01_possible.rs deleted file mode 100644 index f7b0cfb34..000000000 --- a/vendor/clap/examples/tutorial_builder/04_01_possible.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command}; - -fn main() { - let matches = command!() - .arg( - arg!() - .help("What mode to run the program in") - .value_parser(["fast", "slow"]), - ) - .get_matches(); - - // Note, it's safe to call unwrap() because the arg is required - match matches - .get_one::("MODE") - .expect("'MODE' is required and parsing will fail if its missing") - .as_str() - { - "fast" => { - println!("Hare"); - } - "slow" => { - println!("Tortoise"); - } - _ => unreachable!(), - } -} diff --git a/vendor/clap/examples/tutorial_builder/04_02_parse.rs b/vendor/clap/examples/tutorial_builder/04_02_parse.rs deleted file mode 100644 index c2f3cc533..000000000 --- a/vendor/clap/examples/tutorial_builder/04_02_parse.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, value_parser}; - -fn main() { - let matches = command!() - .arg( - arg!() - .help("Network port to use") - .value_parser(value_parser!(u16).range(1..)), - ) - .get_matches(); - - // Note, it's safe to call unwrap() because the arg is required - let port: u16 = *matches - .get_one::("PORT") - .expect("'PORT' is required and parsing will fail if its missing"); - println!("PORT = {}", port); -} diff --git a/vendor/clap/examples/tutorial_builder/04_02_validate.rs b/vendor/clap/examples/tutorial_builder/04_02_validate.rs deleted file mode 100644 index e60018a46..000000000 --- a/vendor/clap/examples/tutorial_builder/04_02_validate.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Note: this requires the `cargo` feature - -use std::ops::RangeInclusive; - -use clap::{arg, command}; - -fn main() { - let matches = command!() - .arg( - arg!() - .help("Network port to use") - .value_parser(port_in_range), - ) - .get_matches(); - - // Note, it's safe to call unwrap() because the arg is required - let port: u16 = *matches - .get_one::("PORT") - .expect("'PORT' is required and parsing will fail if its missing"); - println!("PORT = {}", port); -} - -const PORT_RANGE: RangeInclusive = 1..=65535; - -fn port_in_range(s: &str) -> Result { - let port: usize = s - .parse() - .map_err(|_| format!("`{}` isn't a port number", s))?; - if PORT_RANGE.contains(&port) { - Ok(port as u16) - } else { - Err(format!( - "Port not in range {}-{}", - PORT_RANGE.start(), - PORT_RANGE.end() - )) - } -} diff --git a/vendor/clap/examples/tutorial_builder/04_03_relations.rs b/vendor/clap/examples/tutorial_builder/04_03_relations.rs deleted file mode 100644 index 605e5b48e..000000000 --- a/vendor/clap/examples/tutorial_builder/04_03_relations.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Note: this requires the `cargo` feature - -use std::path::PathBuf; - -use clap::{arg, command, value_parser, ArgAction, ArgGroup}; - -fn main() { - // Create application like normal - let matches = command!() - // Add the version arguments - .arg(arg!(--"set-ver" "set version manually").required(false)) - .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) - .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue)) - .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue)) - // Create a group, make it required, and add the above arguments - .group( - ArgGroup::new("vers") - .required(true) - .args(&["set-ver", "major", "minor", "patch"]), - ) - // Arguments can also be added to a group individually, these two arguments - // are part of the "input" group which is not required - .arg( - arg!([INPUT_FILE] "some regular input") - .value_parser(value_parser!(PathBuf)) - .group("input"), - ) - .arg( - arg!(--"spec-in" "some special input argument") - .required(false) - .value_parser(value_parser!(PathBuf)) - .group("input"), - ) - // Now let's assume we have a -c [config] argument which requires one of - // (but **not** both) the "input" arguments - .arg( - arg!(config: -c ) - .required(false) - .value_parser(value_parser!(PathBuf)) - .requires("input"), - ) - .get_matches(); - - // Let's assume the old version 1.2.3 - let mut major = 1; - let mut minor = 2; - let mut patch = 3; - - // See if --set-ver was used to set the version manually - let version = if let Some(ver) = matches.get_one::("set-ver") { - ver.to_owned() - } else { - // Increment the one requested (in a real program, we'd reset the lower numbers) - let (maj, min, pat) = ( - *matches.get_one::("major").expect("defaulted by clap"), - *matches.get_one::("minor").expect("defaulted by clap"), - *matches.get_one::("patch").expect("defaulted by clap"), - ); - match (maj, min, pat) { - (true, _, _) => major += 1, - (_, true, _) => minor += 1, - (_, _, true) => patch += 1, - _ => unreachable!(), - }; - format!("{}.{}.{}", major, minor, patch) - }; - - println!("Version: {}", version); - - // Check for usage of -c - if matches.contains_id("config") { - let input = matches - .get_one::("INPUT_FILE") - .unwrap_or_else(|| matches.get_one::("spec-in").unwrap()) - .display(); - println!( - "Doing work using input {} and config {}", - input, - matches.get_one::("config").unwrap().display() - ); - } -} diff --git a/vendor/clap/examples/tutorial_builder/04_04_custom.rs b/vendor/clap/examples/tutorial_builder/04_04_custom.rs deleted file mode 100644 index 3dc080505..000000000 --- a/vendor/clap/examples/tutorial_builder/04_04_custom.rs +++ /dev/null @@ -1,93 +0,0 @@ -// Note: this requires the `cargo` feature - -use std::path::PathBuf; - -use clap::{arg, command, value_parser, ArgAction, ErrorKind}; - -fn main() { - // Create application like normal - let mut cmd = command!() - // Add the version arguments - .arg(arg!(--"set-ver" "set version manually").required(false)) - .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) - .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue)) - .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue)) - // Arguments can also be added to a group individually, these two arguments - // are part of the "input" group which is not required - .arg(arg!([INPUT_FILE] "some regular input").value_parser(value_parser!(PathBuf))) - .arg( - arg!(--"spec-in" "some special input argument") - .required(false) - .value_parser(value_parser!(PathBuf)), - ) - // Now let's assume we have a -c [config] argument which requires one of - // (but **not** both) the "input" arguments - .arg( - arg!(config: -c ) - .required(false) - .value_parser(value_parser!(PathBuf)), - ); - let matches = cmd.get_matches_mut(); - - // Let's assume the old version 1.2.3 - let mut major = 1; - let mut minor = 2; - let mut patch = 3; - - // See if --set-ver was used to set the version manually - let version = if let Some(ver) = matches.get_one::("set-ver") { - if *matches.get_one::("major").expect("defaulted by clap") - || *matches.get_one::("minor").expect("defaulted by clap") - || *matches.get_one::("patch").expect("defaulted by clap") - { - cmd.error( - ErrorKind::ArgumentConflict, - "Can't do relative and absolute version change", - ) - .exit(); - } - ver.to_string() - } else { - // Increment the one requested (in a real program, we'd reset the lower numbers) - let (maj, min, pat) = ( - *matches.get_one::("major").expect("defaulted by clap"), - *matches.get_one::("minor").expect("defaulted by clap"), - *matches.get_one::("patch").expect("defaulted by clap"), - ); - match (maj, min, pat) { - (true, false, false) => major += 1, - (false, true, false) => minor += 1, - (false, false, true) => patch += 1, - _ => { - cmd.error( - ErrorKind::ArgumentConflict, - "Can only modify one version field", - ) - .exit(); - } - }; - format!("{}.{}.{}", major, minor, patch) - }; - - println!("Version: {}", version); - - // Check for usage of -c - if matches.contains_id("config") { - let input = matches - .get_one::("INPUT_FILE") - .or_else(|| matches.get_one::("spec-in")) - .unwrap_or_else(|| { - cmd.error( - ErrorKind::MissingRequiredArgument, - "INPUT_FILE or --spec-in is required when using --config", - ) - .exit() - }) - .display(); - println!( - "Doing work using input {} and config {}", - input, - matches.get_one::("config").unwrap().display() - ); - } -} diff --git a/vendor/clap/examples/tutorial_builder/05_01_assert.rs b/vendor/clap/examples/tutorial_builder/05_01_assert.rs deleted file mode 100644 index d6f19ffe5..000000000 --- a/vendor/clap/examples/tutorial_builder/05_01_assert.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Note: this requires the `cargo` feature - -use clap::{arg, command, value_parser}; - -fn main() { - let matches = cmd().get_matches(); - - // Note, it's safe to call unwrap() because the arg is required - let port: usize = *matches - .get_one::("PORT") - .expect("'PORT' is required and parsing will fail if its missing"); - println!("PORT = {}", port); -} - -fn cmd() -> clap::Command<'static> { - command!().arg( - arg!() - .help("Network port to use") - .value_parser(value_parser!(usize)), - ) -} - -#[test] -fn verify_app() { - cmd().debug_assert(); -} diff --git a/vendor/clap/examples/tutorial_builder/README.md b/vendor/clap/examples/tutorial_builder/README.md deleted file mode 100644 index 945b01e72..000000000 --- a/vendor/clap/examples/tutorial_builder/README.md +++ /dev/null @@ -1,658 +0,0 @@ -# Tutorial - -*Jump to [derive tutorial](../tutorial_derive/README.md)* - -1. [Quick Start](#quick-start) -2. [Configuring the Parser](#configuring-the-parser) -3. [Adding Arguments](#adding-arguments) - 1. [Positionals](#positionals) - 2. [Options](#options) - 3. [Flags](#flags) - 4. [Subcommands](#subcommands) - 5. [Defaults](#defaults) -4. Validation - 1. [Enumerated values](#enumerated-values) - 2. [Validated values](#validated-values) - 3. [Argument Relations](#argument-relations) - 4. [Custom Validation](#custom-validation) -5. [Tips](#tips) -6. [Contributing](#contributing) - -## Quick Start - -You can create an application with several arguments using usage strings. - -[Example:](01_quick.rs) -```console -$ 01_quick --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] - -ARGS: - Optional name to operate on - -OPTIONS: - -c, --config Sets a custom config file - -d, --debug Turn debugging information on - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - help Print this message or the help of the given subcommand(s) - test does testing things - -``` - -By default, the program does nothing: -```console -$ 01_quick -Debug mode is off - -``` - -But you can mix and match the various features -```console -$ 01_quick -dd test -Debug mode is on -Not printing testing lists... - -``` - -## Configuring the Parser - -You use the `Command` the start building a parser. - -[Example:](02_apps.rs) -```console -$ 02_apps --help -MyApp 1.0 -Kevin K. -Does awesome things - -USAGE: - 02_apps[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_apps --version -MyApp 1.0 - -``` - -You can use `command!()` to fill these fields in from your `Cargo.toml` -file. **This requires the `cargo` feature flag.** - -[Example:](02_crate.rs) -```console -$ 02_crate --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_crate[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_crate --version -clap [..] - -``` - -You can use `Command` methods to change the application level behavior of clap. - -[Example:](02_app_settings.rs) -```console -$ 02_app_settings --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_app_settings[EXE] --two --one - -OPTIONS: - --two - --one - -h, --help Print help information - -V, --version Print version information - -$ 02_app_settings --one -1 --one -3 --two 10 -two: "10" -one: "-3" - -``` - -## Adding Arguments - -### Positionals - -You can have users specify values by their position on the command-line: - -[Example:](03_03_positional.rs) -```console -$ 03_03_positional --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_03_positional[EXE] [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_03_positional -NAME: None - -$ 03_03_positional bob -NAME: Some("bob") - -``` - -### Options - -You can name your arguments with a flag: -- Order doesn't matter -- They can be optional -- Intent is clearer - -[Example:](03_02_option.rs) -```console -$ 03_02_option --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_02_option[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -n, --name - -V, --version Print version information - -$ 03_02_option -name: None - -$ 03_02_option --name bob -name: Some("bob") - -$ 03_02_option --name=bob -name: Some("bob") - -$ 03_02_option -n bob -name: Some("bob") - -$ 03_02_option -n=bob -name: Some("bob") - -$ 03_02_option -nbob -name: Some("bob") - -``` - -### Flags - -Flags can also be switches that can be on/off: - -[Example:](03_01_flag_bool.rs) -```console -$ 03_01_flag_bool --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_bool[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_bool -verbose: false - -$ 03_01_flag_bool --verbose -verbose: true - -$ 03_01_flag_bool --verbose --verbose -verbose: true - -``` - -Or counted. - -[Example:](03_01_flag_count.rs) -```console -$ 03_01_flag_count --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_count[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_count -verbose: 0 - -$ 03_01_flag_count --verbose -verbose: 1 - -$ 03_01_flag_count --verbose --verbose -verbose: 2 - -``` - -### Subcommands - -Subcommands are defined as `Command`s that get added via `Command::subcommand`. Each -instance of a Subcommand can have its own version, author(s), Args, and even its own -subcommands. - -[Example:](03_04_subcommands.rs) -```console -$ 03_04_subcommands help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -$ 03_04_subcommands help add -03_04_subcommands[EXE]-add [..] -Adds files to myapp - -USAGE: - 03_04_subcommands[EXE] add [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_04_subcommands add bob -'myapp add' was used, name is: Some("bob") - -``` - -Because we set `Command::arg_required_else_help`: -```console -$ 03_04_subcommands -? failed -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -``` - -Because we set `Command::propagate_version`: -```console -$ 03_04_subcommands --version -clap [..] - -$ 03_04_subcommands add --version -03_04_subcommands[EXE]-add [..] - -``` - -### Defaults - -We've previously showed that arguments can be `required` or optional. When -optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can -set `Arg::default_value`. - -[Example:](03_05_default_values.rs) -```console -$ 03_05_default_values --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_05_default_values[EXE] [NAME] - -ARGS: - [default: alice] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_05_default_values -NAME: "alice" - -$ 03_05_default_values bob -NAME: "bob" - -``` - -## Validation - -### Enumerated values - -If you have arguments of specific values you want to test for, you can use the -`PossibleValuesParser` or `Arg::value_parser(["val1", ...])` for short. - -This allows you specify the valid values for that argument. If the user does not use one of -those specific values, they will receive a graceful exit with error message informing them -of the mistake, and what the possible valid values are - -[Example:](04_01_possible.rs) -```console -$ 04_01_possible --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_possible[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_possible fast -Hare - -$ 04_01_possible slow -Tortoise - -$ 04_01_possible medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -When enabling the `derive` feature, you can use `ValueEnum` to take care of the boiler plate for you, giving the same results. - -[Example:](04_01_enum.rs) -```console -$ 04_01_enum --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_enum[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_enum fast -Hare - -$ 04_01_enum slow -Tortoise - -$ 04_01_enum medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -### Validated values - -More generally, you can validate and parse into any data type. - -[Example:](04_02_parse.rs) -```console -$ 04_02_parse --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_parse[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_parse 22 -PORT = 22 - -$ 04_02_parse foobar -? failed -error: Invalid value "foobar" for '': invalid digit found in string - -For more information try --help - -$ 04_02_parse_derive 0 -? failed -error: Invalid value "0" for '': 0 is not in 1..=65535 - -For more information try --help - -``` - -A custom parser can be used to improve the error messages or provide additional validation: - -[Example:](04_02_validate.rs) -```console -$ 04_02_validate --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_validate[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_validate 22 -PORT = 22 - -$ 04_02_validate foobar -? failed -error: Invalid value "foobar" for '': `foobar` isn't a port number - -For more information try --help - -$ 04_02_validate 0 -? failed -error: Invalid value "0" for '': Port not in range 1-65535 - -For more information try --help - -``` - -### Argument Relations - -You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. - -`ArgGroup`s make it easier to declare relations instead of having to list each -individually, or when you want a rule to apply "any but not all" arguments. - -Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -present out of a given set. Imagine that you had multiple arguments, and you want one of them to -be required, but making all of them required isn't feasible because perhaps they conflict with -each other. - -[Example:](04_03_relations.rs) -```console -$ 04_03_relations --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_03_relations -? failed -error: The following required arguments were not provided: - <--set-ver |--major|--minor|--patch> - -USAGE: - 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -For more information try --help - -$ 04_03_relations --major -Version: 2.2.3 - -$ 04_03_relations --major --minor -? failed -error: The argument '--major' cannot be used with '--minor' - -USAGE: - 04_03_relations[EXE] <--set-ver |--major|--minor|--patch> - -For more information try --help - -$ 04_03_relations --major -c config.toml -? failed -error: The following required arguments were not provided: - > - -USAGE: - 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > - -For more information try --help - -$ 04_03_relations --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -### Custom Validation - -As a last resort, you can create custom errors with the basics of clap's formatting. - -[Example:](04_04_custom.rs) -```console -$ 04_04_custom --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_04_custom -? failed -error: Can only modify one version field - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -Version: 2.2.3 - -$ 04_04_custom --major --minor -? failed -error: Can only modify one version field - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -c config.toml -? failed -Version: 2.2.3 -error: INPUT_FILE or --spec-in is required when using --config - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -## Tips - -- For more complex demonstration of features, see our [examples](../README.md). -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) - -## Contributing - -New example code: -- Please update the corresponding section in the [derive tutorial](../tutorial_derive/README.md) -- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). - -See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/vendor/clap/examples/tutorial_derive/01_quick.rs b/vendor/clap/examples/tutorial_derive/01_quick.rs deleted file mode 100644 index 2c2031061..000000000 --- a/vendor/clap/examples/tutorial_derive/01_quick.rs +++ /dev/null @@ -1,69 +0,0 @@ -use std::path::PathBuf; - -use clap::{Parser, Subcommand}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// Optional name to operate on - #[clap(value_parser)] - name: Option, - - /// Sets a custom config file - #[clap(short, long, value_parser, value_name = "FILE")] - config: Option, - - /// Turn debugging information on - #[clap(short, long, action = clap::ArgAction::Count)] - debug: u8, - - #[clap(subcommand)] - command: Option, -} - -#[derive(Subcommand)] -enum Commands { - /// does testing things - Test { - /// lists test values - #[clap(short, long, action)] - list: bool, - }, -} - -fn main() { - let cli = Cli::parse(); - - // You can check the value provided by positional arguments, or option arguments - if let Some(name) = cli.name.as_deref() { - println!("Value for name: {}", name); - } - - if let Some(config_path) = cli.config.as_deref() { - println!("Value for config: {}", config_path.display()); - } - - // You can see how many times a particular flag or argument occurred - // Note, only flags can have multiple occurrences - match cli.debug { - 0 => println!("Debug mode is off"), - 1 => println!("Debug mode is kind of on"), - 2 => println!("Debug mode is on"), - _ => println!("Don't be crazy"), - } - - // You can check for the existence of subcommands, and if found use their - // matches just as you would the top level cmd - match &cli.command { - Some(Commands::Test { list }) => { - if *list { - println!("Printing testing lists..."); - } else { - println!("Not printing testing lists..."); - } - } - None => {} - } - - // Continued program logic goes here... -} diff --git a/vendor/clap/examples/tutorial_derive/02_app_settings.rs b/vendor/clap/examples/tutorial_derive/02_app_settings.rs deleted file mode 100644 index 6a06929bb..000000000 --- a/vendor/clap/examples/tutorial_derive/02_app_settings.rs +++ /dev/null @@ -1,19 +0,0 @@ -use clap::{AppSettings, Parser}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -#[clap(allow_negative_numbers = true)] -#[clap(global_setting(AppSettings::DeriveDisplayOrder))] -struct Cli { - #[clap(long, value_parser)] - two: String, - #[clap(long, value_parser)] - one: String, -} - -fn main() { - let cli = Cli::parse(); - - println!("two: {:?}", cli.two); - println!("one: {:?}", cli.one); -} diff --git a/vendor/clap/examples/tutorial_derive/02_apps.rs b/vendor/clap/examples/tutorial_derive/02_apps.rs deleted file mode 100644 index b97ce1eed..000000000 --- a/vendor/clap/examples/tutorial_derive/02_apps.rs +++ /dev/null @@ -1,20 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(name = "MyApp")] -#[clap(author = "Kevin K. ")] -#[clap(version = "1.0")] -#[clap(about = "Does awesome things", long_about = None)] -struct Cli { - #[clap(long, value_parser)] - two: String, - #[clap(long, value_parser)] - one: String, -} - -fn main() { - let cli = Cli::parse(); - - println!("two: {:?}", cli.two); - println!("one: {:?}", cli.one); -} diff --git a/vendor/clap/examples/tutorial_derive/02_crate.rs b/vendor/clap/examples/tutorial_derive/02_crate.rs deleted file mode 100644 index df16468d0..000000000 --- a/vendor/clap/examples/tutorial_derive/02_crate.rs +++ /dev/null @@ -1,17 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(long, value_parser)] - two: String, - #[clap(long, value_parser)] - one: String, -} - -fn main() { - let cli = Cli::parse(); - - println!("two: {:?}", cli.two); - println!("one: {:?}", cli.one); -} diff --git a/vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs b/vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs deleted file mode 100644 index de677d8c6..000000000 --- a/vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs +++ /dev/null @@ -1,14 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(short, long, action)] - verbose: bool, -} - -fn main() { - let cli = Cli::parse(); - - println!("verbose: {:?}", cli.verbose); -} diff --git a/vendor/clap/examples/tutorial_derive/03_01_flag_count.rs b/vendor/clap/examples/tutorial_derive/03_01_flag_count.rs deleted file mode 100644 index 680f7f5e5..000000000 --- a/vendor/clap/examples/tutorial_derive/03_01_flag_count.rs +++ /dev/null @@ -1,14 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(short, long, action = clap::ArgAction::Count)] - verbose: u8, -} - -fn main() { - let cli = Cli::parse(); - - println!("verbose: {:?}", cli.verbose); -} diff --git a/vendor/clap/examples/tutorial_derive/03_02_option.rs b/vendor/clap/examples/tutorial_derive/03_02_option.rs deleted file mode 100644 index 75b67afe7..000000000 --- a/vendor/clap/examples/tutorial_derive/03_02_option.rs +++ /dev/null @@ -1,14 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(short, long, value_parser)] - name: Option, -} - -fn main() { - let cli = Cli::parse(); - - println!("name: {:?}", cli.name.as_deref()); -} diff --git a/vendor/clap/examples/tutorial_derive/03_03_positional.rs b/vendor/clap/examples/tutorial_derive/03_03_positional.rs deleted file mode 100644 index 7478951f1..000000000 --- a/vendor/clap/examples/tutorial_derive/03_03_positional.rs +++ /dev/null @@ -1,14 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(value_parser)] - name: Option, -} - -fn main() { - let cli = Cli::parse(); - - println!("name: {:?}", cli.name.as_deref()); -} diff --git a/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs b/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs deleted file mode 100644 index 62a45a97e..000000000 --- a/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs +++ /dev/null @@ -1,30 +0,0 @@ -use clap::{Parser, Subcommand}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -#[clap(propagate_version = true)] -struct Cli { - #[clap(subcommand)] - command: Commands, -} - -#[derive(Subcommand)] -enum Commands { - /// Adds files to myapp - Add { - #[clap(value_parser)] - name: Option, - }, -} - -fn main() { - let cli = Cli::parse(); - - // You can check for the existence of subcommands, and if found use their - // matches just as you would the top level cmd - match &cli.command { - Commands::Add { name } => { - println!("'myapp add' was used, name is: {:?}", name) - } - } -} diff --git a/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs b/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs deleted file mode 100644 index b6124936c..000000000 --- a/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs +++ /dev/null @@ -1,33 +0,0 @@ -use clap::{Args, Parser, Subcommand}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -#[clap(propagate_version = true)] -struct Cli { - #[clap(subcommand)] - command: Commands, -} - -#[derive(Subcommand)] -enum Commands { - /// Adds files to myapp - Add(Add), -} - -#[derive(Args)] -struct Add { - #[clap(value_parser)] - name: Option, -} - -fn main() { - let cli = Cli::parse(); - - // You can check for the existence of subcommands, and if found use their - // matches just as you would the top level cmd - match &cli.command { - Commands::Add(name) => { - println!("'myapp add' was used, name is: {:?}", name.name) - } - } -} diff --git a/vendor/clap/examples/tutorial_derive/03_05_default_values.rs b/vendor/clap/examples/tutorial_derive/03_05_default_values.rs deleted file mode 100644 index 10a1ec808..000000000 --- a/vendor/clap/examples/tutorial_derive/03_05_default_values.rs +++ /dev/null @@ -1,14 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - #[clap(default_value_t = String::from("alice"), value_parser)] - name: String, -} - -fn main() { - let cli = Cli::parse(); - - println!("name: {:?}", cli.name); -} diff --git a/vendor/clap/examples/tutorial_derive/04_01_enum.rs b/vendor/clap/examples/tutorial_derive/04_01_enum.rs deleted file mode 100644 index 84b4cace4..000000000 --- a/vendor/clap/examples/tutorial_derive/04_01_enum.rs +++ /dev/null @@ -1,28 +0,0 @@ -use clap::{ArgEnum, Parser}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// What mode to run the program in - #[clap(arg_enum, value_parser)] - mode: Mode, -} - -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum)] -enum Mode { - Fast, - Slow, -} - -fn main() { - let cli = Cli::parse(); - - match cli.mode { - Mode::Fast => { - println!("Hare"); - } - Mode::Slow => { - println!("Tortoise"); - } - } -} diff --git a/vendor/clap/examples/tutorial_derive/04_02_parse.rs b/vendor/clap/examples/tutorial_derive/04_02_parse.rs deleted file mode 100644 index 6336a9cf1..000000000 --- a/vendor/clap/examples/tutorial_derive/04_02_parse.rs +++ /dev/null @@ -1,15 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// Network port to use - #[clap(value_parser = clap::value_parser!(u16).range(1..))] - port: u16, -} - -fn main() { - let cli = Cli::parse(); - - println!("PORT = {}", cli.port); -} diff --git a/vendor/clap/examples/tutorial_derive/04_02_validate.rs b/vendor/clap/examples/tutorial_derive/04_02_validate.rs deleted file mode 100644 index 7dac79c9f..000000000 --- a/vendor/clap/examples/tutorial_derive/04_02_validate.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::ops::RangeInclusive; - -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// Network port to use - #[clap(value_parser = port_in_range)] - port: u16, -} - -fn main() { - let cli = Cli::parse(); - - println!("PORT = {}", cli.port); -} - -const PORT_RANGE: RangeInclusive = 1..=65535; - -fn port_in_range(s: &str) -> Result { - let port: usize = s - .parse() - .map_err(|_| format!("`{}` isn't a port number", s))?; - if PORT_RANGE.contains(&port) { - Ok(port as u16) - } else { - Err(format!( - "Port not in range {}-{}", - PORT_RANGE.start(), - PORT_RANGE.end() - )) - } -} diff --git a/vendor/clap/examples/tutorial_derive/04_03_relations.rs b/vendor/clap/examples/tutorial_derive/04_03_relations.rs deleted file mode 100644 index f8523902d..000000000 --- a/vendor/clap/examples/tutorial_derive/04_03_relations.rs +++ /dev/null @@ -1,72 +0,0 @@ -use clap::{ArgGroup, Parser}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -#[clap(group( - ArgGroup::new("vers") - .required(true) - .args(&["set-ver", "major", "minor", "patch"]), - ))] -struct Cli { - /// set version manually - #[clap(long, value_name = "VER", value_parser)] - set_ver: Option, - - /// auto inc major - #[clap(long, action)] - major: bool, - - /// auto inc minor - #[clap(long, action)] - minor: bool, - - /// auto inc patch - #[clap(long, action)] - patch: bool, - - /// some regular input - #[clap(group = "input", value_parser)] - input_file: Option, - - /// some special input argument - #[clap(long, group = "input", value_parser)] - spec_in: Option, - - #[clap(short, requires = "input", value_parser)] - config: Option, -} - -fn main() { - let cli = Cli::parse(); - - // Let's assume the old version 1.2.3 - let mut major = 1; - let mut minor = 2; - let mut patch = 3; - - // See if --set-ver was used to set the version manually - let version = if let Some(ver) = cli.set_ver.as_deref() { - ver.to_string() - } else { - // Increment the one requested (in a real program, we'd reset the lower numbers) - let (maj, min, pat) = (cli.major, cli.minor, cli.patch); - match (maj, min, pat) { - (true, _, _) => major += 1, - (_, true, _) => minor += 1, - (_, _, true) => patch += 1, - _ => unreachable!(), - }; - format!("{}.{}.{}", major, minor, patch) - }; - - println!("Version: {}", version); - - // Check for usage of -c - if let Some(config) = cli.config.as_deref() { - let input = cli - .input_file - .as_deref() - .unwrap_or_else(|| cli.spec_in.as_deref().unwrap()); - println!("Doing work using input {} and config {}", input, config); - } -} diff --git a/vendor/clap/examples/tutorial_derive/04_04_custom.rs b/vendor/clap/examples/tutorial_derive/04_04_custom.rs deleted file mode 100644 index 454d489c1..000000000 --- a/vendor/clap/examples/tutorial_derive/04_04_custom.rs +++ /dev/null @@ -1,93 +0,0 @@ -use clap::{CommandFactory, ErrorKind, Parser}; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// set version manually - #[clap(long, value_name = "VER", value_parser)] - set_ver: Option, - - /// auto inc major - #[clap(long, action)] - major: bool, - - /// auto inc minor - #[clap(long, action)] - minor: bool, - - /// auto inc patch - #[clap(long, action)] - patch: bool, - - /// some regular input - #[clap(value_parser)] - input_file: Option, - - /// some special input argument - #[clap(long, value_parser)] - spec_in: Option, - - #[clap(short, value_parser)] - config: Option, -} - -fn main() { - let cli = Cli::parse(); - - // Let's assume the old version 1.2.3 - let mut major = 1; - let mut minor = 2; - let mut patch = 3; - - // See if --set-ver was used to set the version manually - let version = if let Some(ver) = cli.set_ver.as_deref() { - if cli.major || cli.minor || cli.patch { - let mut cmd = Cli::command(); - cmd.error( - ErrorKind::ArgumentConflict, - "Can't do relative and absolute version change", - ) - .exit(); - } - ver.to_string() - } else { - // Increment the one requested (in a real program, we'd reset the lower numbers) - let (maj, min, pat) = (cli.major, cli.minor, cli.patch); - match (maj, min, pat) { - (true, false, false) => major += 1, - (false, true, false) => minor += 1, - (false, false, true) => patch += 1, - _ => { - let mut cmd = Cli::command(); - cmd.error( - ErrorKind::ArgumentConflict, - "Can only modify one version field", - ) - .exit(); - } - }; - format!("{}.{}.{}", major, minor, patch) - }; - - println!("Version: {}", version); - - // Check for usage of -c - if let Some(config) = cli.config.as_deref() { - // todo: remove `#[allow(clippy::or_fun_call)]` lint when MSRV is bumped. - #[allow(clippy::or_fun_call)] - let input = cli - .input_file - .as_deref() - // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const' - .or(cli.spec_in.as_deref()) - .unwrap_or_else(|| { - let mut cmd = Cli::command(); - cmd.error( - ErrorKind::MissingRequiredArgument, - "INPUT_FILE or --spec-in is required when using --config", - ) - .exit() - }); - println!("Doing work using input {} and config {}", input, config); - } -} diff --git a/vendor/clap/examples/tutorial_derive/05_01_assert.rs b/vendor/clap/examples/tutorial_derive/05_01_assert.rs deleted file mode 100644 index f5fa3f6c5..000000000 --- a/vendor/clap/examples/tutorial_derive/05_01_assert.rs +++ /dev/null @@ -1,21 +0,0 @@ -use clap::Parser; - -#[derive(Parser)] -#[clap(author, version, about, long_about = None)] -struct Cli { - /// Network port to use - #[clap(value_parser)] - port: u16, -} - -fn main() { - let cli = Cli::parse(); - - println!("PORT = {}", cli.port); -} - -#[test] -fn verify_app() { - use clap::CommandFactory; - Cli::command().debug_assert() -} diff --git a/vendor/clap/examples/tutorial_derive/README.md b/vendor/clap/examples/tutorial_derive/README.md deleted file mode 100644 index 6127b6cd3..000000000 --- a/vendor/clap/examples/tutorial_derive/README.md +++ /dev/null @@ -1,639 +0,0 @@ -# Tutorial - -*Jump to [builder tutorial](../tutorial_builder/README.md)* - -1. [Quick Start](#quick-start) -2. [Configuring the Parser](#configuring-the-parser) -3. [Adding Arguments](#adding-arguments) - 1. [Positionals](#positionals) - 2. [Options](#options) - 3. [Flags](#flags) - 4. [Subcommands](#subcommands) - 5. [Defaults](#defaults) -4. Validation - 1. [Enumerated values](#enumerated-values) - 2. [Validated values](#validated-values) - 3. [Argument Relations](#argument-relations) - 4. [Custom Validation](#custom-validation) -5. [Tips](#tips) -6. [Contributing](#contributing) - -## Quick Start - -You can create an application declaratively with a `struct` and some -attributes. **This requires enabling the `derive` feature flag.** - -[Example:](01_quick.rs) -```console -$ 01_quick_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 01_quick_derive[EXE] [OPTIONS] [NAME] [SUBCOMMAND] - -ARGS: - Optional name to operate on - -OPTIONS: - -c, --config Sets a custom config file - -d, --debug Turn debugging information on - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - help Print this message or the help of the given subcommand(s) - test does testing things - -``` - -By default, the program does nothing: -```console -$ 01_quick_derive -Debug mode is off - -``` - -But you can mix and match the various features -```console -$ 01_quick_derive -dd test -Debug mode is on -Not printing testing lists... - -``` - -In addition to this tutorial, see the [derive reference](../derive_ref/README.md). - -## Configuring the Parser - -You use derive `Parser` the start building a parser. - -[Example:](02_apps.rs) -```console -$ 02_apps_derive --help -MyApp 1.0 -Kevin K. -Does awesome things - -USAGE: - 02_apps_derive[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_apps_derive --version -MyApp 1.0 - -``` - -You can use `#[clap(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file. - -[Example:](02_crate.rs) -```console -$ 02_crate_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_crate_derive[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_crate_derive --version -clap [..] - -``` - -You can use attributes to change the application level behavior of clap. Any `Command` builder function can be used as an attribute. - -[Example:](02_app_settings.rs) -```console -$ 02_app_settings_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_app_settings_derive[EXE] --two --one - -OPTIONS: - --two - --one - -h, --help Print help information - -V, --version Print version information - -$ 02_app_settings_derive --one -1 --one -3 --two 10 -two: "10" -one: "-3" - -``` - -## Adding Arguments - -### Positionals - -You can have users specify values by their position on the command-line: - -[Example:](03_03_positional.rs) -```console -$ 03_03_positional_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_03_positional_derive[EXE] [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_03_positional_derive -name: None - -$ 03_03_positional_derive bob -name: Some("bob") - -``` - -### Options - -You can name your arguments with a flag: -- Order doesn't matter -- They can be optional -- Intent is clearer - -The `#[clap(short = 'c')]` and `#[clap(long = "name")]` attributes that define -the flags are `Arg` methods that are derived from the field name when no value -is specified (`#[clap(short)]` and `#[clap(long)]`). - -[Example:](03_02_option.rs) -```console -$ 03_02_option_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_02_option_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -n, --name - -V, --version Print version information - -$ 03_02_option_derive -name: None - -$ 03_02_option_derive --name bob -name: Some("bob") - -$ 03_02_option_derive --name=bob -name: Some("bob") - -$ 03_02_option_derive -n bob -name: Some("bob") - -$ 03_02_option_derive -n=bob -name: Some("bob") - -$ 03_02_option_derive -nbob -name: Some("bob") - -``` - -### Flags - -Flags can also be switches that can be on/off. This is enabled via the -`#[clap(parse(from_flag)]` attribute though this is implied when the field is a -`bool`. - -[Example:](03_01_flag_bool.rs) -```console -$ 03_01_flag_bool_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_bool_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_bool_derive -verbose: false - -$ 03_01_flag_bool_derive --verbose -verbose: true - -$ 03_01_flag_bool_derive --verbose --verbose -verbose: true - -``` - -Or counted with `#[clap(action = clap::ArgAction::Count)]`: - -[Example:](03_01_flag_count.rs) -```console -$ 03_01_flag_count_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_count_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_count_derive -verbose: 0 - -$ 03_01_flag_count_derive --verbose -verbose: 1 - -$ 03_01_flag_count_derive --verbose --verbose -verbose: 2 - -``` - -### Subcommands - -Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[clap(subcommand)]` attribute. Each -instance of a Subcommand can have its own version, author(s), Args, and even its own -subcommands. - -[Example:](03_04_subcommands.rs) -```console -$ 03_04_subcommands_derive help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands_derive[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -$ 03_04_subcommands_derive help add -03_04_subcommands_derive[EXE]-add [..] -Adds files to myapp - -USAGE: - 03_04_subcommands_derive[EXE] add [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_04_subcommands_derive add bob -'myapp add' was used, name is: Some("bob") - -``` - -Above, we used a struct-variant to define the `add` subcommand. Alternatively, -you can -[use a struct for your subcommand's arguments](03_04_subcommands_alt.rs). - -Because we used `command: Commands` instead of `command: Option`: -```console -$ 03_04_subcommands_derive -? failed -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands_derive[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -``` - -Because we added `#[clap(propagate_version = true)]`: -```console -$ 03_04_subcommands_derive --version -clap [..] - -$ 03_04_subcommands_derive add --version -03_04_subcommands_derive[EXE]-add [..] - -``` - -### Defaults - -We've previously showed that arguments can be `required` or optional. When -optional, you work with an `Option` and can `unwrap_or`. Alternatively, you can -set `#[clap(default_value_t)]`. - -[Example:](03_05_default_values.rs) -```console -$ 03_05_default_values_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_05_default_values_derive[EXE] [NAME] - -ARGS: - [default: alice] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_05_default_values_derive -name: "alice" - -$ 03_05_default_values_derive bob -name: "bob" - -``` - -## Validation - -### Enumerated values - -If you have arguments of specific values you want to test for, you can derive -`ValueEnum`. - -This allows you specify the valid values for that argument. If the user does not use one of -those specific values, they will receive a graceful exit with error message informing them -of the mistake, and what the possible valid values are - -[Example:](04_01_enum.rs) -```console -$ 04_01_enum_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_enum_derive[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_enum_derive fast -Hare - -$ 04_01_enum_derive slow -Tortoise - -$ 04_01_enum_derive medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -### Validated values - -More generally, you can validate and parse into any data type. - -[Example:](04_02_parse.rs) -```console -$ 04_02_parse_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_parse_derive[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_parse_derive 22 -PORT = 22 - -$ 04_02_parse_derive foobar -? failed -error: Invalid value "foobar" for '': invalid digit found in string - -For more information try --help - -$ 04_02_parse_derive 0 -? failed -error: Invalid value "0" for '': 0 is not in 1..=65535 - -For more information try --help - -``` - -A custom parser can be used to improve the error messages or provide additional validation: - -[Example:](04_02_validate.rs) -```console -$ 04_02_validate_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_validate_derive[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_validate_derive 22 -PORT = 22 - -$ 04_02_validate_derive foobar -? failed -error: Invalid value "foobar" for '': `foobar` isn't a port number - -For more information try --help - -$ 04_02_validate_derive 0 -? failed -error: Invalid value "0" for '': Port not in range 1-65535 - -For more information try --help - -``` - -### Argument Relations - -You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. - -`ArgGroup`s make it easier to declare relations instead of having to list each -individually, or when you want a rule to apply "any but not all" arguments. - -Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -present out of a given set. Imagine that you had multiple arguments, and you want one of them to -be required, but making all of them required isn't feasible because perhaps they conflict with -each other. - -[Example:](04_03_relations.rs) -```console -$ 04_03_relations_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_03_relations_derive -? failed -error: The following required arguments were not provided: - <--set-ver |--major|--minor|--patch> - -USAGE: - 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -For more information try --help - -$ 04_03_relations_derive --major -Version: 2.2.3 - -$ 04_03_relations_derive --major --minor -? failed -error: The argument '--major' cannot be used with '--minor' - -USAGE: - 04_03_relations_derive[EXE] <--set-ver |--major|--minor|--patch> - -For more information try --help - -$ 04_03_relations_derive --major -c config.toml -? failed -error: The following required arguments were not provided: - > - -USAGE: - 04_03_relations_derive[EXE] -c <--set-ver |--major|--minor|--patch> > - -For more information try --help - -$ 04_03_relations_derive --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -### Custom Validation - -As a last resort, you can create custom errors with the basics of clap's formatting. - -[Example:](04_04_custom.rs) -```console -$ 04_04_custom_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_04_custom_derive -? failed -error: Can only modify one version field - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -Version: 2.2.3 - -$ 04_04_custom_derive --major --minor -? failed -error: Can only modify one version field - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -c config.toml -? failed -Version: 2.2.3 -error: INPUT_FILE or --spec-in is required when using --config - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -## Tips - -- For more complex demonstration of features, see our [examples](../README.md). -- See the [derive reference](../derive_ref/README.md) to understand how to use - anything in the [builder API](https://docs.rs/clap/) in the derive API. -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) - -## Contributing - -New example code: -- Please update the corresponding section in the [builder tutorial](../tutorial_builder/README.md) -- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). - -See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/vendor/clap/examples/typed-derive.md b/vendor/clap/examples/typed-derive.md deleted file mode 100644 index 7c61f70d9..000000000 --- a/vendor/clap/examples/typed-derive.md +++ /dev/null @@ -1,86 +0,0 @@ -*Jump to [source](typed-derive.rs)* - -**This requires enabling the `derive` feature flag.** - -Help: -```console -$ typed-derive --help -clap - -USAGE: - typed-derive[EXE] [OPTIONS] - -OPTIONS: - --bind Handle IP addresses - -D Hand-written parser for tuples - -h, --help Print help information - -I