diff --git a/Cargo.lock b/Cargo.lock index b91e7d75be0c..994f98dd2216 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -726,15 +726,17 @@ dependencies = [ [[package]] name = "clap" -version = "2.34.0" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +checksum = "7a30c3bf9ff12dfe5dae53f0a96e0febcd18420d1c0e7fad77796d9d5c4b5375" dependencies = [ "bitflags", + "indexmap", + "lazy_static", + "os_str_bytes", "strsim", - "term_size", + "terminal_size", "textwrap", - "unicode-width", ] [[package]] @@ -3669,6 +3671,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" +dependencies = [ + "memchr", +] + [[package]] name = "osclientcerts-static" version = "0.1.4" @@ -4780,9 +4791,9 @@ dependencies = [ [[package]] name = "strsim" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "style" @@ -4978,16 +4989,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "term_size" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "termcolor" version = "1.1.2" @@ -4998,13 +4999,22 @@ dependencies = [ ] [[package]] -name = "textwrap" -version = "0.11.0" +name = "terminal_size" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" dependencies = [ - "term_size", - "unicode-width", + "libc", + "winapi", +] + +[[package]] +name = "textwrap" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80" +dependencies = [ + "terminal_size", ] [[package]] diff --git a/testing/geckodriver/Cargo.toml b/testing/geckodriver/Cargo.toml index 0eaadcd0abe8..5ece3c619c60 100644 --- a/testing/geckodriver/Cargo.toml +++ b/testing/geckodriver/Cargo.toml @@ -12,7 +12,7 @@ edition = "2018" [dependencies] base64 = "0.12" chrono = "0.4.6" -clap = { version = "^2.19", default-features = false, features = ["suggestions", "wrap_help"] } +clap = { version = "3", default-features = false, features = ["cargo", "std", "suggestions", "wrap_help"] } hyper = "0.13" lazy_static = "1.0" log = { version = "0.4", features = ["std"] } diff --git a/testing/geckodriver/src/main.rs b/testing/geckodriver/src/main.rs index 30bd6d15b108..af6342a7c74a 100644 --- a/testing/geckodriver/src/main.rs +++ b/testing/geckodriver/src/main.rs @@ -33,7 +33,7 @@ use std::path::PathBuf; use std::result; use std::str::FromStr; -use clap::{App, Arg}; +use clap::{App, AppSettings, Arg}; macro_rules! try_opt { ($expr:expr, $err_type:expr, $err_msg:expr) => {{ @@ -233,7 +233,7 @@ fn get_allowed_origins(allow_origins: Option) -> Result, } fn parse_args(app: &mut App) -> ProgramResult { - let args = app.get_matches_from_safe_borrow(env::args())?; + let args = app.try_get_matches_from_mut(env::args())?; if args.is_present("help") { return Ok(Operation::Help); @@ -261,7 +261,7 @@ fn parse_args(app: &mut App) -> ProgramResult { }; let android_storage = - value_t!(args, "android_storage", AndroidStorageInput).unwrap_or(AndroidStorageInput::Auto); + args.value_of_t::("android_storage").unwrap_or(AndroidStorageInput::Auto); let binary = args.value_of("binary").map(PathBuf::from); @@ -378,11 +378,13 @@ fn main() { }); } -fn make_app<'a, 'b>() -> App<'a, 'b> { +fn make_app<'a>() -> App<'a> { App::new(format!("geckodriver {}", build::build_info())) + .setting(AppSettings::NoAutoHelp) + .setting(AppSettings::NoAutoVersion) .about("WebDriver implementation for Firefox") .arg( - Arg::with_name("webdriver_host") + Arg::new("webdriver_host") .long("host") .takes_value(true) .value_name("HOST") @@ -390,8 +392,8 @@ fn make_app<'a, 'b>() -> App<'a, 'b> { .help("Host IP to use for WebDriver server"), ) .arg( - Arg::with_name("webdriver_port") - .short("p") + Arg::new("webdriver_port") + .short('p') .long("port") .takes_value(true) .value_name("PORT") @@ -399,15 +401,15 @@ fn make_app<'a, 'b>() -> App<'a, 'b> { .help("Port to use for WebDriver server"), ) .arg( - Arg::with_name("binary") - .short("b") + Arg::new("binary") + .short('b') .long("binary") .takes_value(true) .value_name("BINARY") .help("Path to the Firefox binary"), ) .arg( - Arg::with_name("marionette_host") + Arg::new("marionette_host") .long("marionette-host") .takes_value(true) .value_name("HOST") @@ -415,14 +417,14 @@ fn make_app<'a, 'b>() -> App<'a, 'b> { .help("Host to use to connect to Gecko"), ) .arg( - Arg::with_name("marionette_port") + Arg::new("marionette_port") .long("marionette-port") .takes_value(true) .value_name("PORT") .help("Port to use to connect to Gecko [default: system-allocated port]"), ) .arg( - Arg::with_name("websocket_port") + Arg::new("websocket_port") .long("websocket-port") .takes_value(true) .value_name("PORT") @@ -430,25 +432,25 @@ fn make_app<'a, 'b>() -> App<'a, 'b> { .help("Port to use to connect to WebDriver BiDi [default: 9222]"), ) .arg( - Arg::with_name("connect_existing") + Arg::new("connect_existing") .long("connect-existing") .requires("marionette_port") .help("Connect to an existing Firefox instance"), ) .arg( - Arg::with_name("jsdebugger") + Arg::new("jsdebugger") .long("jsdebugger") .help("Attach browser toolbox debugger for Firefox"), ) .arg( - Arg::with_name("verbosity") - .multiple(true) + Arg::new("verbosity") + .multiple_occurrences(true) .conflicts_with("log_level") - .short("v") + .short('v') .help("Log level verbosity (-v for debug and -vv for trace level)"), ) .arg( - Arg::with_name("log_level") + Arg::new("log_level") .long("log") .takes_value(true) .value_name("LEVEL") @@ -456,37 +458,37 @@ fn make_app<'a, 'b>() -> App<'a, 'b> { .help("Set Gecko log level"), ) .arg( - Arg::with_name("help") - .short("h") + Arg::new("help") + .short('h') .long("help") .help("Prints this message"), ) .arg( - Arg::with_name("version") - .short("V") + Arg::new("version") + .short('V') .long("version") .help("Prints version and copying information"), ) .arg( - Arg::with_name("android_storage") + Arg::new("android_storage") .long("android-storage") .possible_values(&["auto", "app", "internal", "sdcard"]) .value_name("ANDROID_STORAGE") .help("Selects storage location to be used for test data (deprecated)."), ) .arg( - Arg::with_name("allow_hosts") + Arg::new("allow_hosts") .long("allow-hosts") .takes_value(true) - .multiple(true) + .multiple_values(true) .value_name("ALLOW_HOSTS") .help("List of hostnames to allow. By default the value of --host is allowed, and in addition if that's a well known local address, other variations on well known local addresses are allowed. If --allow-hosts is provided only exactly those hosts are allowed."), ) .arg( - Arg::with_name("allow_origins") + Arg::new("allow_origins") .long("allow-origins") .takes_value(true) - .multiple(true) + .multiple_values(true) .value_name("ALLOW_ORIGINS") .help("List of request origins to allow. These must be formatted as scheme://host:port. By default any request with an origin header is rejected. If --allow-origins is provided then only exactly those origins are allowed."), ) diff --git a/third_party/rust/clap/.cargo-checksum.json b/third_party/rust/clap/.cargo-checksum.json index f70b25fc3aa0..f835936e9775 100644 --- a/third_party/rust/clap/.cargo-checksum.json +++ b/third_party/rust/clap/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"623d43f94b419a5e79f7bc103d4de47f60daf7803d49e63058ba9e24f8f8c6cc","CONTRIBUTORS.md":"9b0d3eee116dda23705b732c19b777ebb2b998a6e4554027ae3f61715376b4bc","Cargo.toml":"e7d0b7019b86f3a6901416714ac94702f666c8de0bf197d717abb8a2f86e7e6a","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"6a836ddd7544962b33ae76b03e0f550ace4e4c967aee23e24ce14fc31e58e885","SPONSORS.md":"640b56e535db654d7bf14b1fe63bc837dcfde37a85f14eb4f404663fe1b72af9","clap-test.rs":"b5ca72dedfe1e71c250c42a01a52a3f5f9ea2bb14d9fe09093e73b71880f79fd","justfile":"9ee43d53fda234044fee4edd1ecdac9f19864c7f00a4ea5cb2b6a8a0287c93e3","src/app/help.rs":"037094b39990115fdac105f550c2f6eb1cbbfc8ff8f65b6ca34c65634902c3ab","src/app/meta.rs":"d15a4118e9de562cacf9d2063f1f491e3c3ce4092b4e8ea5d4d92e2631ca247b","src/app/mod.rs":"0aee709776d1be519a5587258b433ba0b54d5ebda14bb0544ce32c0505d5dcec","src/app/parser.rs":"83917c7e8f39f1e5d1807095f0856be3c3450aa88a6abb8e4d7c1d1fe9dbb2c4","src/app/settings.rs":"b29e3f90c282a27865b27674bb5b0a4def2966646f0e70b4f78e587c9649e379","src/app/usage.rs":"65f6b5d6f068a8ded0e78faf59575202bc8729a079e9806d0afeba87fa6ba9fc","src/app/validator.rs":"3124617cbaf959466241f4ba1a9837c1184a7a06325c5cbe3d613a7786febd4e","src/args/any_arg.rs":"5a34d363ce5d74e1829c4feb2a8044e0d3c31d5af2094933cf61d6579e548ecf","src/args/arg.rs":"e9ad38d43bef8d36e96ae6edb2dc6ea2258c6a7287f6479aad5a21b8ed197fd6","src/args/arg_builder/base.rs":"989952f8b827bd60db85bebb09b23de4d3e1296cc1f195e9da447b154f10cd09","src/args/arg_builder/flag.rs":"3c90fc16079b3f921c9e9b3a9607467eb5afddfdc8da53e9528987a43d883e36","src/args/arg_builder/mod.rs":"31844ad665171a2d49d551debd3d1a20e8a77dd74d02f9ff6fc22f63b019db02","src/args/arg_builder/option.rs":"d882e07dc1d6a77aae06fc5dad5502b7a4c1fc6e8124e6ab08b6ec037cb08b85","src/args/arg_builder/positional.rs":"fd6720931b9622a6d6576494dfbe67ae40416b6083d0302c1a0d9e9a86bb2d3d","src/args/arg_builder/switched.rs":"bc4c5acb77741562c4258b643a3dddd6b22e5b1874b71919d333c7d1e03e0ccb","src/args/arg_builder/valued.rs":"5f19d8e84e3d0bd3aee4b6fbb124206a6ab234492fe2ffc7279043e983522765","src/args/arg_matcher.rs":"a3cbe567cab3817c3ec7e37eb36641c9b9af1056b0002748b99a3ce255d65fd5","src/args/arg_matches.rs":"2058c1b0276db9d345b66d0531159fa05677ef865823ac8ec9831473359b64a8","src/args/group.rs":"6f08b7ebcbe2968a6d8462ab7c32dfc36c6b862a00853e9dc13af827196bc923","src/args/macros.rs":"4686d5929c760d2dace4110e96179d6aa7e43d7f911938199b07cb5728dc319b","src/args/matched_arg.rs":"28754509ea5493b66b4a5648d977f7cd9b379507b6eff89d76931be91509e6fe","src/args/mod.rs":"66cc0bb745fafd6387db72caa5ac414514990a07421270bfb5d8aff77ff01600","src/args/settings.rs":"f52313e363c1a928d65a52fbb7abb04b2ae00bd1e319fe267cf809363618fce8","src/args/subcommand.rs":"518418bb276c9758e3f82fc73341d69a242836ce163cd2ef6198075acf6594ba","src/completions/bash.rs":"d086d1e477ed14702650e2e7e0d2d33ba0a977f0a5c9f4e5d3cdb23b6ae5529f","src/completions/elvish.rs":"91e6f6685c258bfa4cdd4d428fa84ec9b59b2133e3d75f0e88072a37454430dc","src/completions/fish.rs":"3a828f824bde8dbe6bfa2d9ea52259b8b534bc547e9d96aec46f56e430b118e4","src/completions/macros.rs":"fd449b9d5fc6c591feb419d209f72cddfff0dd0345a8ec9787c361be6e5275f8","src/completions/mod.rs":"96b1115d6973b68dbbb1b50929f281e4ba9943995bc69dbb0ef08311d623ae33","src/completions/powershell.rs":"738a642a074c74ea28af66de3973b132de97587192c996bed436d54f6dfb6179","src/completions/shell.rs":"f6e132d8ea06ee30435c977f0040a6eb804bfe7a802181041dee8a4f69f64bd1","src/completions/zsh.rs":"0a06b25521714c70bfb943e8a11be62b8010ddb8676a426c2b30b00daccef9fa","src/errors.rs":"7c755e43fa743a9f5071ce30fee224e84684ca7b948ce128844552fbd36cde75","src/fmt.rs":"02c640020993b439133ba6a336f5f6d79d80ca9ede8b81b115c429b0aa2b6944","src/lib.rs":"b55c29b8b6d36b3ff1e4230bbce533d8170139a72a28cf5e0fc26789bbc3383e","src/macros.rs":"86977f1557b943678c1b6feeb4b63b17692e35601075a6be841a40fa0da7acd4","src/map.rs":"0b53139bf9eb768843a478b905929153ae6837082d846d97c81dd0a98d2c5d55","src/osstringext.rs":"92be9bb46ce1673a71bd1e809585621a00e9b38d9eb8caf70f0f29c4a47e0c74","src/strext.rs":"9847933a25ccf757dbcbb1c5a4921a5f8cdaa9dfcd451961bc37d1023d8dd1e1","src/suggestions.rs":"98f6ad3aa5df6cc6c8a1d31a5d1bea9a33cc8fed2b0f5f38255f3878b3cfce37","src/usage_parser.rs":"90b41f753d26cd6dfbf97613a8325c9034c1d98e55cee339c792f0b70baa6595"},"package":"a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"} \ No newline at end of file +{"files":{"Cargo.lock":"67d366e477c95557534095f1d90f3f3da040c2beefd464b5ca7807c55737de79","Cargo.toml":"9eb2eff2e26845f75b0f4f8aee222031d261a43d9efded6fcbe0b9eab470f233","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"3318dc5f9c3c236fa609561f48d87631f1ba32a52467a71883e8caa62529dfbd","benches/01_default.rs":"f0be47b9a370aa729fbe36cb7845153ffbc64d3699bb50b74424e89a4ae48d4a","benches/02_simple.rs":"1ed8d0eb3ae627db67141197f0d4fe22d2bdaa449782f095d511c5178922e077","benches/03_complex.rs":"8866bee6de558b1fdf226814f077903e7c1f4709c314c5dc224f8f02285eb3d7","benches/04_new_help.rs":"a1ac5a6cde8eb23006b878ad4b20cab3359656666d23dac51263e73330fe72ac","benches/05_ripgrep.rs":"3680076a8b7e471fd36ac2bfdc6cc3070aeea227baf41038d73bfadca0f8233a","benches/06_rustup.rs":"f120229525421e44e4f92e8ed913af5287890f89bb8ac47d4a9250c9f3195cc6","examples/README.md":"1f79959991f9e39abb6eb39e0848222c703d2675d071b0c61769f7e4da40f502","examples/cargo-example-derive.md":"53a35e48cd04dfa10d70f99eb6d97d0d74110958f7f9e4ffc460fca87a256a73","examples/cargo-example-derive.rs":"950a1b91d795c626005639f84c3cd8ca133dc470b0f153364cdf5f7e75eaa697","examples/cargo-example.md":"1f270b0a0ac9122feb9cdac0887c1c1bcf1b654fed27147871c9cfe71851a4d9","examples/cargo-example.rs":"259712cb859a71a9d60a788bc1eb94100099d5d449a3bed34906c3c9decd9580","examples/demo.md":"3e986afca0863142fdd4cc092b5969fba32a70fac8adf84a55bd652f4b30eedb","examples/demo.rs":"2bf20d203a1f35fbdcae25690e4e9f55938a485ab92f909822decc0d2f3a6c10","examples/derive_ref/README.md":"a92db7ace75503220a8f2943cca2dcd86109b498a206f0251cf8724a4b7aca69","examples/derive_ref/custom-bool.md":"4aa41737326d7591a223d3b98b6c19dada4b62d12ac9d7aee44edadf71286fb0","examples/derive_ref/custom-bool.rs":"82b52b9fd902007a5b075445efac5bbc10f59e1a32433abe70850769b99a00cf","examples/escaped-positional-derive.md":"b2190ada5ad2634c3ceb7f9d98293512628762545f9519579cbee9867c6a406a","examples/escaped-positional-derive.rs":"0784fc1a0407053065bd231ba20d7c7d7c0225ef5ee48892b60632ce87dceb48","examples/escaped-positional.md":"b6a5c103f5cea1464b5ac8e63e1964f032a4dbb4a908e45b9b391f4857fe2684","examples/escaped-positional.rs":"472d84586bff5eb48fb10c0c8eca214935c0f3c7499df3df0a232c75e94278df","examples/git-derive.md":"08acb33eb9309365d4f2d8ae703b2273c697e41dffe8bf8c76701724e420ecd9","examples/git-derive.rs":"f05043fd233de1f81209fd36f3883767f18c4d633d5664cea874756bcbef8751","examples/git.md":"53651572035f35076fd1fb26556eb90dc0074959cd70dc568384165f213da11d","examples/git.rs":"656d05727abac3e7a0906565eab91751d266b743f889e7b4fdab687283f55f96","examples/keyvalue-derive.md":"d0d4751a234108c70ea839182d79c261a25b05d3b818584d96a375330de0165e","examples/keyvalue-derive.rs":"2455cc4a3d38bccbbe44e865b6d8fd0bc32be8bf3a74ff6c607489ceeebf6473","examples/multicall-busybox.md":"f755cf1a92930b42e6a920ba16a68cd08e1d16810d649f22b74d52ecee6a998b","examples/multicall-busybox.rs":"4762b1dfd518fd6959b3aee5721837f62d75f7e2dc139019c200cbced56815b8","examples/multicall-hostname.md":"6fbc7bbd9dd94e9b8bfdd9cae85909fbe8091c3580f94a9ac2189bbe66efb3cc","examples/multicall-hostname.rs":"17428c0c95af69ec561e4a3472c3e6862fd42bc9ee5fad896dae81b501a34ce9","examples/pacman.md":"870633ad60db3c736d95378ad04964393f76c56fd0f7dc90a8f444ce51ad4b3a","examples/pacman.rs":"28d6b264042090d1063a28587f2ac2b8a32b2ff6a048a72ac7f03c0fa57d0f8f","examples/tutorial_builder/01_quick.rs":"77cee52cf769850c331dcb7b09ab4ca5a79886ed2a5876f0da961761532d9c1c","examples/tutorial_builder/02_app_settings.rs":"60ba38141c703a2a5012fcd7195a9b8726496b50aaacbc1180a79a5b3a3ed5ee","examples/tutorial_builder/02_apps.rs":"e4323a1210b30996c937282a0fc28490a6e2ed8f5d31300a6d68b36f567d456c","examples/tutorial_builder/02_crate.rs":"48ac80a522338bf311608989e3402847b2bd0e2777c3b66775455133b34148b6","examples/tutorial_builder/03_01_flag_bool.rs":"9e96dd8fde99265b7e147f044cf55f1eb7a3c8228e29be3368c3d44210d9cec1","examples/tutorial_builder/03_01_flag_count.rs":"fe2a2300cace0d7bb55f47124f622c642546100a18676dc8aa88c5fb434b1e9c","examples/tutorial_builder/03_02_option.rs":"d146fd8af68818db087de474e2863171c19d32847f3147c75a054ed93c548b3d","examples/tutorial_builder/03_03_positional.rs":"ee4057bb14416b80eff1ac6a26adaca28dff601501dca0204bd5d9af3aaff033","examples/tutorial_builder/03_04_subcommands.rs":"f57e11b4082a23887741eaf4869a60fd8a4e8bcf60d63e6047120b8a9182829f","examples/tutorial_builder/03_05_default_values.rs":"883e2f2be05046e6ff5de9a9069609846247b1e2cd5b75b19633295b5d05b392","examples/tutorial_builder/04_01_enum.rs":"25fbd7fff15164ab868964b9983e05dac7a27a27e72f2643482df4f95a4a5a42","examples/tutorial_builder/04_01_possible.rs":"4782a6f95770a093217fdb257100898d93282d6feaed5ae0db951dd1ccdbaac2","examples/tutorial_builder/04_02_validate.rs":"a66118adb631947131807a07bcf468adfb69b5ab8b789ec73a57ca2bdd085de4","examples/tutorial_builder/04_03_relations.rs":"8c7922f5cef0505a344daefd8e514ed821cb94d0dd070cc78070a3158a9b03ab","examples/tutorial_builder/04_04_custom.rs":"291fd0d6ee571f04cb121a320158c72c85867b4be90729593b0d3fbb6bdc4c3c","examples/tutorial_builder/05_01_assert.rs":"03a2e2ebe949d4ba0cdb435c6ffd91501f9724faa71b24d3eecb1edbd45f728d","examples/tutorial_builder/README.md":"53b102e904ea3ffd563353b7f9e696f4b110b6c0b8e00fd91acd664651c68116","examples/tutorial_derive/01_quick.rs":"5687707ceae990e488037e86f479e9a49a8d905b76601e8460424eeb095cbd76","examples/tutorial_derive/02_app_settings.rs":"3076d14899573716310e8b463d91492b443b7060ea50843972c42a9342381cf7","examples/tutorial_derive/02_apps.rs":"5c71c66b2a6ad0d57c47e911fc7d9ea9163064b89ee2ece610202b133241c3e5","examples/tutorial_derive/02_crate.rs":"345f4e9a7ba384d6008c1686009b1ba05ec646252fb56efdd02d8efd0b80d851","examples/tutorial_derive/03_01_flag_bool.rs":"8fb058ef030429ff601509e2d0f67279522d8c8639b5bafee29eaa83e983b0ba","examples/tutorial_derive/03_01_flag_count.rs":"edc54dcf8631ff60438b89871d7e92f1a97077ae4293271af2c279ec53a3d0bc","examples/tutorial_derive/03_02_option.rs":"cc9487c64a71ed272ee3ec210a87fde5cded839cb64548f0bab0a3f0c44186fe","examples/tutorial_derive/03_03_positional.rs":"092d843366f4959f917bcbeef3a521c033c623ba25dc8f8f167e9cc218024d7d","examples/tutorial_derive/03_04_subcommands.rs":"1a9ea5dee9856dddbaba2342ed295d64eac53f90bc6c8c0d6ee8ab7f318edc0e","examples/tutorial_derive/03_05_default_values.rs":"28dacd9836fe525dab37b0095c8df40d8fa0c19457c0d09ac32f0f7b8972baeb","examples/tutorial_derive/04_01_enum.rs":"12fbe926afa371c633e36324c9e18976ac8b375939f7d637c9fcfabb0833a297","examples/tutorial_derive/04_02_validate.rs":"ecd08d395fd455cb4a167c29279dabfa0be13cc19d70cd9a9fe199725a3efe83","examples/tutorial_derive/04_03_relations.rs":"ede16700d983aa08081d29054cd946237c67951e3c7f3ee92d432a7abcb3952e","examples/tutorial_derive/04_04_custom.rs":"8c4d6849430aeb9fb76e0cea33d7815a41e144b918844e14fc9e62d3ce9058a9","examples/tutorial_derive/05_01_assert.rs":"75c61f1281291d7c7d1483964d6c04185daed94bc2700050963b6e5dee12795e","examples/tutorial_derive/README.md":"c4892eadcaf0ea425945d4b82f1a18a949a671fad849217ed1db8922605f0032","src/build/app/debug_asserts.rs":"c2de27dda3c5e1908accfdd097762bf1f6f93ab04af8eedf78abc443b87e13e5","src/build/app/mod.rs":"8a60a94c75f777bacaab3fc1b997b4c1089169d3c6c39a16974bb3376e734c22","src/build/app/settings.rs":"439b5a139d50832736da7f30e1748e8035475a2bfdbd7942322826b1b078f54c","src/build/app/tests.rs":"59ff6cdaed75eb3a6832453499e6c6abff5b55c9ab9b3533c154c9c35c81acbd","src/build/arg/debug_asserts.rs":"c8c9556d497a7b81d5caaf9c51594dfa1a1ced40bb4f9565590b76ba926755db","src/build/arg/mod.rs":"c67d625fbc378fcc8e58a380a4c457553937e3fe0d56654db84c31ebb10fd08c","src/build/arg/possible_value.rs":"8ed9410b2384ff342484ed2dc2597226a4e721e5fae814cfeaec1912d185bea0","src/build/arg/regex.rs":"b18891310186ecdcca9bb611833b7188cc80fe72e9fef27b63fa076b880a1acb","src/build/arg/settings.rs":"5533c231f3a74670282ee6441e01492b8f8059cf7c57b08a82acf0a74f330d34","src/build/arg/tests.rs":"d3320cb8317db0473289dad5137ca6ff2f0ef31c2aa4cdbfd549d88853ec5b74","src/build/arg/value_hint.rs":"e40604c01b58815f118118f4f3de481354779e1a41925cd27a9ae186b4da6f96","src/build/arg_group.rs":"c3e0c04c677769fa043bb7d7311ca922943c022f1d9069814fbea49e02a092a7","src/build/macros.rs":"904e42e72c49107ae324f45d5df24fbff13b9c7d4589f1a4ae38594add704434","src/build/mod.rs":"62de0f151e54f2a9d563c006108156882649fdda86f849a8f4b25f9508190051","src/build/usage_parser.rs":"9218cdfbbcfd7b55ec767036f5d21e07edcd098ea3e9f62cfba14d05e95a7bd3","src/derive.rs":"2b7180eeef3ef4be3111cdedf28885e75d3833210cdad23166d49864e24af4fc","src/lib.rs":"2955ccfdf911f6614a216ad3e352bd8b4a09ff894c8513ad8f6deb3142d54cd2","src/macros.rs":"03a1540909c4c472301bbc162afede5255e21dba73404e2035af29b57ad48a21","src/mkeymap.rs":"b3f695aa04f2c7e1e951cd6dbd545b229f361fa0fc97ebff1ba03879f52d4fd8","src/output/fmt.rs":"b6ec41c78ce226004b3867b5013a89c0c7015309334ad4949ae579685d62a96d","src/output/help.rs":"9b455854abbc1499efca8d785ab4a4a88ec2e07b12319071c08478dccebbbf9f","src/output/mod.rs":"3a61f89a4568e95114a3ab839da8f3c4c92de2a228549308f5d1be076a474917","src/output/usage.rs":"42100920ce0173ee215f0be840b1c13344ce54074d0febb01ccbab8c2cb845b2","src/parse/arg_matcher.rs":"f9b978330e82b390beddcf821b2ab307a10066c55907b8517561b19a7dd3bd94","src/parse/errors.rs":"ccc178376caae59088a306fb980d797f6b2ec1942403c6c0b601345f5e0cf350","src/parse/features/mod.rs":"6ed075e97af56bff22f22ed1ee83ff6479360e05f9d3661a3145f822c242b694","src/parse/features/suggestions.rs":"06709bf7a19abdc230445d17d9fa96bb0840bbff5ab1b4d0a050de4aeb89d292","src/parse/matches/arg_matches.rs":"0b91cd7ea3723873b3a5a274c56f2883fac6c6b007499ad8b72757cc94b16027","src/parse/matches/matched_arg.rs":"2abbdc7ab5976f11d8105299f9cff9bba42f3c5dc3d1f61dfa4896f62535ee06","src/parse/matches/mod.rs":"26f478e97311f8c758dfd12b85ea811f3954ca9486504027daa0c488ad5957c1","src/parse/mod.rs":"d57a14b8732fbd4aa0789cc221a8a9058ece265dbf1c2df7cd329f48860febee","src/parse/parser.rs":"d60c343720c29e8604603094a64d86a0c17e38dff77dd4ac9f8022fa65265d27","src/parse/validator.rs":"d6dcb4c87726cf2d9e865ef4a01cb9c2571a8a62b852cf3de95ad0ba01f13d0d","src/util/color.rs":"e207e5850ac71a88a032a42734414721d0a71581eb94023c64721d804c5dd00c","src/util/fnv.rs":"82492d91d990f38b62de8b3c3e67f1fad55919117b1f448aa28acf6d21919fd7","src/util/graph.rs":"f35396b6e2a427377dcbbca69b1b98737d89684a3834cfda98cbf8cc70ff9c2f","src/util/id.rs":"fc498c65887385d92a51359a2f72556c2e508ee49b8cac4b3f827512795d690d","src/util/mod.rs":"702c2567286d80f9ccb4e6910cda690965f23b21a93c4cd286f37e7890e92783","src/util/str_to_bool.rs":"f9302078014c7b8f493811f2bc0bcbb982c33efde6c5ca98bea479781c1501b7"},"package":"7a30c3bf9ff12dfe5dae53f0a96e0febcd18420d1c0e7fad77796d9d5c4b5375"} \ No newline at end of file diff --git a/third_party/rust/clap/CHANGELOG.md b/third_party/rust/clap/CHANGELOG.md deleted file mode 100644 index 7f61b8410e9d..000000000000 --- a/third_party/rust/clap/CHANGELOG.md +++ /dev/null @@ -1,2902 +0,0 @@ - -## v2.34.0 (2021-11-30) - -- Updates to Rust 2018 edition and bumps the MSRV to Rust 1.46 - - -### v2.33.4 (2021-11-29) - -#### Bug Fixes - -* **prevents `panic`:** swallows broken pipe errors on error output ([7a729bc4](https://github.com/kbknapp/clap-rs/commit/7a729bc4df2646b05f6bf15f001124cd39d076ce)) - - -### v2.33.3 (2020-08-13) - -#### Improvements - -* Suppress deprecation warnings when using `crate_*` macros. - - -### v2.33.2 (2020-08-5) - -#### Documentation - -* Fixed links to `2.x` examples. Now they point to the right place. - - -### v2.33.1 (2020-05-11) - -#### Bug Fixes - -* Windows: Prevent some panics when parsing invalid Unicode on Windows ([922c645](https://github.com/clap-rs/clap/commit/922c64508389170c9c77f1c8a4e597d14d3ed2f0), closes [#1905](https://github.com/clap-rs/clap/issues/1905)) - -#### Documentation - -* fixes versions referenced in the README ([d307466a](https://github.com/kbknapp/clap-rs/commit/d307466af1013f172b8ec0252f01a473e2192d6b)) -* **README.md:** - * cuts down the number of examples to reduce confusion ([6e508ee0](https://github.com/kbknapp/clap-rs/commit/6e508ee09e7153de4adf4e88b0aa6418a537dadd)) - -#### Improvements - -* **Deps:** doesnt compile ansi_term on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155)) - -#### Minimum Required Rust - -* As of this release, `clap` requires `rustc 1.36.0` or greater. - - -## v2.33.0 (2019-04-06) - -#### New Sponsor - -* Stephen Oats is now a sponsor \o/ ([823457c0](https://github.com/kbknapp/clap-rs/commit/823457c0ef5e994ed7080cf62addbfe1aa3b1833)) -* **SPONSORS.md:** fixes Josh Triplett's info in the sponsor document ([24cb5740](https://github.com/kbknapp/clap-rs/commit/24cb574090a11159b48bba105d5ec2dfb0a20e4e)) - -#### Features - -* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9)) -* There is a new setting to disable automatic building of `--help` and `-h` flags (`AppSettings::DisableAutoHelp`) - -#### Improvements - -* **arg_matches.rs:** add Debug implementations ([47192b7a](https://github.com/kbknapp/clap-rs/commit/47192b7a2d84ec716b81ae4af621e008a8762dc9)) -* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559)) - -#### Documentation - -* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c)) -* **README.md:** use https for all links ([96a7639a](https://github.com/kbknapp/clap-rs/commit/96a7639a36bcb184c3f45348986883115ef1ab3a)) - -#### Bug Fixes - -* add debug assertion for missing args in subcommand ArgGroup ([2699d9e5](https://github.com/kbknapp/clap-rs/commit/2699d9e51e7eadc258ba64c4e347c5d1fef61343)) -* Restore compat with Rust 1.21 ([6b263de1](https://github.com/kbknapp/clap-rs/commit/6b263de1d42ede692ec5ee55019ad2fc6386f92e)) -* Dont mention unused subcommands ([ef92e2b6](https://github.com/kbknapp/clap-rs/commit/ef92e2b639ed305bdade4741f60fa85cb0101c5a)) -* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4)) -* **arg_enum!:** - * Fix comma position for valid values. ([1f1f9ff3](https://github.com/kbknapp/clap-rs/commit/1f1f9ff3fa38a43231ef8be9cfea89a32e53f518)) - * Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862)) -* **completions:** improve correctness of completions when whitespace is involved ([5a08ff29](https://github.com/kbknapp/clap-rs/commit/5a08ff295b2aa6ce29420df6252a0e3ff4441bdc)) -* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897)) -* **macros:** fixes broken pattern which prevented calling multi-argument Arg methods ([9e7a352e](https://github.com/kbknapp/clap-rs/commit/9e7a352e13aaf8025d80f2bac5c47fb32528672b)) -* **parser:** Better interaction between AllowExternalSubcommands and SubcommandRequired ([9601c95a](https://github.com/kbknapp/clap-rs/commit/9601c95a03d2b82bf265c328b4769238f1b79002)) - -#### Minimum Required Rust - -* As of this release, `clap` requires `rustc 1.31.0` or greater. - - -## v2.32.0 (2018-06-26) - -#### Minimum Required Rust - -* As of this release, `clap` requires `rustc 1.21.0` or greater. - - -#### Features - -* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9)) - -#### Improvements - -* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559)) - -#### Bug Fixes - -* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4)) -* **arg_enum!:** Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862)) -* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897)) - -#### Documentation - -* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c)) - - - - -### v2.31.2 (2018-03-19) - -#### Bug Fixes - -* **Fish Completions:** fixes a bug that only allowed a single completion in in Fish Shell ([e8774a8](https://github.com/kbknapp/clap-rs/pull/1214/commits/e8774a84ee4a319c888036e7c595ab46451d8e48), closes [#1212](https://github.com/kbknapp/clap-rs/issues/1212)) -* **AllowExternalSubcommands**: fixes a bug where external subcommands would be blocked by a similarly named subcommand (suggestions were getting in the way). ([a410e85](https://github.com/kbknapp/clap-rs/pull/1215/commits/a410e855bcd82b05f9efa73fa8b9774dc8842c6b)) - -#### Documentation - -* Fixes some typos in the `README.md` ([c8e685d7](https://github.com/kbknapp/clap-rs/commit/c8e685d76adee2a3cc06cac6952ffcf6f9548089)) - - -### v2.31.1 (2018-03-06) - - -#### Improvements - -* **AllowMissingPositional:** improves the ability of AllowMissingPositional to allow 'skipping' to the last positional arg with '--' ([df20e6e2](https://github.com/kbknapp/clap-rs/commit/df20e6e24b4e782be0b423b484b9798e3e2efe2f)) - - - -## v2.31.0 (2018-03-04) - - -#### Features - -* **Arg Indices:** adds the ability to query argument value indices ([f58d0576](https://github.com/kbknapp/clap-rs/commit/f58d05767ec8133c8eb2de117cb642b9ae29ccbc)) -* **Indices:** implements an Indices iterator ([1e67be44](https://github.com/kbknapp/clap-rs/commit/1e67be44f0ccf161cc84c4e6082382072e89c302)) -* **Raw Args** adds a convenience function to `Arg` that allows implying all of `Arg::last` `Arg::allow_hyphen_values` and `Arg::multiple(true)` ([66a78f29](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) - -#### Documentation - -* Fix some typos and markdown issues. ([935ba0dd](https://github.com/kbknapp/clap-rs/commit/935ba0dd547a69c3f636c5486795012019408794)) -* **Arg Indices:** adds the documentation for the arg index querying methods ([50bc0047](https://github.com/kbknapp/clap-rs/commit/50bc00477afa64dc6cdc5de161d3de3ba1d105a7)) -* **CONTRIBUTING.md:** fix url to clippy upstream repo to point to https://github.com/rust-lang-nursery/rust-clippy instead of https://github.com/Manishearth/rust-clippy ([42407d7f](https://github.com/kbknapp/clap-rs/commit/42407d7f21d794103cda61f49d2615aae0a4bcd9)) -* **Values:** improves the docs example of the Values iterator ([74075d65](https://github.com/kbknapp/clap-rs/commit/74075d65e8db1ddb5e2a4558009a5729d749d1b6)) -* Updates readme to hint that the `wrap_help` feature is a thing ([fc7ab227](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) - -### Improvements - -* Cargo.toml: use codegen-units = 1 in release and bench profiles ([19f425ea](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2)) -* Adds WASM support (clap now compiles on WASM!) ([689949e5](https://github.com/kbknapp/clap-rs/commit/689949e57d390bb61bc69f3ed91f60a2105738d0)) -* Uses the short help tool-tip for PowerShell completion scripts ([ecda22ce](https://github.com/kbknapp/clap-rs/commit/ecda22ce7210ce56d7b2d1a5445dd1b8a2959656)) - - - -## v2.30.0 (2018-02-13) - -#### Bug Fixes - -* **YAML:** Adds a missing conversion from `Arg::last` when instantiating from a YAML file ([aab77c81a5](https://github.com/kbknapp/clap-rs/pull/1175/commits/aab77c81a519b045f95946ae0dd3e850f9b93070), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1173)) - -#### Improvements - -* **Bash Completions:** instead of completing a generic option name, all bash completions fall back to file completions UNLESS `Arg::possible_values` was used ([872f02ae](https://github.com/kbknapp/clap-rs/commit/872f02aea900ffa376850a279eb164645e1234fa)) -* **Deps:** No longer needlessly compiles `ansi_term` on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155)) -* **Help Message:** changes the `[values: foo bar baz]` array to `[possible values: foo bar baz]` for consistency with the API ([414707e4e97](https://github.com/kbknapp/clap-rs/pull/1176/commits/414707e4e979d07bfe555247e5d130c546673708), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1160)) - - - -### v2.29.4 (2018-02-06) - - -#### Bug Fixes - -* **Overrides Self:** fixes a bug where options with multiple values couldnt ever have multiple values ([d95907cf](https://github.com/kbknapp/clap-rs/commit/d95907cff6d011a901fe35fa00b0f4e18547a1fb)) - - - - -### v2.29.3 (2018-02-05) - - -#### Improvements - -* **Overrides:** clap now supports arguments which override with themselves ([6c7a0010](https://github.com/kbknapp/clap-rs/commit/6c7a001023ca1eac1cc6ffe6c936b4c4a2aa3c45), closes [#976](https://github.com/kbknapp/clap-rs/issues/976)) - -#### Bug Fixes - -* **Requirements:** fixes an issue where conflicting args would still show up as required ([e06cefac](https://github.com/kbknapp/clap-rs/commit/e06cefac97083838c0a4e1444dcad02a5c3f911e), closes [#1158](https://github.com/kbknapp/clap-rs/issues/1158)) -* Fixes a bug which disallows proper nesting of `--` ([73993fe](https://github.com/kbknapp/clap-rs/commit/73993fe30d135f682e763ec93dcb0814ed518011), closes [#1161](https://github.com/kbknapp/clap-rs/issues/1161)) - -#### New Settings - -* **AllArgsOverrideSelf:** adds a new convenience setting to allow all args to override themselves ([4670325d](https://github.com/kbknapp/clap-rs/commit/4670325d1bf0369addec2ae2bcb56f1be054c924)) - - - - -### v2.29.2 (2018-01-16) - - -#### Features - -* **completions/zsh.rs:** - * Escape possible values for options ([25561dec](https://github.com/kbknapp/clap-rs/commit/25561decf147d329b64634a14d9695673c2fc78f)) - * Implement postional argument possible values completion ([f3b0afd2](https://github.com/kbknapp/clap-rs/commit/f3b0afd2bef8b7be97162f8a7802ddf7603dff36)) - * Complete positional arguments properly ([e39aeab8](https://github.com/kbknapp/clap-rs/commit/e39aeab8487596046fbdbc6a226e5c8820585245)) - -#### Bug Fixes - -* **completions/zsh.rs:** - * Add missing autoload for is-at-least ([a6522607](https://github.com/kbknapp/clap-rs/commit/a652260795d1519f6ec2a7a09ccc1258499cad7b)) - * Don't pass -S to _arguments if Zsh is too old ([16b4f143](https://github.com/kbknapp/clap-rs/commit/16b4f143ff466b7ef18a267bc44ade0f9639109b)) - * Maybe fix completions with mixed positionals and subcommands ([1146f0da](https://github.com/kbknapp/clap-rs/commit/1146f0da154d6796fbfcb09db8efa3593cb0d898)) -* **completions/zsh.zsh:** Remove redundant code from output ([0e185b92](https://github.com/kbknapp/clap-rs/commit/0e185b922ed1e0fd653de00b4cd8d567d72ff68e), closes [#1142](https://github.com/kbknapp/clap-rs/issues/1142)) - - - - -### 2.29.1 (2018-01-09) - - -#### Documentation - -* fixes broken links. ([56e734b8](https://github.com/kbknapp/clap-rs/commit/56e734b839303d733d2e5baf7dac39bd7b97b8e4)) -* updates contributors list ([e1313a5a](https://github.com/kbknapp/clap-rs/commit/e1313a5a0f69d8f4016f73b860a63af8318a6676)) - -#### Performance - -* further debloating by removing generics from error cases ([eb8d919e](https://github.com/kbknapp/clap-rs/commit/eb8d919e6f3443db279ba0c902f15d76676c02dc)) -* debloats clap by deduplicating logic and refactors ([03e413d7](https://github.com/kbknapp/clap-rs/commit/03e413d7175d35827cd7d8908d47dbae15a849a3)) - -#### Bug Fixes - -* fixes the ripgrep benchmark by adding a value to a flag that expects it ([d26ab2b9](https://github.com/kbknapp/clap-rs/commit/d26ab2b97cf9c0ea675b440b7b0eaf6ac3ad01f4)) -* **bash completion:** Change the bash completion script code generation to support hyphens. ([ba7f1d18](https://github.com/kbknapp/clap-rs/commit/ba7f1d18eba7a07ce7f57e0981986f66c994b639)) -* **completions/zsh.rs:** Fix completion of long option values ([46365cf8](https://github.com/kbknapp/clap-rs/commit/46365cf8be5331ba04c895eb183e2f230b5aad51)) - - - -## 2.29.0 (2017-12-02) - - -#### API Additions - -* **Arg:** adds Arg::hide_env_values(bool) which allows one to hide any current env values and display only the key in help messages ([fb41d062](https://github.com/kbknapp/clap-rs/commit/fb41d062eedf37cb4f805c90adca29909bd197d7)) - - - - -## 2.28.0 (2017-11-28) - -The minimum required Rust is now 1.20. This was done to start using bitflags 1.0 and having >1.0 deps is a *very good* thing! - -#### Documentation - -* changes the demo version to 2.28 to stay in sync ([ce6ca492](https://github.com/kbknapp/clap-rs/commit/ce6ca492c7510ab6474075806360b96081b021a9)) -* Fix URL path to github hosted files ([ce72aada](https://github.com/kbknapp/clap-rs/commit/ce72aada56a9581d4a6cb4bf9bdb861c3906f8df), closes [#1106](https://github.com/kbknapp/clap-rs/issues/1106)) -* fix typo ([002b07fc](https://github.com/kbknapp/clap-rs/commit/002b07fc98a1c85acb66296b1eec0b2aba906125)) -* **README.md:** updates the readme and pulls out some redundant sections ([db6caf86](https://github.com/kbknapp/clap-rs/commit/db6caf8663747e679d2f4ed3bd127f33476754aa)) - -#### Improvements - -* adds '[SUBCOMMAND]' to usage strings with only AppSettings::AllowExternalSubcommands is used with no other subcommands ([e78bb757](https://github.com/kbknapp/clap-rs/commit/e78bb757a3df16e82d539e450c06767a6bfcf859), closes [#1093](https://github.com/kbknapp/clap-rs/issues/1093)) - -#### API Additions - -* Adds Arg::case_insensitive(bool) which allows matching Arg::possible_values without worrying about ASCII case ([1fec268e](https://github.com/kbknapp/clap-rs/commit/1fec268e51736602e38e67c76266f439e2e0ef12), closes [#1118](https://github.com/kbknapp/clap-rs/issues/1118)) -* Adds the traits to be used with the clap-derive crate to be able to use Custom Derive ([6f4c3412](https://github.com/kbknapp/clap-rs/commit/6f4c3412415e882f5ca2cc3fbd6d4dce79440828)) - -#### Bug Fixes - -* Fixes a regression where --help couldn't be overridden ([a283d69f](https://github.com/kbknapp/clap-rs/commit/a283d69fc08aa016ae1bf9ba010012abecc7ba69), closes [#1112](https://github.com/kbknapp/clap-rs/issues/1112)) -* fixes a bug that allowed options to pass parsing when no value was provided ([2fb75821](https://github.com/kbknapp/clap-rs/commit/2fb758219c7a60d639da67692e100b855a8165ac), closes [#1105](https://github.com/kbknapp/clap-rs/issues/1105)) -* ignore PropagateGlobalValuesDown deprecation warning ([f61ce3f5](https://github.com/kbknapp/clap-rs/commit/f61ce3f55fe65e16b3db0bd4facdc4575de22767), closes [#1086](https://github.com/kbknapp/clap-rs/issues/1086)) - -#### Deps - -* Updates `bitflags` to 1.0 - - - - -## v2.27.1 (2017-10-24) - - -#### Bug Fixes - -* Adds `term_size` as an optional dependency (with feature `wrap_help`) to fix compile bug - - -## v2.27.0 (2017-10-24) - -** This release raises the minimum required version of Rust to 1.18 ** - -** This release also contains a very minor breaking change to fix a bug ** - -The only CLIs affected will be those using unrestrained multiple values and subcommands where the -subcommand name can coincide with one of the multiple values. - -See the commit [0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31) for full details. - - -#### Bug Fixes - -* Values from global args are now propagated UP and DOWN! -* fixes a bug where using AppSettings::AllowHyphenValues would allow invalid arguments even when there is no way for them to be valid ([77ed4684](https://github.com/kbknapp/clap-rs/commit/77ed46841fc0263d7aa32fcc5cc49ef703b37c04), closes [#1066](https://github.com/kbknapp/clap-rs/issues/1066)) -* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/)) -* fixes a bug that prevented number_of_values and default_values to be used together ([5eb342a9](https://github.com/kbknapp/clap-rs/commit/5eb342a99dde07b0f011048efde3e283bc1110fc), closes [#1050](https://github.com/kbknapp/clap-rs/issues/1050), [#1056](https://github.com/kbknapp/clap-rs/issues/1056)) -* fixes a bug that didn't allow args with default values to have conflicts ([58b5b4be](https://github.com/kbknapp/clap-rs/commit/58b5b4be315280888d50d9b15119b91a9028f050), closes [#1071](https://github.com/kbknapp/clap-rs/issues/1071)) -* fixes a panic when using global args and calling App::get_matches_from_safe_borrow multiple times ([d86ec797](https://github.com/kbknapp/clap-rs/commit/d86ec79742c77eb3f663fb30e225954515cf25bb), closes [#1076](https://github.com/kbknapp/clap-rs/issues/1076)) -* fixes issues and potential regressions with global args values not being propagated properly or at all ([a43f9dd4](https://github.com/kbknapp/clap-rs/commit/a43f9dd4aaf1864dd14a3c28dec89ccdd70c61e5), closes [#1010](https://github.com/kbknapp/clap-rs/issues/1010), [#1061](https://github.com/kbknapp/clap-rs/issues/1061), [#978](https://github.com/kbknapp/clap-rs/issues/978)) -* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047)) - -#### Documentation - -* adds addtional blurbs about using multiples with subcommands ([03455b77](https://github.com/kbknapp/clap-rs/commit/03455b7751a757e7b2f6ffaf2d16168539c99661)) -* updates the docs to reflect changes to global args and that global args values can now be propagated back up the stack ([ead076f0](https://github.com/kbknapp/clap-rs/commit/ead076f03ada4c322bf3e34203925561ec496d87)) -* add html_root_url attribute ([e67a061b](https://github.com/kbknapp/clap-rs/commit/e67a061bcf567c6518d6c2f58852e01f02764b22)) -* sync README version numbers with crate version ([5536361b](https://github.com/kbknapp/clap-rs/commit/5536361bcda29887ed86bb68e43d0b603cbc423f)) - -#### Improvements - -* args that have require_delimiter(true) is now reflected in help and usage strings ([dce61699](https://github.com/kbknapp/clap-rs/commit/dce616998ed9bd95e8ed3bec1f09a4883da47b85), closes [#1052](https://github.com/kbknapp/clap-rs/issues/1052)) -* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046)) - -#### Breaking Changes - -* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/)) - -#### Deprecations - -* **AppSettings::PropagateGlobalValuesDown:** this setting is no longer required to propagate values down or up ([2bb5ddce](https://github.com/kbknapp/clap-rs/commit/2bb5ddcee61c791ca1aaca494fbeb4bd5e277488)) - - - - -### v2.26.2 (2017-09-14) - - -#### Improvements - -* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046)) - -#### Bug Fixes - -* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047)) - - - - -### v2.26.1 (2017-09-14) - - -#### Bug Fixes - -* fixes using require_equals(true) and min_values(0) together ([10ae208f](https://github.com/kbknapp/clap-rs/commit/10ae208f68518eff6e98166724065745f4083174), closes [#1044](https://github.com/kbknapp/clap-rs/issues/1044)) -* escape special characters in zsh and fish completions ([87e019fc](https://github.com/kbknapp/clap-rs/commit/87e019fc84ba6193a8c4ddc26c61eb99efffcd25)) -* avoid panic generating default help msg if term width set to 0 due to bug in textwrap 0.7.0 ([b3eadb0d](https://github.com/kbknapp/clap-rs/commit/b3eadb0de516106db4e08f078ad32e8f6d6e7a57)) -* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349)) -* adds a debug assertion to ensure all args added to groups actually exist ([7ad123e2](https://github.com/kbknapp/clap-rs/commit/7ad123e2c02577e3ca30f7e205181e896b157d11), closes [#917](https://github.com/kbknapp/clap-rs/issues/917)) -* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ab2f4c9e](https://github.com/kbknapp/clap-rs/commit/ab2f4c9e563e36ec739a4b55d5a5b76fdb9e9fa4), closes [#960](https://github.com/kbknapp/clap-rs/issues/960)) -* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21)) -* **Help Message:** fixes long_about not being usable ([a8257ea0](https://github.com/kbknapp/clap-rs/commit/a8257ea0ffb812e552aca256c4a3d2aebfd8065b), closes [#1043](https://github.com/kbknapp/clap-rs/issues/1043)) -* **Suggestions:** output for flag after subcommand ([434ea5ba](https://github.com/kbknapp/clap-rs/commit/434ea5ba71395d8c1afcf88e69f0b0d8339b01a1)) - - - - -## v2.26.0 (2017-07-29) - -Minimum version of Rust is now v1.13.0 (Stable) - - -#### Improvements - -* bumps unicode-segmentation to v1.2 ([cd7b40a2](https://github.com/kbknapp/clap-rs/commit/cd7b40a21c77bae17ba453c5512cb82b7d1ce474)) - - -#### Performance - -* update textwrap to version 0.7.0 ([c2d4e637](https://github.com/kbknapp/clap-rs/commit/c2d4e63756a6f070e38c16dff846e9b0a53d6f93)) - - - - - -### v2.25.1 (2017-07-21) - -#### Improvements - -* impl Default for Values + OsValues for any lifetime. ([fb7d6231f1](https://github.com/kbknapp/clap-rs/commit/fb7d6231f13a2f79f411e62dca210b7dc9994c18)) - -#### Documentation - -* Various documentation typos and grammar fixes - - -### v2.25.0 (2017-06-20) - - -#### Features - -* use textwrap crate for wrapping help texts ([b93870c1](https://github.com/kbknapp/clap-rs/commit/b93870c10ae3bd90d233c586a33e086803117285)) - -#### Improvements - -* **Suggestions:** suggests to use flag after subcommand when applicable ([2671ca72](https://github.com/kbknapp/clap-rs/commit/2671ca7260119d4311d21c4075466aafdd9da734)) -* Bumps bitflags crate to v0.9 - -#### Documentation - -* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349)) - -#### Documentation - -* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cbea3d5a](https://github.com/kbknapp/clap-rs/commit/cbea3d5acf3271a7a734498c4d99c709941c331e), closes [#949](https://github.com/kbknapp/clap-rs/issues/949)) -* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([f9b0d657](https://github.com/kbknapp/clap-rs/commit/f9b0d657835d3f517f313d70962177dc30acf4a7)) -* **README.md:** - * added a warning about using ~ deps ([821929b5](https://github.com/kbknapp/clap-rs/commit/821929b51bd60213955705900a436c9a64fcb79f), closes [#964](https://github.com/kbknapp/clap-rs/issues/964)) -* **clap_app!:** adds using the @group specifier to the macro docs ([826048cb](https://github.com/kbknapp/clap-rs/commit/826048cb3cbc0280169303f1498ff0a2b7395883), closes [#932](https://github.com/kbknapp/clap-rs/issues/932)) - - - - -### v2.24.2 (2017-05-15) - - -#### Bug Fixes - -* adds a debug assertion to ensure all args added to groups actually exist ([14f6b8f3](https://github.com/kbknapp/clap-rs/commit/14f6b8f3a2f6df73aeeec9c54a54909b1acfc158), closes [#917](https://github.com/kbknapp/clap-rs/issues/917)) -* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ebf73a09](https://github.com/kbknapp/clap-rs/commit/ebf73a09db6f3c03c19cdd76b1ba6113930e1643), closes [#960](https://github.com/kbknapp/clap-rs/issues/960)) -* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21)) - -#### Documentation - -* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cf569438](https://github.com/kbknapp/clap-rs/commit/cf569438f309c199800bb8e46c9f140187de69d7), closes [#949](https://github.com/kbknapp/clap-rs/issues/949)) -* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([ded5a2f1](https://github.com/kbknapp/clap-rs/commit/ded5a2f15474d4a5bd46a67b130ccb8b6781bd01)) -* **clap_app!:** adds using the @group specifier to the macro docs ([fe85fcb1](https://github.com/kbknapp/clap-rs/commit/fe85fcb1772b61f13b20b7ea5290e2437a76190c), closes [#932](https://github.com/kbknapp/clap-rs/issues/932)) - - - - -### v2.24.0 (2017-05-07) - - -#### Bug Fixes - -* fixes a bug where args with last(true) and required(true) set were not being printed in the usage string ([3ac533fe](https://github.com/kbknapp/clap-rs/commit/3ac533fedabf713943eedf006f830a5a486bbe80), closes [#944](https://github.com/kbknapp/clap-rs/issues/944)) -* fixes a bug that was printing the arg name, instead of value name when Arg::last(true) was used ([e1fe8ac3](https://github.com/kbknapp/clap-rs/commit/e1fe8ac3bc1f9cf4e36df0d881f8419755f1787b), closes [#940](https://github.com/kbknapp/clap-rs/issues/940)) -* fixes a bug where flags were parsed as flags AND positional values when specific combinations of settings were used ([20f83292](https://github.com/kbknapp/clap-rs/commit/20f83292d070038b8cee2a6b47e91f6b0a2f7871), closes [#946](https://github.com/kbknapp/clap-rs/issues/946)) - - - - -## v2.24.0 (2017-05-05) - - -#### Documentation - -* **README.md:** fix some typos ([fa34deac](https://github.com/kbknapp/clap-rs/commit/fa34deac079f334c3af97bb7fb151880ba8887f8)) - -#### API Additions - -* **Arg:** add `default_value_os` ([d5ef8955](https://github.com/kbknapp/clap-rs/commit/d5ef8955414b1587060f7218385256105b639c88)) -* **arg_matches.rs:** Added a Default implementation for Values and OsValues iterators. ([0a4384e3](https://github.com/kbknapp/clap-rs/commit/0a4384e350eed74c2a4dc8964c203f21ac64897f)) - - - -### v2.23.2 (2017-04-19) - - -#### Bug Fixes - -* **PowerShell Completions:** fixes a bug where powershells completions cant be used if no subcommands are defined ([a8bce558](https://github.com/kbknapp/clap-rs/commit/a8bce55837dc4e0fb187dc93180884a40ae09c6f), closes [#931](https://github.com/kbknapp/clap-rs/issues/931)) - -#### Improvements - -* bumps term_size to take advantage of better terminal dimension handling ([e05100b7](https://github.com/kbknapp/clap-rs/commit/e05100b73d74066a90876bf38f952adf5e8ee422)) -* **PowerShell Completions:** massively dedups subcommand names in the generate script to make smaller scripts that are still functionally equiv ([85b0e1cc](https://github.com/kbknapp/clap-rs/commit/85b0e1cc4b9755dda75a93d898d79bc38631552b)) - -#### Documentation - -* Fix a typo the minimum rust version required ([71dabba3](https://github.com/kbknapp/clap-rs/commit/71dabba3ea0a17c88b0e2199c9d99f0acbf3bc17)) - - -### v2.23.1 (2017-04-05) - - -#### Bug Fixes - -* fixes a missing newline character in the autogenerated help and version messages in some instances ([5ae9007d](https://github.com/kbknapp/clap-rs/commit/5ae9007d984ae94ae2752df51bcbaeb0ec89bc15)) - - - -## v2.23.0 (2017-04-05) - - -#### API Additions - -* `App::long_about` -* `App::long_version` -* `App::print_long_help` -* `App::write_long_help` -* `App::print_long_version` -* `App::write_long_version` -* `Arg::long_help` - -#### Features - -* allows distinguishing between short and long version messages (-V/short or --version/long) ([59272b06](https://github.com/kbknapp/clap-rs/commit/59272b06cc213289dc604dbc694cb95d383a5d68)) -* allows distinguishing between short and long help with subcommands in the same manner as args ([6b371891](https://github.com/kbknapp/clap-rs/commit/6b371891a1702173a849d1e95f9fecb168bf6fc4)) -* allows specifying a short help vs a long help (i.e. varying levels of detail depending on if -h or --help was used) ([ef1b24c3](https://github.com/kbknapp/clap-rs/commit/ef1b24c3a0dff2f58c5e2e90880fbc2b69df20ee)) -* **clap_app!:** adds support for arg names with hyphens similar to longs with hyphens ([f7a88779](https://github.com/kbknapp/clap-rs/commit/f7a8877978c8f90e6543d4f0d9600c086cf92cd7), closes [#869](https://github.com/kbknapp/clap-rs/issues/869)) - -#### Bug Fixes - -* fixes a bug that wasn't allowing help and version to be properly overridden ([8b2ceb83](https://github.com/kbknapp/clap-rs/commit/8b2ceb8368bcb70689fadf1c7f4b9549184926c1), closes [#922](https://github.com/kbknapp/clap-rs/issues/922)) - -#### Documentation - -* **clap_app!:** documents the `--("some-arg")` method for using args with hyphens inside them ([bc08ef3e](https://github.com/kbknapp/clap-rs/commit/bc08ef3e185393073d969d301989b6319c616c1f), closes [#919](https://github.com/kbknapp/clap-rs/issues/919)) - - - - -### v2.22.2 (2017-03-30) - - -#### Bug Fixes - -* **Custom Usage Strings:** fixes the usage string regression when using help templates ([0e4fd96d](https://github.com/kbknapp/clap-rs/commit/0e4fd96d74280d306d09e60ac44f938a82321769)) - - - - -### v2.22.1 (2017-03-24) - - -#### Bug Fixes - -* **usage:** fixes a big regression with custom usage strings ([2c41caba](https://github.com/kbknapp/clap-rs/commit/2c41caba3c7d723a2894e315d04da796b0e97759)) - - -## v2.22.0 (2017-03-23) - -#### API Additions - -* **App::name:** adds the ability to change the name of the App instance after creation ([d49e8292](https://github.com/kbknapp/clap-rs/commit/d49e8292b026b06e2b70447cd9f08299f4fcba76), closes [#908](https://github.com/kbknapp/clap-rs/issues/908)) -* **Arg::hide_default_value:** adds ability to hide the default value of an argument from the help string ([89e6ea86](https://github.com/kbknapp/clap-rs/commit/89e6ea861e16a1ad56757ca12f6b32d02253e44a), closes [#902](https://github.com/kbknapp/clap-rs/issues/902)) - - - -### v2.21.3 (2017-03-23) - -#### Bug Fixes - -* **yaml:** adds support for loading author info from yaml ([e04c390c](https://github.com/kbknapp/clap-rs/commit/e04c390c597a55fa27e724050342f16c42f1c5c9)) - - - -### v2.21.2 (2017-03-17) - - -#### Improvements - -* add fish subcommand help support ([f8f68cf8](https://github.com/kbknapp/clap-rs/commit/f8f68cf8251669aef4539a25a7c1166f0ac81ea6)) -* options that use `require_equals(true)` now display the equals sign in help messages, usage strings, and errors" ([c8eb0384](https://github.com/kbknapp/clap-rs/commit/c8eb0384d394d2900ccdc1593099c97808a3fa05), closes [#903](https://github.com/kbknapp/clap-rs/issues/903)) - - -#### Bug Fixes - -* setting the max term width now correctly propagates down through child subcommands - - - - -### v2.21.1 (2017-03-12) - - -#### Bug Fixes - -* **ArgRequiredElseHelp:** fixes the precedence of this error to prioritize over other error messages ([74b751ff](https://github.com/kbknapp/clap-rs/commit/74b751ff2e3631e337b7946347c1119829a41c53), closes [#895](https://github.com/kbknapp/clap-rs/issues/895)) -* **Positionals:** fixes some regression bugs resulting from old asserts in debug mode. ([9a3bc98e](https://github.com/kbknapp/clap-rs/commit/9a3bc98e9b55e7514b74b73374c5ac8b6e5e0508), closes [#896](https://github.com/kbknapp/clap-rs/issues/896)) - - - - -## v2.21.0 (2017-03-09) - -#### Performance - -* doesn't run `arg_post_processing` on multiple values anymore ([ec516182](https://github.com/kbknapp/clap-rs/commit/ec5161828729f6a53f0fccec8648f71697f01f78)) -* changes internal use of `VecMap` to `Vec` for matched values of `Arg`s ([22bf137a](https://github.com/kbknapp/clap-rs/commit/22bf137ac581684c6ed460d2c3c640c503d62621)) -* vastly reduces the amount of cloning when adding non-global args minus when they're added from `App::args` which is forced to clone ([8da0303b](https://github.com/kbknapp/clap-rs/commit/8da0303bc02db5fe047cfc0631a9da41d9dc60f7)) -* refactor to remove unneeded vectors and allocations and checks for significant performance increases ([0efa4119](https://github.com/kbknapp/clap-rs/commit/0efa4119632f134fc5b8b9695b007dd94b76735d)) - -#### Documentation - -* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1)) - -#### Improvements - -* when `AppSettings::SubcommandsNegateReqs` and `ArgsNegateSubcommands` are used, a new more accurate double line usage string is shown ([50f02300](https://github.com/kbknapp/clap-rs/commit/50f02300d81788817acefef0697e157e01b6ca32), closes [#871](https://github.com/kbknapp/clap-rs/issues/871)) - -#### API Additions - -* **Arg::last:** adds the ability to mark a positional argument as 'last' which means it should be used with `--` syntax and can be accessed early ([6a7aea90](https://github.com/kbknapp/clap-rs/commit/6a7aea9043b83badd9ab038b4ecc4c787716147e), closes [#888](https://github.com/kbknapp/clap-rs/issues/888)) -* provides `default_value_os` and `default_value_if[s]_os` ([0f2a3782](https://github.com/kbknapp/clap-rs/commit/0f2a378219a6930748d178ba350fe5925be5dad5), closes [#849](https://github.com/kbknapp/clap-rs/issues/849)) -* provides `App::help_message` and `App::version_message` which allows one to override the auto-generated help/version flag associated help ([389c413](https://github.com/kbknapp/clap-rs/commit/389c413b7023dccab8c76aa00577ea1d048e7a99), closes [#889](https://github.com/kbknapp/clap-rs/issues/889)) - -#### New Settings - -* **InferSubcommands:** adds a setting to allow one to infer shortened subcommands or aliases (i.e. for subcommmand "test", "t", "te", or "tes" would be allowed assuming no other ambiguities) ([11602032](https://github.com/kbknapp/clap-rs/commit/11602032f6ff05881e3adf130356e37d5e66e8f9), closes [#863](https://github.com/kbknapp/clap-rs/issues/863)) - -#### Bug Fixes - -* doesn't print the argument sections in the help message if all args in that section are hidden ([ce5ee5f5](https://github.com/kbknapp/clap-rs/commit/ce5ee5f5a76f838104aeddd01c8ec956dd347f50)) -* doesn't include the various [ARGS] [FLAGS] or [OPTIONS] if the only ones available are hidden ([7b4000af](https://github.com/kbknapp/clap-rs/commit/7b4000af97637703645c5fb2ac8bb65bd546b95b), closes [#882](https://github.com/kbknapp/clap-rs/issues/882)) -* now correctly shows subcommand as required in the usage string when AppSettings::SubcommandRequiredElseHelp is used ([8f0884c1](https://github.com/kbknapp/clap-rs/commit/8f0884c1764983a49b45de52a1eddf8d721564d8)) -* fixes some memory leaks when an error is detected and clap exits ([8c2dd287](https://github.com/kbknapp/clap-rs/commit/8c2dd28718262ace4ae0db98563809548e02a86b)) -* fixes a trait that's marked private accidentlly, but should be crate internal public ([1ae21108](https://github.com/kbknapp/clap-rs/commit/1ae21108015cea87e5360402e1747025116c7878)) -* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846)) - -#### Features - -* **Options:** adds the ability to require the equals syntax with options --opt=val ([f002693d](https://github.com/kbknapp/clap-rs/commit/f002693dec6a6959c4e9590cb7b7bfffd6d6e5bc), closes [#833](https://github.com/kbknapp/clap-rs/issues/833)) - - - - -### v2.20.5 (2017-02-18) - - -#### Bug Fixes - -* **clap_app!:** fixes a critical bug of a missing fragment specifier when using `!property` style tags. ([5635c1f94](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94)) - - - -### v2.20.4 (2017-02-15) - - -#### Bug Fixes - -* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846)) - -#### Documentation - -* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1)) - - - -### v2.20.3 (2017-02-03) - - -#### Documentation - -* **Macros:** adds a warning about changing values in Cargo.toml not triggering a rebuild automatically ([112aea3e](https://github.com/kbknapp/clap-rs/commit/112aea3e42ae9e0c0a2d33ebad89496dbdd95e5d), closes [#838](https://github.com/kbknapp/clap-rs/issues/838)) - -#### Bug Fixes - -* fixes a println->debugln typo ([279aa62e](https://github.com/kbknapp/clap-rs/commit/279aa62eaf08f56ce090ba16b937bc763cbb45be)) -* fixes bash completions for commands that have an underscore in the name ([7f5cfa72](https://github.com/kbknapp/clap-rs/commit/7f5cfa724f0ac4e098f5fe466c903febddb2d994), closes [#581](https://github.com/kbknapp/clap-rs/issues/581)) -* fixes a bug where ZSH completions would panic if the binary name had an underscore in it ([891a2a00](https://github.com/kbknapp/clap-rs/commit/891a2a006f775e92c556dda48bb32fac9807c4fb), closes [#581](https://github.com/kbknapp/clap-rs/issues/581)) -* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828)) -* fixes a bug where global args weren't included in the generated completion scripts ([9a1e006e](https://github.com/kbknapp/clap-rs/commit/9a1e006eb75ad5a6057ebd119aa90f7e06c0ace8), closes [#841](https://github.com/kbknapp/clap-rs/issues/841)) - - - - -### v2.20.2 (2017-02-03) - -#### Bug Fixes - -* fixes a critical bug where subcommand settings were being propogated too far ([74648c94](https://github.com/kbknapp/clap-rs/commit/74648c94b893df542bfa5bb595e68c7bb8167e36), closes [#832](https://github.com/kbknapp/clap-rs/issues/832)) - - -#### Improvements - -* adds ArgGroup::multiple to the supported YAML fields for building ArgGroups from YAML ([d8590037](https://github.com/kbknapp/clap-rs/commit/d8590037ce07dafd8cd5b26928aa4a9fd3018288), closes [#840](https://github.com/kbknapp/clap-rs/issues/840)) - - -### v2.20.1 (2017-01-31) - -#### Bug Fixes - -* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828)) -* actually show character in debug output ([84d8c547](https://github.com/kbknapp/clap-rs/commit/84d8c5476de95b7f37d61888bc4f13688b712434)) -* include final character in line lenght ([aff4ba18](https://github.com/kbknapp/clap-rs/commit/aff4ba18da8147e1259b04b0bfbc1fcb5c78a3c0)) - -#### Improvements - -* updates libc and term_size deps for the libc version conflict ([6802ac4a](https://github.com/kbknapp/clap-rs/commit/6802ac4a59c142cda9ec55ca0c45ae5cb9a6ab55)) - -#### Documentation - -* fix link from app_from_crate! to crate_authors! (#822) ([5b29be9b](https://github.com/kbknapp/clap-rs/commit/5b29be9b073330ab1f7227cdd19fe4aab39d5dcb)) -* fix spelling of "guaranteed" ([4f30a65b](https://github.com/kbknapp/clap-rs/commit/4f30a65b9c03eb09607eb91a929a6396637dc105)) - - - -#### New Settings - -* **ArgsNegateSubcommands:** disables args being allowed between subcommands ([5e2af8c9](https://github.com/kbknapp/clap-rs/commit/5e2af8c96adb5ab75fa2d1536237ebcb41869494), closes [#793](https://github.com/kbknapp/clap-rs/issues/793)) -* **DontCollapseArgsInUsage:** disables the collapsing of positional args into `[ARGS]` in the usage string ([c2978afc](https://github.com/kbknapp/clap-rs/commit/c2978afc61fb46d5263ab3b2d87ecde1c9ce1553), closes [#769](https://github.com/kbknapp/clap-rs/issues/769)) -* **DisableHelpSubcommand:** disables building the `help` subcommand ([a10fc859](https://github.com/kbknapp/clap-rs/commit/a10fc859ee20159fbd9ff4337be59b76467a64f2)) -* **AllowMissingPositional:** allows one to implement `$ prog [optional] ` style CLIs where the second postional argument is required, but the first is optional ([1110fdc7](https://github.com/kbknapp/clap-rs/commit/1110fdc7a345c108820dc45783a9bf893fa4c214), closes [#636](https://github.com/kbknapp/clap-rs/issues/636)) -* **PropagateGlobalValuesDown:** automatically propagats global arg's values down through *used* subcommands ([985536c8](https://github.com/kbknapp/clap-rs/commit/985536c8ebcc09af98aac835f42a8072ad58c262), closes [#694](https://github.com/kbknapp/clap-rs/issues/694)) - -#### API Additions - -##### Arg - -* **Arg::value_terminator:** adds the ability to terminate multiple values with a given string or char ([be64ce0c](https://github.com/kbknapp/clap-rs/commit/be64ce0c373efc106384baca3f487ea99fe7b8cf), closes [#782](https://github.com/kbknapp/clap-rs/issues/782)) -* **Arg::default_value_if[s]:** adds new methods for *conditional* default values (such as a particular value from another argument was used) ([eb4010e7](https://github.com/kbknapp/clap-rs/commit/eb4010e7b21724447ef837db11ac441915728f22)) -* **Arg::requires_if[s]:** adds the ability to *conditionally* require additional args (such as if a particular value was used) ([198449d6](https://github.com/kbknapp/clap-rs/commit/198449d64393c265f0bc327aaeac23ec4bb97226)) -* **Arg::required_if[s]:** adds the ability for an arg to be *conditionally* required (i.e. "arg X is only required if arg Y was used with value Z") ([ee9cfddf](https://github.com/kbknapp/clap-rs/commit/ee9cfddf345a6b5ae2af42ba72aa5c89e2ca7f59)) -* **Arg::validator_os:** adds ability to validate values which may contain invalid UTF-8 ([47232498](https://github.com/kbknapp/clap-rs/commit/47232498a813db4f3366ccd3e9faf0bff56433a4)) - -##### Macros - -* **crate_description!:** Uses the `Cargo.toml` description field to fill in the `App::about` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) -* **crate_name!:** Uses the `Cargo.toml` name field to fill in the `App::new` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) -* **app_from_crate!:** Combines `crate_version!`, `crate_name!`, `crate_description!`, and `crate_authors!` into a single macro call to build a default `App` instance from the `Cargo.toml` fields ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778)) - - -#### Features - -* **no_cargo:** adds a `no_cargo` feature to disable Cargo-env-var-dependent macros for those *not* using `cargo` to build their crates (#786) ([6fdd2f9d](https://github.com/kbknapp/clap-rs/commit/6fdd2f9d693aaf1118fc61bd362273950703f43d)) - -#### Bug Fixes - -* **Options:** fixes a critical bug where options weren't forced to have a value ([5a5f2b1e](https://github.com/kbknapp/clap-rs/commit/5a5f2b1e9f598a0d0280ef3e98abbbba2bc41132), closes [#665](https://github.com/kbknapp/clap-rs/issues/665)) -* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([d3d34a2b](https://github.com/kbknapp/clap-rs/commit/d3d34a2b51ef31004055b0ab574f766d801c3adf), closes [#789](https://github.com/kbknapp/clap-rs/issues/789)) -* **Help Subcommand:** fixes a bug where the help subcommand couldn't be overriden ([d34ec3e0](https://github.com/kbknapp/clap-rs/commit/d34ec3e032d03e402d8e87af9b2942fe2819b2da), closes [#787](https://github.com/kbknapp/clap-rs/issues/787)) -* **Low Index Multiples:** fixes a bug which caused combinations of LowIndexMultiples and `Arg::allow_hyphen_values` to fail parsing ([26c670ca](https://github.com/kbknapp/clap-rs/commit/26c670ca16d2c80dc26d5c1ce83380ace6357318)) - -#### Improvements - -* **Default Values:** improves the error message when default values are involved ([1f33de54](https://github.com/kbknapp/clap-rs/commit/1f33de545036e7fd2f80faba251fca009bd519b8), closes [#774](https://github.com/kbknapp/clap-rs/issues/774)) -* **YAML:** adds conditional requirements and conditional default values to YAML ([9a4df327](https://github.com/kbknapp/clap-rs/commit/9a4df327893486adb5558ffefba790c634ccdc6e), closes [#764](https://github.com/kbknapp/clap-rs/issues/764)) -* Support `--("some-arg-name")` syntax for defining long arg names when using `clap_app!` macro ([f41ec962](https://github.com/kbknapp/clap-rs/commit/f41ec962c243a5ffff8b1be1ae2ad63970d3d1d4)) -* Support `("some app name")` syntax for defining app names when using `clap_app!` macro ([9895b671](https://github.com/kbknapp/clap-rs/commit/9895b671cff784f35cf56abcd8270f7c2ba09699), closes [#759](https://github.com/kbknapp/clap-rs/issues/759)) -* **Help Wrapping:** long app names (with spaces), authors, and descriptions are now wrapped appropriately ([ad4691b7](https://github.com/kbknapp/clap-rs/commit/ad4691b71a63e951ace346318238d8834e04ad8a), closes [#777](https://github.com/kbknapp/clap-rs/issues/777)) - - -#### Documentation - -* **Conditional Default Values:** fixes the failing doc tests of Arg::default_value_ifs ([4ef09101](https://github.com/kbknapp/clap-rs/commit/4ef091019c083b4db1a0c13f1c1e95ac363259f2)) -* **Conditional Requirements:** adds docs for Arg::requires_ifs ([7f296e29](https://github.com/kbknapp/clap-rs/commit/7f296e29db7d9036e76e5dbcc9c8b20dfe7b25bd)) -* **README.md:** fix some typos ([f22c21b4](https://github.com/kbknapp/clap-rs/commit/f22c21b422d5b287d1a1ac183a379ee02eebf54f)) -* **src/app/mod.rs:** fix some typos ([5c9b0d47](https://github.com/kbknapp/clap-rs/commit/5c9b0d47ca78dea285c5b9dec79063d24c3e451a)) - - -### v2.19.3 (2016-12-28) - - -#### Bug Fixes - -* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([a0ee4993](https://github.com/kbknapp/clap-rs/commit/a0ee4993015ea97b06b5bc9f378d8bcb18f1c51c), closes [#789](https://github.com/kbknapp/clap-rs/issues/789)) - - - - -### v2.19.2 (2016-12-08) - -#### Bug Fixes - -* **ZSH Completions:** escapes square brackets in ZSH completions ([7e17d5a3](https://github.com/kbknapp/clap-rs/commit/7e17d5a36b2cc2cc77e7b15796b14d639ed3cbf7), closes [#771](https://github.com/kbknapp/clap-rs/issues/771)) - -#### Documentation - -* **Examples:** adds subcommand examples ([0e0f3354](https://github.com/kbknapp/clap-rs/commit/0e0f33547a6901425afc1d9fbe19f7ae3832d9a4), closes [#766](https://github.com/kbknapp/clap-rs/issues/766)) -* **README.md:** adds guidance on when to use ~ in version pinning, and clarifies breaking change policy ([591eaefc](https://github.com/kbknapp/clap-rs/commit/591eaefc7319142ba921130e502bb0729feed907), closes [#765](https://github.com/kbknapp/clap-rs/issues/765)) - - - - -### v2.19.1 (2016-12-01) - - -#### Bug Fixes - -* **Help Messages:** fixes help message alignment when specific settings are used on options ([cd94b318](https://github.com/kbknapp/clap-rs/commit/cd94b3188d63b63295a319e90e826bca46befcd2), closes [#760](https://github.com/kbknapp/clap-rs/issues/760)) - -#### Improvements - -* **Bash Completion:** allows bash completion to fall back to traidtional bash completion upon no matching completing function ([b1b16d56](https://github.com/kbknapp/clap-rs/commit/b1b16d56d8fddf819bdbe24b3724bb6a9f3fa613))) - - - -## v2.19.0 (2016-11-21) - -#### Features - -* allows specifying AllowLeadingHyphen style values, but only for specific args vice command wide ([c0d70feb](https://github.com/kbknapp/clap-rs/commit/c0d70febad9996a77a54107054daf1914c50d4ef), closes [#742](https://github.com/kbknapp/clap-rs/issues/742)) - -#### Bug Fixes - -* **Required Unless:** fixes a bug where having required_unless set doesn't work when conflicts are also set ([d20331b6](https://github.com/kbknapp/clap-rs/commit/d20331b6f7940ac3a4e919999f8bb4780875125d), closes [#753](https://github.com/kbknapp/clap-rs/issues/753)) -* **ZSH Completions:** fixes an issue where zsh completions caused panics if there were no subcommands ([49e7cdab](https://github.com/kbknapp/clap-rs/commit/49e7cdab76dd1ccc07221e360f07808ec62648aa), closes [#754](https://github.com/kbknapp/clap-rs/issues/754)) - -#### Improvements - -* **Validators:** improves the error messages for validators ([65eb3385](https://github.com/kbknapp/clap-rs/commit/65eb33859d3ff53e7d3277f02a9d3fd9038a9dfb), closes [#744](https://github.com/kbknapp/clap-rs/issues/744)) - -#### Documentation - -* updates the docs landing page ([01e1e33f](https://github.com/kbknapp/clap-rs/commit/01e1e33f377934099a4a725fab5cd6c5ff50eaa2)) -* adds the macro version back to the readme ([45eb9bf1](https://github.com/kbknapp/clap-rs/commit/45eb9bf130329c3f3853aba0342c2fe3c64ff80f)) -* fix broken docs links ([808e7cee](https://github.com/kbknapp/clap-rs/commit/808e7ceeb86d4a319bdc270f51c23a64621dbfb3)) -* **Compatibility Policy:** adds an official compatibility policy to ([760d66dc](https://github.com/kbknapp/clap-rs/commit/760d66dc17310b357f257776624151da933cd25d), closes [#740](https://github.com/kbknapp/clap-rs/issues/740)) -* **Contributing:** updates the readme to improve the readability and contributing sections ([eb51316c](https://github.com/kbknapp/clap-rs/commit/eb51316cdfdc7258d287ba13b67ef2f42bd2b8f6)) - - -## v2.18.0 (2016-11-05) - - -#### Features - -* **Completions:** adds completion support for PowerShell. ([cff82c88](https://github.com/kbknapp/clap-rs/commit/cff82c880e21064fca63351507b80350df6caadf), closes [#729](https://github.com/kbknapp/clap-rs/issues/729)) - - - - -### v2.17.1 (2016-11-02) - - -#### Bug Fixes - -* **Low Index Multiples:** fixes a bug where using low index multiples was propagated to subcommands ([33924e88](https://github.com/kbknapp/clap-rs/commit/33924e884461983c4e6b5ea1330fecc769a4ade7), closes [#725](https://github.com/kbknapp/clap-rs/issues/725)) - - - - -## v2.17.0 (2016-11-01) - - -#### Features - -* **Positional Args:** allows specifying the second to last positional argument as multiple(true) ([1ced2a74](https://github.com/kbknapp/clap-rs/commit/1ced2a7433ea8937a1b260ea65d708f32ca7c95e), closes [#725](https://github.com/kbknapp/clap-rs/issues/725)) - - - - -### v2.16.4 (2016-10-31) - - -#### Improvements - -* **Error Output:** conflicting errors are now symetrical, meaning more consistent and less confusing ([3d37001d](https://github.com/kbknapp/clap-rs/commit/3d37001d1dc647d73cc597ff172f1072d4beb80d), closes [#718](https://github.com/kbknapp/clap-rs/issues/718)) - -#### Documentation - -* Fix typo in example `13a_enum_values_automatic` ([c22fbc07](https://github.com/kbknapp/clap-rs/commit/c22fbc07356e556ffb5d1a79ec04597d149b915e)) -* **README.md:** fixes failing yaml example (#715) ([21fba9e6](https://github.com/kbknapp/clap-rs/commit/21fba9e6cd8c163012999cd0ce271ec8780c5695)) - -#### Bug Fixes - -* **ZSH Completions:** fixes bug that caused panic on subcommands with aliases ([5c70e1a0](https://github.com/kbknapp/clap-rs/commit/5c70e1a01bc977e44c10015d18bb8e215c32dfc8), closes [#714](https://github.com/kbknapp/clap-rs/issues/714)) -* **debug:** fixes the debug feature (#716) ([6c11ccf4](https://github.com/kbknapp/clap-rs/commit/6c11ccf443d46258d51f7cda33fbcc81e7fe8e90)) - - - - -### v2.16.3 (2016-10-28) - - -#### Bug Fixes - -* Derive display order after propagation ([9cb6facf](https://github.com/kbknapp/clap-rs/commit/9cb6facf507aff7cddd124b8c29714d2b0e7bd13), closes [#706](https://github.com/kbknapp/clap-rs/issues/706)) -* **yaml-example:** inconsistent args ([847f7199](https://github.com/kbknapp/clap-rs/commit/847f7199219ead5065561d91d64780d99ae4b587)) - - - - -### v2.16.2 (2016-10-25) - - -#### Bug Fixes - -* **Fish Completions:** fixes a bug where single quotes are not escaped ([780b4a18](https://github.com/kbknapp/clap-rs/commit/780b4a18281b6f7f7071e1b9db2290fae653c406), closes [#704](https://github.com/kbknapp/clap-rs/issues/704)) - - - -### v2.16.1 (2016-10-24) - - -#### Bug Fixes - -* **Help Message:** fixes a regression bug where args with multiple(true) threw off alignment ([ebddac79](https://github.com/kbknapp/clap-rs/commit/ebddac791f3ceac193d5ad833b4b734b9643a7af), closes [#702](https://github.com/kbknapp/clap-rs/issues/702)) - - - - -## v2.16.0 (2016-10-23) - - -#### Features - -* **Completions:** adds ZSH completion support ([3e36b0ba](https://github.com/kbknapp/clap-rs/commit/3e36b0bac491d3f6194aee14604caf7be26b3d56), closes [#699](https://github.com/kbknapp/clap-rs/issues/699)) - - - - -## v2.15.0 (2016-10-21) - - -#### Features - -* **AppSettings:** adds new setting `AppSettings::AllowNegativeNumbers` ([ab064546](https://github.com/kbknapp/clap-rs/commit/ab06454677fb6aa9b9f804644fcca2168b1eaee3), closes [#696](https://github.com/kbknapp/clap-rs/issues/696)) - -#### Documentation - -* **app/settings.rs:** moves variants to roughly alphabetical order ([9ed4d4d7](https://github.com/kbknapp/clap-rs/commit/9ed4d4d7957a23357aef60081e45639ab9e3905f)) - - - -### v2.14.1 (2016-10-20) - - -#### Documentation - -* Improve documentation around features ([4ee85b95](https://github.com/kbknapp/clap-rs/commit/4ee85b95d2d16708a016a3ba4e6e2c93b89b7fad)) -* reword docs for ErrorKind and app::Settings ([3ccde7a4](https://github.com/kbknapp/clap-rs/commit/3ccde7a4b8f7a2ea8b916a5415c04a8ff4b5cb7a)) -* fix tests that fail when the "suggestions" feature is disabled ([996fc381](https://github.com/kbknapp/clap-rs/commit/996fc381763a48d125c7ea8a58fed057fd0b4ac6)) -* fix the OsString-using doc-tests ([af9e1a39](https://github.com/kbknapp/clap-rs/commit/af9e1a393ce6cdda46a03c8a4f48df222b015a24)) -* tag non-rust code blocks as such instead of ignoring them ([0ba9f4b1](https://github.com/kbknapp/clap-rs/commit/0ba9f4b123f281952581b6dec948f7e51dd22890)) -* **ErrorKind:** improve some errors about subcommands ([9f6217a4](https://github.com/kbknapp/clap-rs/commit/9f6217a424da823343d7b801b9c350dee3cd1906)) -* **yaml:** make sure the doc-tests don't fail before "missing file" ([8c0f5551](https://github.com/kbknapp/clap-rs/commit/8c0f55516f4910c78c9f8a2bdbd822729574f95b)) - -#### Improvements - -* Stabilize clap_app! ([cd516006](https://github.com/kbknapp/clap-rs/commit/cd516006e35c37b005f329338560a0a53d1f3e00)) -* **with_defaults:** Deprecate App::with_defaults() ([26085409](https://github.com/kbknapp/clap-rs/commit/2608540940c8bb66e517b65706bc7dea55510682), closes [#638](https://github.com/kbknapp/clap-rs/issues/638)) - -#### Bug Fixes - -* fixes a bug that made determining when to auto-wrap long help messages inconsistent ([468baadb](https://github.com/kbknapp/clap-rs/commit/468baadb8398fc1d37897b0c49374aef4cf97dca), closes [#688](https://github.com/kbknapp/clap-rs/issues/688)) -* **Completions:** fish completions for nested subcommands ([a61eaf8a](https://github.com/kbknapp/clap-rs/commit/a61eaf8aade76cfe90ccc0f7125751ebf60e3254)) -* **features:** Make lints not enable other nightly-requiring features ([835f75e3](https://github.com/kbknapp/clap-rs/commit/835f75e3ba20999117363ed9f916464d777f36ef)) - - - - -## v2.14.0 (2016-10-05) - - -#### Features - -* **arg_aliases:** Ability to alias arguments ([33b5f6ef](https://github.com/kbknapp/clap-rs/commit/33b5f6ef2c9612ecabb31f96b824793e46bfd3dd), closes [#669](https://github.com/kbknapp/clap-rs/issues/669)) -* **flag_aliases:** Ability to alias flags ([40d6dac9](https://github.com/kbknapp/clap-rs/commit/40d6dac973927dded6ab423481634ef47ee7bfd7)) - -#### Bug Fixes - -* **UsageParser:** Handle non-ascii names / options. ([1d6a7c6e](https://github.com/kbknapp/clap-rs/commit/1d6a7c6e7e6aadc527346aa822f19d8587f714f3), closes [#664](https://github.com/kbknapp/clap-rs/issues/664)) - -#### Documentation - -* typo ([bac417fa](https://github.com/kbknapp/clap-rs/commit/bac417fa1cea3d32308334c7cccfcf54546cd9d8)) - - - -## v2.13.0 (2016-09-18) - - -#### Documentation - -* updates README.md with new website information and updated video tutorials info ([0c19c580](https://github.com/kbknapp/clap-rs/commit/0c19c580cf50f1b82ff32f70b36708ae2bcac132)) -* updates the docs about removing implicit value_delimiter(true) ([c81bc722](https://github.com/kbknapp/clap-rs/commit/c81bc722ebb8a86d22be89b5aec98df9fe222a08)) -* **Default Values:** adds better examples on using default values ([57a8d9ab](https://github.com/kbknapp/clap-rs/commit/57a8d9abb2f973c235a8a14f8fc031673d7a7460), closes [#418](https://github.com/kbknapp/clap-rs/issues/418)) - -#### Bug Fixes - -* **Value Delimiters:** fixes the confusion around implicitly setting value delimiters. (default is now `false`) ([09d4d0a9](https://github.com/kbknapp/clap-rs/commit/09d4d0a9038d7ce2df55c2aec95e16f36189fcee), closes [#666](https://github.com/kbknapp/clap-rs/issues/666)) - - - - -### v2.12.1 (2016-09-13) - - -#### Bug Fixes - -* **Help Wrapping:** fixes a regression-bug where the old {n} newline char stopped working ([92ac353b](https://github.com/kbknapp/clap-rs/commit/92ac353b48b7caa2511ad2a046d94da93c236cf6), closes [#661](https://github.com/kbknapp/clap-rs/issues/661)) - - - - -## v2.12.0 (2016-09-13) - - -#### Features - -* **Help:** adds ability to hide the possible values on a per argument basis ([9151ef73](https://github.com/kbknapp/clap-rs/commit/9151ef739871f2e74910c342299c0de196b95dec), closes [#640](https://github.com/kbknapp/clap-rs/issues/640)) -* **help:** allow for limiting detected terminal width ([a43e28af](https://github.com/kbknapp/clap-rs/commit/a43e28af85c9a9deaedd5ef735f4f13008daab29), closes [#653](https://github.com/kbknapp/clap-rs/issues/653)) - -#### Documentation - -* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611)) -* **Value Delimiters:** updates the docs for the Arg::multiple method WRT value delimiters and default settings ([f9d17a06](https://github.com/kbknapp/clap-rs/commit/f9d17a060aa53f10d0a6e1a7eed5d989d1a59533)) -* **appsettings:** Document AppSetting::DisableVersion ([94501965](https://github.com/kbknapp/clap-rs/commit/945019654d2ca67eb2b1d6014fdf80b84d528d30), closes [#589](https://github.com/kbknapp/clap-rs/issues/589)) - -#### Bug Fixes - -* **AllowLeadingHyphen:** fixes a bug where valid args aren't recognized with this setting ([a9699e4d](https://github.com/kbknapp/clap-rs/commit/a9699e4d7cdc9a06e73b845933ff1fe6d76f016a), closes [#588](https://github.com/kbknapp/clap-rs/issues/588)) - -#### Improvements - -* **Help Wrapping:** - * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617)) - * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f)) -* **Value Delimiters:** changes the default value delimiter rules ([f9e69254](https://github.com/kbknapp/clap-rs/commit/f9e692548e8c94de15f909432de301407d6bb834), closes [#655](https://github.com/kbknapp/clap-rs/issues/655)) -* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816)) - -#### Performance - -* **help:** fix redundant contains() checks ([a8afed74](https://github.com/kbknapp/clap-rs/commit/a8afed7428bf0733f8e93bb11ad6c00d9e970fcc)) - - - - -### v2.11.3 (2016-09-07) - - -#### Documentation - -* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611)) - -#### Improvements - -* **Help Wrapping:** - * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617)) - * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f)) -* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816)) - - - - - -### v2.11.2 (2016-09-06) - -#### Improvements - -* **Help Wrapping:** makes some minor changes to when next line help is automatically used ([5658b117](https://github.com/kbknapp/clap-rs/commit/5658b117aec3e03adff9c8c52a4c4bc1fcb4e1ff)) - - - -### v2.11.1 (2016-09-05) - - -#### Bug Fixes - -* **Settings:** fixes an issue where settings weren't propogated down through grand-child subcommands ([b3efc107](https://github.com/kbknapp/clap-rs/commit/b3efc107515d78517b20798ff3890b8a2b04498e), closes [#638](https://github.com/kbknapp/clap-rs/issues/638)) - -#### Features - -* **Errors:** Errors with custom description ([58512f2f](https://github.com/kbknapp/clap-rs/commit/58512f2fcb430745f1ee6ee8f1c67f62dc216c73)) - -#### Improvements - -* **help:** use term_size instead of home-grown solution ([fc7327e9](https://github.com/kbknapp/clap-rs/commit/fc7327e9dcf4258ef2baebf0a8714d9c0622855b)) - - - - -### v2.11.0 (2016-08-28) - - -#### Bug Fixes - -* **Groups:** fixes some usage strings that contain both args in groups and ones that conflict with each other ([3d782def](https://github.com/kbknapp/clap-rs/commit/3d782def57725e2de26ca5a5bc5cc2e40ddebefb), closes [#616](https://github.com/kbknapp/clap-rs/issues/616)) - -#### Documentation - -* moves docs to docs.rs ([03209d5e](https://github.com/kbknapp/clap-rs/commit/03209d5e1300906f00bafec1869c2047a92e5071), closes [#634](https://github.com/kbknapp/clap-rs/issues/634)) - -#### Improvements - -* **Completions:** uses standard conventions for bash completion files, namely '{bin}.bash-completion' ([27f5bbfb](https://github.com/kbknapp/clap-rs/commit/27f5bbfbcc9474c2f57c2b92b1feb898ae46ee70), closes [#567](https://github.com/kbknapp/clap-rs/issues/567)) -* **Help:** automatically moves help text to the next line and wraps when term width is determined to be too small, or help text is too long ([150964c4](https://github.com/kbknapp/clap-rs/commit/150964c4e7124d54476c9d9b4b3f2406f0fd00e5), closes [#597](https://github.com/kbknapp/clap-rs/issues/597)) -* **YAML Errors:** vastly improves error messages when using YAML ([f43b7c65](https://github.com/kbknapp/clap-rs/commit/f43b7c65941c53adc0616b8646a21dc255862eb2), closes [#574](https://github.com/kbknapp/clap-rs/issues/574)) - -#### Features - -* adds App::with_defaults to automatically use crate_authors! and crate_version! macros ([5520bb01](https://github.com/kbknapp/clap-rs/commit/5520bb012c127dfd299fd55699443c744d8dcd5b), closes [#600](https://github.com/kbknapp/clap-rs/issues/600)) - - - - -### v2.10.4 (2016-08-25) - - -#### Bug Fixes - -* **Help Wrapping:** fixes a bug where help is wrapped incorrectly and causing a panic with some non-English characters ([d0b442c7](https://github.com/kbknapp/clap-rs/commit/d0b442c7beeecac9764406bc3bd171ced0b8825e), closes [#626](https://github.com/kbknapp/clap-rs/issues/626)) - - - - -### v2.10.3 (2016-08-25) - -#### Features - -* **Help:** adds new short hand way to use source formatting and ignore term width in help messages ([7dfdaf20](https://github.com/kbknapp/clap-rs/commit/7dfdaf200ebb5c431351a045b48f5e0f0d3f31db), closes [#625](https://github.com/kbknapp/clap-rs/issues/625)) - -#### Documentation - -* **Term Width:** adds details about set_term_width(0) ([00b8205d](https://github.com/kbknapp/clap-rs/commit/00b8205d22639d1b54b9c453c55c785aace52cb2)) - -#### Bug Fixes - -* **Unicode:** fixes two bugs where non-English characters were stripped or caused a panic with help wrapping ([763a5c92](https://github.com/kbknapp/clap-rs/commit/763a5c920e23efc74d190af0cb8b5dd714b2d67a), closes [#626](https://github.com/kbknapp/clap-rs/issues/626)) - - - - -### v2.10.2 (2016-08-22) - - -#### Bug Fixes - -* fixes a bug where the help is printed twice ([a643fb28](https://github.com/kbknapp/clap-rs/commit/a643fb283acd9905dc727c4579c5c9fa2ceaa7e7), closes [#623](https://github.com/kbknapp/clap-rs/issues/623)) - - - - -### v2.10.1 (2016-08-21) - - -#### Bug Fixes - -* **Help Subcommand:** fixes misleading usage string when using multi-level subcommmands ([e203515e](https://github.com/kbknapp/clap-rs/commit/e203515e3ac495b405dbba4f78fb6af148fd282e), closes [#618](https://github.com/kbknapp/clap-rs/issues/618)) - -#### Features - -* **YAML:** allows using lists or single values with arg declarations ([9ade2cd4](https://github.com/kbknapp/clap-rs/commit/9ade2cd4b268d6d7fe828319ce6a523c641b9c38), closes [#614](https://github.com/kbknapp/clap-rs/issues/614), [#613](https://github.com/kbknapp/clap-rs/issues/613)) - - - - -## v2.10.0 (2016-07-29) - - -#### Features - -* **Completions:** one can generate a basic fish completions script at compile time ([1979d2f2](https://github.com/kbknapp/clap-rs/commit/1979d2f2f3216e57d02a97e624a8a8f6cf867ed9)) - -#### Bug Fixes - -* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635)) - -#### Breaking Changes - -* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635)) - -#### Documentation - -* **YAML:** fixes example 17's incorrect reference to arg_groups instead of groups ([b6c99e13](https://github.com/kbknapp/clap-rs/commit/b6c99e1377f918e78c16c8faced70a71607da931), closes [#601](https://github.com/kbknapp/clap-rs/issues/601)) - - - - -### 2.9.3 (2016-07-24) - - -#### Bug Fixes - -* fixes bug where only first arg in list of required_unless_one is recognized ([1fc3b55b](https://github.com/kbknapp/clap-rs/commit/1fc3b55bd6c8653b02e7c4253749c6b77737d2ac), closes [#575](https://github.com/kbknapp/clap-rs/issues/575)) -* **Settings:** fixes typo subcommandsrequired->subcommandrequired ([fc72cdf5](https://github.com/kbknapp/clap-rs/commit/fc72cdf591d30f5d9375d0b5cc2a2ff3e812f9f6), closes [#593](https://github.com/kbknapp/clap-rs/issues/593)) - -#### Features - -* **Completions:** adds the ability to generate completions to io::Write object ([9f62cf73](https://github.com/kbknapp/clap-rs/commit/9f62cf7378ba5acb5ce8c5bac89b4aa60c30755f)) -* **Settings:** Add unset_setting and unset_settings fns to App (#598) ([0ceba231](https://github.com/kbknapp/clap-rs/commit/0ceba231c6767cd6d88fdb1feeeea41deadf77ff), closes [#590](https://github.com/kbknapp/clap-rs/issues/590)) - - - -### 2.9.2 (2016-07-03) - - -#### Documentation - -* **Completions:** fixes the formatting of the Cargo.toml excerpt in the completions example ([722f2607](https://github.com/kbknapp/clap-rs/commit/722f2607beaef56b6a0e433db5fd09492d9f028c)) - -#### Bug Fixes - -* **Completions:** fixes bug where --help and --version short weren't added to the completion list ([e9f2438e](https://github.com/kbknapp/clap-rs/commit/e9f2438e2ce99af0ae570a2eaf541fc7f55b771b), closes [#536](https://github.com/kbknapp/clap-rs/issues/536)) - - - - -### 2.9.1 (2016-07-02) - - -#### Improvements - -* **Completions:** allows multiple completions to be built by namespacing with bin name ([57484b2d](https://github.com/kbknapp/clap-rs/commit/57484b2daeaac01c1026e8c84efc8bf099e0eb31)) - - - -## v2.9.0 (2016-07-01) - - -#### Documentation - -* **Completions:** - * fixes some errors in the completion docs ([9b359bf0](https://github.com/kbknapp/clap-rs/commit/9b359bf06255d3dad8f489308044b60a9d1e6a87)) - * adds documentation for completion scripts ([c6c519e4](https://github.com/kbknapp/clap-rs/commit/c6c519e40efd6c4533a9ef5efe8e74fd150391b7)) - -#### Features - -* **Completions:** - * one can now generate a bash completions script at compile time! ([e75b6c7b](https://github.com/kbknapp/clap-rs/commit/e75b6c7b75f729afb9eb1d2a2faf61dca7674634), closes [#376](https://github.com/kbknapp/clap-rs/issues/376)) - * completions now include aliases to subcommands, including all subcommand options ([0ab9f840](https://github.com/kbknapp/clap-rs/commit/0ab9f84052a8cf65b5551657f46c0c270841e634), closes [#556](https://github.com/kbknapp/clap-rs/issues/556)) - * completions now continue completing even after first completion ([18fc2e5b](https://github.com/kbknapp/clap-rs/commit/18fc2e5b5af63bf54a94b72cec5e1223d49f4806)) - * allows matching on possible values in options ([89cc2026](https://github.com/kbknapp/clap-rs/commit/89cc2026ba9ac69cf44c5254360bbf99236d4f89), closes [#557](https://github.com/kbknapp/clap-rs/issues/557)) - -#### Bug Fixes - -* **AllowLeadingHyphen:** fixes an issue where isn't ignored like it should be with this setting ([96c24c9a](https://github.com/kbknapp/clap-rs/commit/96c24c9a8fa1f85e06138d3cdd133e51659e19d2), closes [#558](https://github.com/kbknapp/clap-rs/issues/558)) - - -## v2.8.0 (2016-06-30) - - -#### Features - -* **Arg:** adds new setting `Arg::require_delimiter` which requires val delimiter to parse multiple values ([920b5595](https://github.com/kbknapp/clap-rs/commit/920b5595ed72abfb501ce054ab536067d8df2a66)) - -#### Bug Fixes - -* Declare term::Winsize as repr(C) ([5d663d90](https://github.com/kbknapp/clap-rs/commit/5d663d905c9829ce6e7a164f1f0896cdd70236dd)) - -#### Documentation - -* **Arg:** adds docs for ([49af4e38](https://github.com/kbknapp/clap-rs/commit/49af4e38a5dae2ab0a7fc3b4147e2c053d532484)) - - - - -### v2.7.1 (2016-06-29) - - -#### Bug Fixes - -* **Options:** - * options with multiple values and using delimiters no longer parse additional values after a trailing space ([cdc500bd](https://github.com/kbknapp/clap-rs/commit/cdc500bdde6abe238c36ade406ddafc2bafff583)) - * using options with multiple values and with an = no longer parse args after the trailing space as values ([290f61d0](https://github.com/kbknapp/clap-rs/commit/290f61d07177413cf082ada55526d83405f6d011)) - - - - -## v2.7.0 (2016-06-28) - - -#### Documentation - -* fix typos ([43b3d40b](https://github.com/kbknapp/clap-rs/commit/43b3d40b8c38b1571da75af86b5088be96cccec2)) -* **ArgGroup:** vastly improves ArgGroup docs by adding better examples ([9e5f4f5d](https://github.com/kbknapp/clap-rs/commit/9e5f4f5d734d630bca5535c3a0aa4fd4f9db3e39), closes [#534](https://github.com/kbknapp/clap-rs/issues/534)) - -#### Features - -* **ArgGroup:** one can now specify groups which require AT LEAST one of the args ([33689acc](https://github.com/kbknapp/clap-rs/commit/33689acc689b217a8c0ee439f1b1225590c38355), closes [#533](https://github.com/kbknapp/clap-rs/issues/533)) - -#### Bug Fixes - -* **App:** using `App::print_help` now prints the same as would have been printed by `--help` or the like ([e84cc018](https://github.com/kbknapp/clap-rs/commit/e84cc01836bbe0527e97de6db9889bd9e0fd6ba1), closes [#536](https://github.com/kbknapp/clap-rs/issues/536)) -* **Help:** - * prevents invoking help help and displaying incorrect help message ([e3d2893f](https://github.com/kbknapp/clap-rs/commit/e3d2893f377942a2d4cf3c6ff04524d0346e6fdb), closes [#538](https://github.com/kbknapp/clap-rs/issues/538)) - * subcommand help messages requested via help now correctly match --help ([08ad1cff](https://github.com/kbknapp/clap-rs/commit/08ad1cff4fec57224ea957a2891a057b323c01bc), closes [#539](https://github.com/kbknapp/clap-rs/issues/539)) - -#### Improvements - -* **ArgGroup:** Add multiple ArgGroups per Arg ([902e182f](https://github.com/kbknapp/clap-rs/commit/902e182f7a58aff11ff01e0a452abcdbdb2262aa), closes [#426](https://github.com/kbknapp/clap-rs/issues/426)) -* **Usage Strings:** `[FLAGS]` and `[ARGS]` are no longer blindly added to usage strings ([9b2e45b1](https://github.com/kbknapp/clap-rs/commit/9b2e45b170aff567b038d8b3368880b6046c10c6), closes [#537](https://github.com/kbknapp/clap-rs/issues/537)) -* **arg_enum!:** allows using meta items like repr(C) with arg_enum!s ([edf9b233](https://github.com/kbknapp/clap-rs/commit/edf9b2331c17a2cbcc13f961add4c55c2778e773), closes [#543](https://github.com/kbknapp/clap-rs/issues/543)) - - - - -## v2.6.0 (2016-06-14) - - -#### Improvements - -* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115)) -* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724)) -* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589)) -* **Aliases:** improves readability of asliases in help messages ([ca511de7](https://github.com/kbknapp/clap-rs/commit/ca511de71f5b8c2ac419f1b188658e8c63b67846), closes [#526](https://github.com/kbknapp/clap-rs/issues/526), [#529](https://github.com/kbknapp/clap-rs/issues/529)) -* **Usage Strings:** improves the default usage string when only a single positional arg is present ([ec86f2da](https://github.com/kbknapp/clap-rs/commit/ec86f2dada1545a63fc72355e22fcdc4c466c215), closes [#518](https://github.com/kbknapp/clap-rs/issues/518)) - -#### Features - -* **Help:** allows wrapping at specified term width (Even on Windows!) ([1761dc0d](https://github.com/kbknapp/clap-rs/commit/1761dc0d27d0d621229d792be40c36fbf65c3014), closes [#451](https://github.com/kbknapp/clap-rs/issues/451)) -* **Settings:** - * adds new setting to stop delimiting values with -- or TrailingVarArg ([fc3e0f5a](https://github.com/kbknapp/clap-rs/commit/fc3e0f5afda6d24cdb3c4676614beebe13e1e870), closes [#511](https://github.com/kbknapp/clap-rs/issues/511)) - * one can now set an AppSetting which is propogated down through child subcommands ([e2341835](https://github.com/kbknapp/clap-rs/commit/e23418351a3b98bf08dfd7744bc14377c70d59ee), closes [#519](https://github.com/kbknapp/clap-rs/issues/519)) -* **Subcommands:** adds support for visible aliases ([7b10e7f8](https://github.com/kbknapp/clap-rs/commit/7b10e7f8937a07fdb8d16a6d8df79ce78d080cd3), closes [#522](https://github.com/kbknapp/clap-rs/issues/522)) - -#### Bug Fixes - -* fixes bug where args are printed out of order with templates ([05abb534](https://github.com/kbknapp/clap-rs/commit/05abb534864764102031a0d402e64ac65867aa87)) -* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514)) -* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106)) -* **Help:** `App::before_help` and `App::after_help` now correctly wrap ([1f4da767](https://github.com/kbknapp/clap-rs/commit/1f4da7676e6e71aa8dda799f3eeefad105a47819), closes [#516](https://github.com/kbknapp/clap-rs/issues/516)) -* **Settings:** fixes bug where new color settings couldn't be converted from strs ([706a7c11](https://github.com/kbknapp/clap-rs/commit/706a7c11b0900be594de6d5a3121938eff197602)) -* **Subcommands:** subcommands with aliases now display help of the aliased subcommand ([5354d14b](https://github.com/kbknapp/clap-rs/commit/5354d14b51f189885ba110e01e6b76cca3752992), closes [#521](https://github.com/kbknapp/clap-rs/issues/521)) -* **Windows:** fixes a failing windows build ([01e7dfd6](https://github.com/kbknapp/clap-rs/commit/01e7dfd6c07228c0be6695b3c7bf9370d82860d4)) -* **YAML:** adds missing YAML methods for App and Arg ([e468faf3](https://github.com/kbknapp/clap-rs/commit/e468faf3f05950fd9f72d84b69aa2061e91c6c64), closes [#528](https://github.com/kbknapp/clap-rs/issues/528)) - - - - -### v2.5.2 (2016-05-31) - - -#### Improvements - -* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115)) -* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724)) -* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589)) - -#### Bug Fixes - -* fixes bug where args are printed out of order with templates ([3935431d](https://github.com/kbknapp/clap-rs/commit/3935431d5633f577c0826ae2142794b301f4b8ca)) -* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514)) -* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106)) - -#### Documentation - -* inter-links all types and pages ([3312893d](https://github.com/kbknapp/clap-rs/commit/3312893ddaef3f44d68d8d26ed3d08010be50d97), closes [#505](https://github.com/kbknapp/clap-rs/issues/505)) -* makes all publicly available types viewable in docs ([52ca6505](https://github.com/kbknapp/clap-rs/commit/52ca6505b4fec7b5c2d53d160c072d395eb21da6)) - - -### v2.5.1 (2016-05-11) - - -#### Bug Fixes - -* **Subcommand Aliases**: fixes lifetime issue when setting multiple aliases at once ([ac42f6cf0](https://github.com/kbknapp/clap-rs/commit/ac42f6cf0de6c4920f703807d63061803930b18d)) - - -## v2.5.0 (2016-05-10) - - -#### Improvements - -* **SubCommand Aliases:** adds feature to yaml configs too ([69592195](https://github.com/kbknapp/clap-rs/commit/695921954dde46dfd483399dcdef482c9dd7f34a)) - -#### Features - -* **SubCommands:** adds support for subcommand aliases ([66b4dea6](https://github.com/kbknapp/clap-rs/commit/66b4dea65c44d8f77ff522238a9237aed1bcab6d), closes [#469](https://github.com/kbknapp/clap-rs/issues/469)) - - - -### v2.4.3 (2016-05-10) - - -#### Bug Fixes - -* **Usage Strings:** - * now properly dedups args that are also in groups ([3ca0947c](https://github.com/kbknapp/clap-rs/commit/3ca0947c166b4f8525752255e3a4fa6565eb9689), closes [#498](https://github.com/kbknapp/clap-rs/issues/498)) - * removes duplicate groups from usage strings ([f574fb8a](https://github.com/kbknapp/clap-rs/commit/f574fb8a7cde4d4a2fa4c4481d59be2d0f135427)) - -#### Improvements - -* **Groups:** formats positional args in groups in a better way ([fef11154](https://github.com/kbknapp/clap-rs/commit/fef11154fb7430d1cbf04a672aabb366e456a368)) -* **Help:** - * moves positionals to standard <> formatting ([03dfe5ce](https://github.com/kbknapp/clap-rs/commit/03dfe5ceff1d63f172788ff688567ddad9fe119b)) - * default help subcommand string has been shortened ([5b7fe8e4](https://github.com/kbknapp/clap-rs/commit/5b7fe8e4161e43ab19e2e5fcf55fbe46791134e9), closes [#494](https://github.com/kbknapp/clap-rs/issues/494)) - - -### v2.4.3 (2016-05-10) - -* Ghost Release - - -### v2.4.3 (2016-05-10) - -* Ghost Release - - -## v2.4.0 (2016-05-02) - - -#### Features - -* **Help:** adds support for displaying info before help message ([29fbfa3b](https://github.com/kbknapp/clap-rs/commit/29fbfa3b963f2f3ca7704bf5d3e1201531baa373)) -* **Required:** adds allowing args that are required unless certain args are present ([af1f7916](https://github.com/kbknapp/clap-rs/commit/af1f79168390ea7da4074d0d9777de458ea64971)) - -#### Documentation - -* hides formatting from docs ([cb708093](https://github.com/kbknapp/clap-rs/commit/cb708093a7cd057f08c98b7bd1ed54c2db86ae7e)) -* **required_unless:** adds docs and examples for required_unless ([ca727b52](https://github.com/kbknapp/clap-rs/commit/ca727b52423b9883acd88b2f227b2711bc144573)) - -#### Bug Fixes - -* **Required Args:** fixes issue where missing required args are sometimes duplicatd in error messages ([3beebd81](https://github.com/kbknapp/clap-rs/commit/3beebd81e7bc2faa4115ac109cf570e512c5477f), closes [#492](https://github.com/kbknapp/clap-rs/issues/492)) - - - -## v2.3.0 (2016-04-18) - - -#### Improvements - -* **macros.rs:** Added write_nspaces macro (a new version of write_spaces) ([9d757e86](https://github.com/kbknapp/clap-rs/commit/9d757e8678e334e5a740ac750c76a9ed4e785cba)) -* **parser.rs:** - * Provide a way to create a usage string without the USAGE: title ([a91d378b](https://github.com/kbknapp/clap-rs/commit/a91d378ba0c91b5796457f8c6e881b13226ab735)) - * Make Parser's create_usage public allowing to have function outside the parser to generate the help ([d51945f8](https://github.com/kbknapp/clap-rs/commit/d51945f8b82ebb0963f4f40b384a9e8335783091)) - * Expose Parser's flags, opts and positionals argument as iterators ([9b23e7ee](https://github.com/kbknapp/clap-rs/commit/9b23e7ee40e51f7a823644c4496be955dc6c9d3a)) -* **src/args:** Exposes argument display order by introducing a new Trait ([1321630e](https://github.com/kbknapp/clap-rs/commit/1321630ef56955f152c73376d4d85cceb0bb4a12)) -* **srs/args:** Added longest_filter to AnyArg trait ([65b3f667](https://github.com/kbknapp/clap-rs/commit/65b3f667532685f854c699ddd264d326599cf7e5)) - -#### Features - -* **Authors Macro:** adds a crate_authors macro ([38fb59ab](https://github.com/kbknapp/clap-rs/commit/38fb59abf480eb2b6feca269097412f8b00b5b54), closes [#447](https://github.com/kbknapp/clap-rs/issues/447)) -* **HELP:** - * implements optional colored help messages ([abc8f669](https://github.com/kbknapp/clap-rs/commit/abc8f669c3c8193ffc3a3b0ac6c3ac2198794d4f), closes [#483](https://github.com/kbknapp/clap-rs/issues/483)) - * Add a Templated Help system. ([81e121ed](https://github.com/kbknapp/clap-rs/commit/81e121edd616f7285593f11120c63bcccae0d23e)) - -#### Bug Fixes - -* **HELP:** Adjust Help to semantic changes introduced in 6933b84 ([8d23806b](https://github.com/kbknapp/clap-rs/commit/8d23806bd67530ad412c34a1dcdcb1435555573d)) - - -### v2.2.6 (2016-04-11) - -#### Bug Fixes - -* **Arg Groups**: fixes bug where arg name isn't printed properly ([3019a685](https://github.com/kbknapp/clap-rs/commit/3019a685eee747ccbe6be09ad5dddce0b1d1d4db), closes [#476](https://github.com/kbknapp/clap-rs/issues/476)) - - - -### v2.2.5 (2016-04-03) - - -#### Bug Fixes - -* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470)) -* **Help Message:** fixes bug where arg name is printed twice ([71acf1d5](https://github.com/kbknapp/clap-rs/commit/71acf1d576946658b8bbdb5ae79e6716c43a030f), closes [#472](https://github.com/kbknapp/clap-rs/issues/472)) - - - -### v2.2.4 (2016-03-30) - - -#### Bug Fixes - -* fixes compiling with debug cargo feature ([d4b55450](https://github.com/kbknapp/clap-rs/commit/d4b554509928031ac0808076178075bb21f8c1da)) -* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470)) - - - - -### v2.2.3 (2016-03-28) - - -#### Bug Fixes - -* **Help Subcommand:** fixes issue where help and version flags weren't properly displayed ([205b07bf](https://github.com/kbknapp/clap-rs/commit/205b07bf2e6547851f1290f8cd6b169145e144f1), closes [#466](https://github.com/kbknapp/clap-rs/issues/466)) - - -### v2.2.2 (2016-03-27) - - -#### Bug Fixes - -* **Help Message:** fixes bug with wrapping in the middle of a unicode sequence ([05365ddc](https://github.com/kbknapp/clap-rs/commit/05365ddcc252e4b49e7a75e199d6001a430bd84d), closes [#456](https://github.com/kbknapp/clap-rs/issues/456)) -* **Usage Strings:** fixes small bug where -- would appear needlessly in usage strings ([6933b849](https://github.com/kbknapp/clap-rs/commit/6933b8491c2a7e28cdb61b47dcf10caf33c2f78a), closes [#461](https://github.com/kbknapp/clap-rs/issues/461)) - - - -### 2.2.1 (2016-03-16) - - -#### Features - -* **Help Message:** wraps and aligns the help message of subcommands ([813d75d0](https://github.com/kbknapp/clap-rs/commit/813d75d06fbf077c65762608c0fa5e941cfc393c), closes [#452](https://github.com/kbknapp/clap-rs/issues/452)) - -#### Bug Fixes - -* **Help Message:** fixes a bug where small terminal sizes causing a loop ([1d73b035](https://github.com/kbknapp/clap-rs/commit/1d73b0355236923aeaf6799abc759762ded7e1d0), closes [#453](https://github.com/kbknapp/clap-rs/issues/453)) - - - -## v2.2.0 (2016-03-15) - - -#### Features - -* **Help Message:** can auto wrap and aligning help text to term width ([e36af026](https://github.com/kbknapp/clap-rs/commit/e36af0266635f23e85e951b9088d561e9a5d1bf6), closes [#428](https://github.com/kbknapp/clap-rs/issues/428)) -* **Help Subcommand:** adds support passing additional subcommands to help subcommand ([2c12757b](https://github.com/kbknapp/clap-rs/commit/2c12757bbdf34ce481f3446c074e24c09c2e60fd), closes [#416](https://github.com/kbknapp/clap-rs/issues/416)) -* **Opts and Flags:** adds support for custom ordering in help messages ([9803b51e](https://github.com/kbknapp/clap-rs/commit/9803b51e799904c0befaac457418ee766ccc1ab9)) -* **Settings:** adds support for automatically deriving custom display order of args ([ad86e433](https://github.com/kbknapp/clap-rs/commit/ad86e43334c4f70e86909689a088fb87e26ff95a), closes [#444](https://github.com/kbknapp/clap-rs/issues/444)) -* **Subcommands:** adds support for custom ordering in help messages ([7d2a2ed4](https://github.com/kbknapp/clap-rs/commit/7d2a2ed413f5517d45988eef0765cdcd663b6372), closes [#442](https://github.com/kbknapp/clap-rs/issues/442)) - -#### Bug Fixes - -* **From Usage:** fixes a bug where adding empty lines werent ignored ([c5c58c86](https://github.com/kbknapp/clap-rs/commit/c5c58c86b9c503d8de19da356a5a5cffb59fbe84)) - -#### Documentation - -* **Groups:** explains required ArgGroups better ([4ff0205b](https://github.com/kbknapp/clap-rs/commit/4ff0205b85a45151b59bbaf090a89df13438380f), closes [#439](https://github.com/kbknapp/clap-rs/issues/439)) - - -### v2.1.2 (2016-02-24) - -#### Bug Fixes - -* **Nightly:** fixes failing nightly build ([d752c170](https://github.com/kbknapp/clap-rs/commit/d752c17029598b19037710f204b7943f0830ae75), closes [#434](https://github.com/kbknapp/clap-rs/issues/434)) - - - -### v2.1.1 (2016-02-19) - - -#### Documentation - -* **AppSettings:** clarifies that AppSettings do not propagate ([3c8db0e9](https://github.com/kbknapp/clap-rs/commit/3c8db0e9be1d24edaad364359513cbb02abb4186), closes [#429](https://github.com/kbknapp/clap-rs/issues/429)) -* **Arg Examples:** adds better examples ([1e79cccc](https://github.com/kbknapp/clap-rs/commit/1e79cccc12937bc0e7cd2aad8e404410798e9fff)) - -#### Improvements - -* **Help:** adds setting for next line help by arg ([066df748](https://github.com/kbknapp/clap-rs/commit/066df7486e684cf50a8479a356a12ba972c34ce1), closes [#427](https://github.com/kbknapp/clap-rs/issues/427)) - - - -## v2.1.0 (2016-02-10) - - -#### Features - -* **Defult Values:** adds support for default values in args ([73211952](https://github.com/kbknapp/clap-rs/commit/73211952964a79d97b434dd567e6d7d34be7feb5), closes [#418](https://github.com/kbknapp/clap-rs/issues/418)) - -#### Documentation - -* **Default Values:** adds better examples and notes for default values ([9facd74f](https://github.com/kbknapp/clap-rs/commit/9facd74f843ef3807c5d35259558a344e6c25905)) - - - -### v2.0.6 (2016-02-09) - - -#### Improvements - -* **Positional Arguments:** now displays value name if appropriate ([f0a99916](https://github.com/kbknapp/clap-rs/commit/f0a99916c59ce675515c6dcdfe9a40b130510908), closes [#420](https://github.com/kbknapp/clap-rs/issues/420)) - - - -### v2.0.5 (2016-02-05) - - -#### Bug Fixes - -* **Multiple Values:** fixes bug where number_of_values wasnt respected ([72c387da](https://github.com/kbknapp/clap-rs/commit/72c387da0bb8a6f526f863770f08bb8ca0d3de03)) - - - -### v2.0.4 (2016-02-04) - - -#### Bug Fixes - -* adds support for building ArgGroups from standalone YAML ([fcbc7e12](https://github.com/kbknapp/clap-rs/commit/fcbc7e12f5d7b023b8f30cba8cad28a01cf6cd26)) -* Stop lonely hyphens from causing panic ([85b11468](https://github.com/kbknapp/clap-rs/commit/85b11468b0189d5cc15f1cfac5db40d17a0077dc), closes [#410](https://github.com/kbknapp/clap-rs/issues/410)) -* **AppSettings:** fixes bug where subcmds didn't receive parent ver ([a62e4527](https://github.com/kbknapp/clap-rs/commit/a62e452754b3b0e3ac9a15aa8b5330636229ead1)) - - -### v2.0.3 (2016-02-02) - - -#### Improvements - -* **values:** adds support for up to u64::max values per arg ([c7abf7d7](https://github.com/kbknapp/clap-rs/commit/c7abf7d7611e317b0d31d97632e3d2e13570947c)) -* **occurrences:** Allow for more than 256 occurrences of an argument. ([3731ddb3](https://github.com/kbknapp/clap-rs/commit/3731ddb361163f3d6b86844362871e48c80fa530)) - -#### Features - -* **AppSettings:** adds HidePossibleValuesInHelp to skip writing those values ([cdee7a0e](https://github.com/kbknapp/clap-rs/commit/cdee7a0eb2beeec723cb98acfacf03bf629c1da3)) - -#### Bug Fixes - -* **value_t_or_exit:** fixes typo which causes value_t_or_exit to return a Result ([ee96baff](https://github.com/kbknapp/clap-rs/commit/ee96baffd306cb8d20ddc5575cf739bb1a6354e8)) - - - -### v2.0.2 (2016-01-31) - - -#### Improvements - -* **arg_enum:** enum declared with arg_enum returns [&'static str; #] instead of Vec ([9c4b8a1a](https://github.com/kbknapp/clap-rs/commit/9c4b8a1a6b12949222f17d1074578ad7676b9c0d)) - -#### Bug Fixes - -* clap_app! should be gated by unstable, not nightly feature ([0c8b84af](https://github.com/kbknapp/clap-rs/commit/0c8b84af6161d5baf683688eafc00874846f83fa)) -* **SubCommands:** fixed where subcmds weren't recognized after mult args ([c19c17a8](https://github.com/kbknapp/clap-rs/commit/c19c17a8850602990e24347aeb4427cf43316223), closes [#405](https://github.com/kbknapp/clap-rs/issues/405)) -* **Usage Parser:** fixes a bug where literal single quotes weren't allowed in help strings ([0bcc7120](https://github.com/kbknapp/clap-rs/commit/0bcc71206478074769e311479b34a9f74fe80f5c), closes [#406](https://github.com/kbknapp/clap-rs/issues/406)) - - - -### v2.0.1 (2016-01-30) - - -#### Bug Fixes - -* fixes cargo features to NOT require nightly with unstable features ([dcbcc60c](https://github.com/kbknapp/clap-rs/commit/dcbcc60c9ba17894be636472ea4b07a82d86a9db), closes [#402](https://github.com/kbknapp/clap-rs/issues/402)) - - - -## v2.0.0 (2016-01-28) - - -#### Improvements - -* **From Usage:** vastly improves the usage parser ([fa3a2f86](https://github.com/kbknapp/clap-rs/commit/fa3a2f86bd674c5eb07128c95098fab7d1437247), closes [#350](https://github.com/kbknapp/clap-rs/issues/350)) - -#### Features - -* adds support for external subcommands ([177fe5cc](https://github.com/kbknapp/clap-rs/commit/177fe5cce745c2164a8e38c23be4c4460d2d7211), closes [#372](https://github.com/kbknapp/clap-rs/issues/372)) -* adds support values with a leading hyphen ([e4d429b9](https://github.com/kbknapp/clap-rs/commit/e4d429b9d52e95197bd0b572d59efacecf305a59), closes [#385](https://github.com/kbknapp/clap-rs/issues/385)) -* adds support for turning off the value delimiter ([508db850](https://github.com/kbknapp/clap-rs/commit/508db850a87c2e251cf6b6ddead9ad56b29f9e57), closes [#352](https://github.com/kbknapp/clap-rs/issues/352)) -* adds support changing the value delimiter ([dafeae8a](https://github.com/kbknapp/clap-rs/commit/dafeae8a526162640f6a68da434370c64d190889), closes [#353](https://github.com/kbknapp/clap-rs/issues/353)) -* adds support for comma separated values ([e69da6af](https://github.com/kbknapp/clap-rs/commit/e69da6afcd2fe48a3c458ca031db40997f860eda), closes [#348](https://github.com/kbknapp/clap-rs/issues/348)) -* adds support with options with optional values ([4555736c](https://github.com/kbknapp/clap-rs/commit/4555736cad01441dcde4ea84a285227e0844c16e), closes [#367](https://github.com/kbknapp/clap-rs/issues/367)) -* **UTF-8:** adds support for invalid utf8 in values ([c5c59dec](https://github.com/kbknapp/clap-rs/commit/c5c59dec0bc33b86b2e99d30741336f17ec84282), closes [#269](https://github.com/kbknapp/clap-rs/issues/269)) -* **v2:** implementing the base of 2.x ([a3536054](https://github.com/kbknapp/clap-rs/commit/a3536054512ba833533dc56615ce3663d884381c)) - -#### Bug Fixes - -* fixes nightly build with new lints ([17599195](https://github.com/kbknapp/clap-rs/commit/175991956c37dc83ba9c49396e927a1cb65c5b11)) -* fixes Windows build for 2x release ([674c9b48](https://github.com/kbknapp/clap-rs/commit/674c9b48c7c92079cb180cc650a9e39f34781c32), closes [#392](https://github.com/kbknapp/clap-rs/issues/392)) -* fixes yaml build for 2x base ([adceae64](https://github.com/kbknapp/clap-rs/commit/adceae64c8556d00ab715677377b216f9f468ad7)) - -#### Documentation - -* updates examples for 2x release ([1303b360](https://github.com/kbknapp/clap-rs/commit/1303b3607468f362ab1b452d5614c1a064dc69b4), closes [#394](https://github.com/kbknapp/clap-rs/issues/394)) -* updates examples for 2x release ([0a011f31](https://github.com/kbknapp/clap-rs/commit/0a011f3142aec338d388a6c8bfe22fa7036021bb), closes [#394](https://github.com/kbknapp/clap-rs/issues/394)) -* updates documentation for v2 release ([8d51724e](https://github.com/kbknapp/clap-rs/commit/8d51724ef73dfde5bb94fb9466bc5463a1cc1502)) -* updating docs for 2x release ([576d0e0e](https://github.com/kbknapp/clap-rs/commit/576d0e0e2c7b8f386589179bbf7419b93abacf1c)) -* **README.md:** - * updates readme for v2 release ([acaba01a](https://github.com/kbknapp/clap-rs/commit/acaba01a353c12144b9cd9a3ce447400691849b0), closes [#393](https://github.com/kbknapp/clap-rs/issues/393)) - * fix typo and make documentation conspicuous ([07b9f614](https://github.com/kbknapp/clap-rs/commit/07b9f61495d927f69f7abe6c0d85253f0f4e6107)) - -#### BREAKING CHANGES - -* **Fewer liftimes! Yay!** - * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>` - * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>` - * `ArgMatches<'a, 'b>` => `ArgMatches<'a>` -* **Simply Renamed** - * `App::arg_group` => `App::group` - * `App::arg_groups` => `App::groups` - * `ArgGroup::add` => `ArgGroup::arg` - * `ArgGroup::add_all` => `ArgGroup::args` - * `ClapError` => `Error` - * struct field `ClapError::error_type` => `Error::kind` - * `ClapResult` => `Result` - * `ClapErrorType` => `ErrorKind` -* **Removed Deprecated Functions and Methods** - * `App::subcommands_negate_reqs` - * `App::subcommand_required` - * `App::arg_required_else_help` - * `App::global_version(bool)` - * `App::versionless_subcommands` - * `App::unified_help_messages` - * `App::wait_on_error` - * `App::subcommand_required_else_help` - * `SubCommand::new` - * `App::error_on_no_subcommand` - * `Arg::new` - * `Arg::mutually_excludes` - * `Arg::mutually_excludes_all` - * `Arg::mutually_overrides_with` - * `simple_enum!` -* **Renamed Error Variants** - * `InvalidUnicode` => `InvalidUtf8` - * `InvalidArgument` => `UnknownArgument` -* **Usage Parser** - * Value names can now be specified inline, i.e. `-o, --option 'some option which takes two files'` - * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code** -* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code) -* `crate_version!` returns `&'static str` instead of `String` -* Using the `clap_app!` macro requires compiling with the `unstable` feature because the syntax could change slightly in the future - - - -### v1.5.5 (2016-01-04) - - -#### Bug Fixes - -* fixes an issue where invalid short args didn't cause an error ([c9bf7e44](https://github.com/kbknapp/clap-rs/commit/c9bf7e4440bd2f9b524ea955311d433c40a7d1e0)) -* prints the name in version and help instead of binary name ([8f3817f6](https://github.com/kbknapp/clap-rs/commit/8f3817f665c0cab6726bc16c56a53b6a61e44448), closes [#368](https://github.com/kbknapp/clap-rs/issues/368)) -* fixes an intentional panic issue discovered via clippy ([ea83a3d4](https://github.com/kbknapp/clap-rs/commit/ea83a3d421ea8856d4cac763942834d108b71406)) - - - -### v1.5.4 (2015-12-18) - - -#### Examples - -* **17_yaml:** conditinonally compile 17_yaml example ([575de089](https://github.com/kbknapp/clap-rs/commit/575de089a3e240c398cb10e6cf5a5c6b68662c01)) - -#### Improvements - -* clippy improvements ([99cdebc2](https://github.com/kbknapp/clap-rs/commit/99cdebc23da3a45a165f14b27bebeb2ed828a2ce)) - -#### Bug Fixes - - -* **errors:** return correct error type in WrongNumValues error builder ([5ba8ba9d](https://github.com/kbknapp/clap-rs/commit/5ba8ba9dcccdfa74dd1c44260e64b359bbb36be6)) -* ArgRequiredElseHelp setting now takes precedence over missing required args ([faad83fb](https://github.com/kbknapp/clap-rs/commit/faad83fbef6752f3093b6e98fca09a9449b830f4), closes [#362](https://github.com/kbknapp/clap-rs/issues/362)) - - - -### v1.5.3 (2015-11-20) - - -#### Bug Fixes - -* **Errors:** fixes some instances when errors are missing a final newline ([c4d2b171](https://github.com/kbknapp/clap-rs/commit/c4d2b1711994479ad64ee52b6b49d2ceccbf2118)) - - - - - -### v1.5.2 (2015-11-14) - - -#### Bug Fixes - -* **Errors:** fixes a compiling bug when built on Windows or without the color feature ([a35f7634](https://github.com/kbknapp/clap-rs/commit/a35f76346fe6ecc88dda6a1eb13627186e7ce185)) - - - - -### v1.5.1 (2015-11-13) - - -#### Bug Fixes - -* **Required Args:** fixes a bug where required args are not correctly accounted for ([f03b88a9](https://github.com/kbknapp/clap-rs/commit/f03b88a9766b331a63879bcd747687f2e5a2661b), closes [#343](https://github.com/kbknapp/clap-rs/issues/343)) - - - - -## v1.5.0 (2015-11-13) - - -#### Bug Fixes - -* fixes a bug with required positional args in usage strings ([c6858f78](https://github.com/kbknapp/clap-rs/commit/c6858f78755f8e860204323c828c8355a066dc83)) - -#### Documentation - -* **FAQ:** updates readme with slight changes to FAQ ([a4ef0fab](https://github.com/kbknapp/clap-rs/commit/a4ef0fab73c8dc68f1b138965d1340459c113398)) - -#### Improvements - -* massive errors overhaul ([cdc29175](https://github.com/kbknapp/clap-rs/commit/cdc29175bc9c53e5b4aec86cbc04c1743154dae6)) -* **ArgMatcher:** huge refactor and deduplication of code ([8988853f](https://github.com/kbknapp/clap-rs/commit/8988853fb8825e8f841fde349834cc12cdbad081)) -* **Errors:** errors have been vastly improved ([e59bc0c1](https://github.com/kbknapp/clap-rs/commit/e59bc0c16046db156a88ba71a037db05028e995c)) -* **Traits:** refactoring some configuration into traits ([5800cdec](https://github.com/kbknapp/clap-rs/commit/5800cdec6dce3def4242b9f7bd136308afb19685)) - -#### Performance - -* **App:** - * more BTreeMap->Vec, Opts and SubCmds ([bc4495b3](https://github.com/kbknapp/clap-rs/commit/bc4495b32ec752b6c4b29719e831c043ef2a26ce)) - * changes flags BTreeMap->Vec ([d357640f](https://github.com/kbknapp/clap-rs/commit/d357640fab55e5964fe83efc3c771e53aa3222fd)) - * removed unneeded BTreeMap ([78971fd6](https://github.com/kbknapp/clap-rs/commit/78971fd68d7dc5c8e6811b4520cdc54e4188f733)) - * changes BTreeMap to VecMap in some instances ([64b921d0](https://github.com/kbknapp/clap-rs/commit/64b921d087fdd03775c95ba0bcf65d3f5d36f812)) - * removed excess clones ([ec0089d4](https://github.com/kbknapp/clap-rs/commit/ec0089d42ed715d293fb668d3a90b0db0aa3ec39)) - - - - -### v1.4.7 (2015-11-03) - - -#### Documentation - -* Clarify behavior of Arg::multiple with options. ([434f497a](https://github.com/kbknapp/clap-rs/commit/434f497ab6d831f8145cf09278c97ca6ee6c6fe7)) -* Fix typos and improve grammar. ([c1f66b5d](https://github.com/kbknapp/clap-rs/commit/c1f66b5de7b5269fbf8760a005ef8c645edd3229)) - -#### Bug Fixes - -* **Error Status:** fixes bug where --help and --version return non-zero exit code ([89b51fdf](https://github.com/kbknapp/clap-rs/commit/89b51fdf8b1ab67607567344e2317ff1a757cb12)) - - - - -### v1.4.6 (2015-10-29) - - -#### Features - -* allows parsing without a binary name for daemons and interactive CLIs ([aff89d57](https://github.com/kbknapp/clap-rs/commit/aff89d579b5b85c3dc81b64f16d5865299ec39a2), closes [#318](https://github.com/kbknapp/clap-rs/issues/318)) - -#### Bug Fixes - -* **Errors:** tones down quoting in some error messages ([34ce59ed](https://github.com/kbknapp/clap-rs/commit/34ce59ede53bfa2eef722c74881cdba7419fd9c7), closes [#309](https://github.com/kbknapp/clap-rs/issues/309)) -* **Help and Version:** only builds help and version once ([e3be87cf](https://github.com/kbknapp/clap-rs/commit/e3be87cfc095fc41c9811adcdc6d2b079f237d5e)) -* **Option Args:** fixes bug with args and multiple values ([c9a9548a](https://github.com/kbknapp/clap-rs/commit/c9a9548a8f96cef8a3dd9a980948325fbbc1b91b), closes [#323](https://github.com/kbknapp/clap-rs/issues/323)) -* **POSIX Overrides:** fixes bug where required args are overridden ([40ed2b50](https://github.com/kbknapp/clap-rs/commit/40ed2b50c3a9fe88bfdbaa43cef9fd6493ecaa8e)) -* **Safe Matches:** using 'safe' forms of the get_matches family no longer exit the process ([c47025dc](https://github.com/kbknapp/clap-rs/commit/c47025dca2b3305dea0a0acfdd741b09af0c0d05), closes [#256](https://github.com/kbknapp/clap-rs/issues/256)) -* **Versionless SubCommands:** fixes a bug where the -V flag was needlessly built ([27df8b9d](https://github.com/kbknapp/clap-rs/commit/27df8b9d98d13709dad3929a009f40ebff089a1a), closes [#329](https://github.com/kbknapp/clap-rs/issues/329)) - -#### Documentation - -* adds comparison in readme ([1a8bf31e](https://github.com/kbknapp/clap-rs/commit/1a8bf31e7a6b87ce48a66af2cde1645b2dd5bc95), closes [#325](https://github.com/kbknapp/clap-rs/issues/325)) - - - - -### v1.4.5 (2015-10-06) - - -#### Bug Fixes - -* fixes crash on invalid arg error ([c78ce128](https://github.com/kbknapp/clap-rs/commit/c78ce128ebbe7b8f730815f8176c29d76f4ade8c)) - - - - -### v1.4.4 (2015-10-06) - - -#### Documentation - -* clean up some formatting ([b7df92d7](https://github.com/kbknapp/clap-rs/commit/b7df92d7ea25835701dd22ddff984b9749f48a00)) -* move the crate-level docs to top of the lib.rs file ([d7233bf1](https://github.com/kbknapp/clap-rs/commit/d7233bf122dbf80ba8fc79e5641be2df8af10e7a)) -* changes doc comments to rustdoc comments ([34b601be](https://github.com/kbknapp/clap-rs/commit/34b601be5fdde76c1a0859385b359b96d66b8732)) -* fixes panic in 14_groups example ([945b00a0](https://github.com/kbknapp/clap-rs/commit/945b00a0c27714b63bdca48d003fe205fcfdc578), closes [#295](https://github.com/kbknapp/clap-rs/issues/295)) -* avoid suggesting star dependencies. ([d33228f4](https://github.com/kbknapp/clap-rs/commit/d33228f40b5fefb84cf3dd51546bfb340dcd9f5a)) -* **Rustdoc:** adds portions of the readme to main rustdoc page ([6f9ee181](https://github.com/kbknapp/clap-rs/commit/6f9ee181e69d90bd4206290e59d6f3f1e8f0cbb2), closes [#293](https://github.com/kbknapp/clap-rs/issues/293)) - -#### Bug Fixes - -* grammar error in some conflicting option errors ([e73b07e1](https://github.com/kbknapp/clap-rs/commit/e73b07e19474323ad2260da66abbf6a6d4ecbd4f)) -* **Unified Help:** sorts both flags and options as a unified category ([2a223dad](https://github.com/kbknapp/clap-rs/commit/2a223dad82901fa2e74baad3bfc4c7b94509300f)) -* **Usage:** fixes a bug where required args aren't filtered properly ([72b453dc](https://github.com/kbknapp/clap-rs/commit/72b453dc170af3050bb123d35364f6da77fc06d7), closes [#277](https://github.com/kbknapp/clap-rs/issues/277)) -* **Usage Strings:** fixes a bug ordering of elements in usage strings ([aaf0d6fe](https://github.com/kbknapp/clap-rs/commit/aaf0d6fe7aa2403e76096c16204d254a9ee61ee2), closes [#298](https://github.com/kbknapp/clap-rs/issues/298)) - -#### Features - -* supports -aValue style options ([0e3733e4](https://github.com/kbknapp/clap-rs/commit/0e3733e4fec2015c2d566a51432dcd92cb69cad3)) -* **Trailing VarArg:** adds opt-in setting for final arg being vararg ([27018b18](https://github.com/kbknapp/clap-rs/commit/27018b1821a4bcd5235cfe92abe71b3c99efc24d), closes [#278](https://github.com/kbknapp/clap-rs/issues/278)) - - - - -### v1.4.3 (2015-09-30) - - -#### Features - -* allows accessing arg values by group name ([c92a4b9e](https://github.com/kbknapp/clap-rs/commit/c92a4b9eff2d679957f61c0c41ff404b40d38a91)) - -#### Documentation - -* use links to examples instead of plain text ([bb4fe237](https://github.com/kbknapp/clap-rs/commit/bb4fe237858535627271465147add537e4556b43)) - -#### Bug Fixes - -* **Help Message:** required args no longer double list in usage ([1412e639](https://github.com/kbknapp/clap-rs/commit/1412e639e0a79df84936d1101a837f90077d1c83), closes [#277](https://github.com/kbknapp/clap-rs/issues/277)) -* **Possible Values:** possible value validation is restored ([f121ae74](https://github.com/kbknapp/clap-rs/commit/f121ae749f8f4bfe754ef2e8a6dfc286504b5b75), closes [#287](https://github.com/kbknapp/clap-rs/issues/287)) - - - - -### v1.4.2 (2015-09-23) - - -#### Bug Fixes - -* **Conflicts:** fixes bug with conflicts not removing required args ([e17fcec5](https://github.com/kbknapp/clap-rs/commit/e17fcec53b3216ad047a13dddc6f740473fad1a1), closes [#271](https://github.com/kbknapp/clap-rs/issues/271)) - - - - -### v1.4.1 (2015-09-22) - - -#### Examples - -* add clap_app quick example ([4ba6249c](https://github.com/kbknapp/clap-rs/commit/4ba6249c3cf4d2e083370d1fe4dcc7025282c28a)) - -#### Features - -* **Unicode:** allows non-panicing on invalid unicode characters ([c5bf7ddc](https://github.com/kbknapp/clap-rs/commit/c5bf7ddc8cfb876ec928a5aaf5591232bbb32e5d)) - -#### Documentation - -* properly names Examples section for rustdoc ([87ba5445](https://github.com/kbknapp/clap-rs/commit/87ba54451d7ec7b1c9b9ef134f90bbe39e6fac69)) -* fixes various typos and spelling ([f85640f9](https://github.com/kbknapp/clap-rs/commit/f85640f9f6d8fd3821a40e9b8b7a34fabb789d02)) -* **Arg:** unhides fields of the Arg struct ([931aea88](https://github.com/kbknapp/clap-rs/commit/931aea88427edf43a3da90d5a500c1ff2b2c3614)) - -#### Bug Fixes - -* flush the buffer in App::print_version() ([cbc42a37](https://github.com/kbknapp/clap-rs/commit/cbc42a37d212d84d22b1777d08e584ff191934e7)) -* Macro benchmarks ([13712da1](https://github.com/kbknapp/clap-rs/commit/13712da1d36dc7614eec3a10ad488257ba615751)) - - - - -## v1.4.0 (2015-09-09) - - -#### Features - -* allows printing help message by library consumers ([56b95f32](https://github.com/kbknapp/clap-rs/commit/56b95f320875c62dda82cb91b29059671e120ed1)) -* allows defining hidden args and subcmds ([2cab4d03](https://github.com/kbknapp/clap-rs/commit/2cab4d0334ea3c2439a1d4bfca5bf9905c7ea9ac), closes [#231](https://github.com/kbknapp/clap-rs/issues/231)) -* Builder macro to assist with App/Arg/Group/SubCommand building ([443841b0](https://github.com/kbknapp/clap-rs/commit/443841b012a8d795cd5c2bd69ae6e23ef9b16477)) -* **Errors:** allows consumers to write to stderr and exit on error ([1e6403b6](https://github.com/kbknapp/clap-rs/commit/1e6403b6a863574fa3cb6946b1fb58f034e8664c)) - - - - -### v1.3.2 (2015-09-08) - - -#### Documentation - -* fixed ErrorKind docs ([dd057843](https://github.com/kbknapp/clap-rs/commit/dd05784327fa070eb6ce5ce89a8507e011d8db94)) -* **ErrorKind:** changed examples content ([b9ca2616](https://github.com/kbknapp/clap-rs/commit/b9ca261634b89613bbf3d98fd74d55cefbb31a8c)) - -#### Bug Fixes - -* fixes a bug where the help subcommand wasn't overridable ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745)) - -#### Features - -* adds abiltiy not consume self when parsing matches and/or exit on help ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745)) -* **App:** Added ability for users to handle errors themselves ([934e6fbb](https://github.com/kbknapp/clap-rs/commit/934e6fbb643b2385efc23444fe6fce31494dc288)) - - - - -### v1.3.1 (2015-09-04) - - -#### Examples - -* **17_yaml:** fixed example ([9b848622](https://github.com/kbknapp/clap-rs/commit/9b848622296c8c5c7b9a39b93ddd41f51df790b5)) - -#### Performance - -* changes ArgGroup HashSets to Vec ([3cb4a48e](https://github.com/kbknapp/clap-rs/commit/3cb4a48ebd15c20692f4f3a2a924284dc7fd5e10)) -* changes BTreeSet for Vec in some instances ([baab2e3f](https://github.com/kbknapp/clap-rs/commit/baab2e3f4060e811abee14b1654cbcd5cf3b5fea)) - - - - -## v1.3.0 (2015-09-01) - - -#### Features - -* **YAML:** allows building a CLI from YAML files ([86cf4c45](https://github.com/kbknapp/clap-rs/commit/86cf4c45626a36b8115446952f9069f73c1debc3)) -* **ArgGroups:** adds support for building ArgGroups from yaml ([ecf88665](https://github.com/kbknapp/clap-rs/commit/ecf88665cbff367018b29161a1b75d44a212707d)) -* **Subcommands:** adds support for subcommands from yaml ([e415cf78](https://github.com/kbknapp/clap-rs/commit/e415cf78ba916052d118a8648deba2b9c16b1530)) - -#### Documentation - -* **YAML:** adds examples for using YAML to build a CLI ([ab41d7f3](https://github.com/kbknapp/clap-rs/commit/ab41d7f38219544750e6e1426076dc498073191b)) -* **Args from YAML:** fixes doc examples ([19b348a1](https://github.com/kbknapp/clap-rs/commit/19b348a10050404cd93888dbbbe4f396681b67d0)) -* **Examples:** adds better usage examples instead of having unused variables ([8cbacd88](https://github.com/kbknapp/clap-rs/commit/8cbacd8883004fe71a8ea036ec4391c7dd8efe94)) - -#### Examples - -* Add AppSettings example ([12705079](https://github.com/kbknapp/clap-rs/commit/12705079ca96a709b4dd94f7ddd20a833b26838c)) - -#### Bug Fixes - -* **Unified Help Messages:** fixes a crash from this setting and no opts ([169ffec1](https://github.com/kbknapp/clap-rs/commit/169ffec1003d58d105d7ef2585b3425e57980000), closes [#210](https://github.com/kbknapp/clap-rs/issues/210)) - - - - -### v1.2.5 (2015-08-27) - - -#### Examples - -* add custom validator example ([b9997d1f](https://github.com/kbknapp/clap-rs/commit/b9997d1fca74d4d8f93971f2a01bdf9798f913d5)) -* fix indentation ([d4f1b740](https://github.com/kbknapp/clap-rs/commit/d4f1b740ede410fd2528b9ecd89592c2fd8b1e20)) - -#### Features - -* **Args:** allows opts and args to define a name for help and usage msgs ([ad962ec4](https://github.com/kbknapp/clap-rs/commit/ad962ec478da999c7dba0afdb84c266f4d09b1bd)) - - - - -### v1.2.4 (2015-08-26) - - -#### Bug Fixes - -* **Possible Values:** fixes a bug where suggestions arent made when using --long=value format ([3d5e9a6c](https://github.com/kbknapp/clap-rs/commit/3d5e9a6cedb26668839b481c9978e2fbbab8be6f), closes [#192](https://github.com/kbknapp/clap-rs/issues/192)) - - - - -### v1.2.3 (2015-08-24) - - -#### Bug Fixes - -* **App, Args:** fixed subcommand reqs negation ([b41afa8c](https://github.com/kbknapp/clap-rs/commit/b41afa8c3ded3d1be12f7a2f8ea06cc44afc9458), closes [#188](https://github.com/kbknapp/clap-rs/issues/188)) - - - - -### v1.2.2 (2015-08-23) - - -#### Bug Fixes - -* fixed confusing error message, also added test for it ([fc7a31a7](https://github.com/kbknapp/clap-rs/commit/fc7a31a745efbf1768ee2c62cd3bb72bfe30c708)) -* **App:** fixed requirmets overriding ([9c135eb7](https://github.com/kbknapp/clap-rs/commit/9c135eb790fa16183e5bdb2009ddc3cf9e25f99f)) - - - - -### v1.2.1 (2015-08-20) - - -#### Documentation - -* **README.md:** updates for new features ([16cf9245](https://github.com/kbknapp/clap-rs/commit/16cf9245fb5fc4cf6face898e358368bf9961cbb)) - -#### Features - -* implements posix compatible conflicts for long args ([8c2d48ac](https://github.com/kbknapp/clap-rs/commit/8c2d48acf5473feebd721a9049a9c9b7051e70f9)) -* added overrides to support conflicts in POSIX compatible manner ([0b916a00](https://github.com/kbknapp/clap-rs/commit/0b916a00de26f6941538f6bc5f3365fa302083c1)) -* **Args:** allows defining POSIX compatible argument conflicts ([d715646e](https://github.com/kbknapp/clap-rs/commit/d715646e69759ccd95e01f49b04f489827ecf502)) - -#### Bug Fixes - -* fixed links in cargo and license buttons ([6d9837ad](https://github.com/kbknapp/clap-rs/commit/6d9837ad9a9e006117cd7372fdc60f9a3889c7e2)) - -#### Performance - -* **Args and Apps:** changes HashSet->Vec in some instances for increased performance ([d0c3b379](https://github.com/kbknapp/clap-rs/commit/d0c3b379700757e0a9b0c40af709f8af1f5b4949)) - - - - -### v1.2.0 (2015-08-15) - - -#### Bug Fixes - -* fixed misspell and enum name ([7df170d7](https://github.com/kbknapp/clap-rs/commit/7df170d7f4ecff06608317655d1e0c4298f62076)) -* fixed use for clap crate ([dc3ada73](https://github.com/kbknapp/clap-rs/commit/dc3ada738667d4b689678f79d14251ee82004ece)) - -#### Documentation - -* updates docs for new features ([03496547](https://github.com/kbknapp/clap-rs/commit/034965471782d872ca495045b58d34b31807c5b1)) -* fixed docs for previous changes ([ade36778](https://github.com/kbknapp/clap-rs/commit/ade367780c366425de462506d256e0f554ed3b9c)) - -#### Improvements - -* **AppSettings:** adds ability to add multiple settings at once ([4a00e251](https://github.com/kbknapp/clap-rs/commit/4a00e2510d0ca8d095d5257d51691ba3b61c1374)) - -#### Features - -* Replace application level settings with enum variants ([618dc4e2](https://github.com/kbknapp/clap-rs/commit/618dc4e2c205bf26bc43146164e65eb1f6b920ed)) -* **Args:** allows for custom argument value validations to be defined ([84ae2ddb](https://github.com/kbknapp/clap-rs/commit/84ae2ddbceda34b5cbda98a6959edaa52fde2e1a), closes [#170](https://github.com/kbknapp/clap-rs/issues/170)) - - - - -### v1.1.6 (2015-08-01) - - -#### Bug Fixes - -* fixes two bugs in App when printing newlines in help and subcommands required error ([d63c0136](https://github.com/kbknapp/clap-rs/commit/d63c0136310db9dd2b1c7b4745938311601d8938)) - - - - -### v1.1.5 (2015-07-29) - -#### Performance - -* removes some unneeded allocations ([93e915df](https://github.com/kbknapp/clap-rs/commit/93e915dfe300f7b7d6209ca93323c6a46f89a8c1)) - - -### v1.1.4 (2015-07-20) - - -#### Improvements - -* **Usage Strings** displays a [--] when it may be helpful ([86c3be85](https://github.com/kbknapp/clap-rs/commit/86c3be85fb6f77f83b5a6d2df40ae60937486984)) - -#### Bug Fixes - -* **Macros** fixes a typo in a macro generated error message ([c9195c5f](https://github.com/kbknapp/clap-rs/commit/c9195c5f92abb8cd6a37b4f4fbb2f1fee2a8e368)) -* **Type Errors** fixes formatting of error output when failed type parsing ([fe5d95c6](https://github.com/kbknapp/clap-rs/commit/fe5d95c64f3296e6eddcbec0cb8b86659800145f)) - - - - -### v1.1.3 (2015-07-18) - - -#### Documentation - -* updates README.md to include lack of color support on Windows ([52f81e17](https://github.com/kbknapp/clap-rs/commit/52f81e17377b18d2bd0f34693b642b7f358998ee)) - -#### Bug Fixes - -* fixes formatting bug which prevented compiling on windows ([9cb5dceb](https://github.com/kbknapp/clap-rs/commit/9cb5dceb3e5fe5e0e7b24619ff77e5040672b723), closes [#163](https://github.com/kbknapp/clap-rs/issues/163)) - - - - -### v1.1.2 (2015-07-17) - - -#### Bug Fixes - -* fixes a bug when parsing multiple {n} newlines inside help strings ([6d214b54](https://github.com/kbknapp/clap-rs/commit/6d214b549a9b7e189a94e5fa2b7c92cc333ca637)) - - - - -## v1.1.1 (2015-07-17) - - -#### Bug Fixes - -* fixes a logic bug and allows setting Arg::number_of_values() < 2 ([42b6d1fc](https://github.com/kbknapp/clap-rs/commit/42b6d1fc3c519c92dfb3af15276e7d3b635e6cfe), closes [#161](https://github.com/kbknapp/clap-rs/issues/161)) - - - - -## v1.1.0 (2015-07-16) - - -#### Features - -* allows creating unified help messages, a la docopt or getopts ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1), closes [#158](https://github.com/kbknapp/clap-rs/issues/158)) -* allows stating all subcommands should *not* have --version flags ([336c476f](https://github.com/kbknapp/clap-rs/commit/336c476f631d512b54ac56fdca6f29ebdc2c00c5), closes [#156](https://github.com/kbknapp/clap-rs/issues/156)) -* allows setting version number to auto-propagate through subcommands ([bc66d3c6](https://github.com/kbknapp/clap-rs/commit/bc66d3c6deedeca62463fff95369ab1cfcdd366b), closes [#157](https://github.com/kbknapp/clap-rs/issues/157)) - -#### Improvements - -* **Help Strings** properly aligns and handles newlines in long help strings ([f9800a29](https://github.com/kbknapp/clap-rs/commit/f9800a29696dd2cc0b0284bf693b3011831e556f), closes [#145](https://github.com/kbknapp/clap-rs/issues/145)) - - -#### Performance - -* **Help Messages** big performance improvements when printing help messages ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1)) - -#### Documentation - -* updates readme with new features ([8232f7bb](https://github.com/kbknapp/clap-rs/commit/8232f7bb52e88862bc13c3d4f99ee4f56cfe4bc0)) -* fix incorrect code example for `App::subcommand_required` ([8889689d](https://github.com/kbknapp/clap-rs/commit/8889689dc6336ccc45b2c9f2cf8e2e483a639e93)) - - - -### v1.0.3 (2015-07-11) - - -#### Improvements - -* **Errors** writes errors to stderr ([cc76ab8c](https://github.com/kbknapp/clap-rs/commit/cc76ab8c2b77c67b42f4717ded530df7806142cf), closes [#154](https://github.com/kbknapp/clap-rs/issues/154)) - -#### Documentation - -* **README.md** updates example help message to new format ([0aca29bd](https://github.com/kbknapp/clap-rs/commit/0aca29bd5d6d1a4e9971bdc88d946ffa58606efa)) - - - - -### v1.0.2 (2015-07-09) - - -#### Improvements - -* **Usage** re-orders optional arguments and required to natural standard ([dc7e1fce](https://github.com/kbknapp/clap-rs/commit/dc7e1fcea5c85d317018fb201d2a9262249131b4), closes [#147](https://github.com/kbknapp/clap-rs/issues/147)) - - - - -### v1.0.1 (2015-07-08) - - -#### Bug Fixes - -* allows empty values when using --long='' syntax ([083f82d3](https://github.com/kbknapp/clap-rs/commit/083f82d333b69720a6ef30074875310921d964d1), closes [#151](https://github.com/kbknapp/clap-rs/issues/151)) - - - - -## v1.0.0 (2015-07-08) - - -#### Documentation - -* **README.md** adds new features to what's new list ([938f7f01](https://github.com/kbknapp/clap-rs/commit/938f7f01340f521969376cf4e2e3d9436bca21f7)) -* **README.md** use with_name for subcommands ([28b7e316](https://github.com/kbknapp/clap-rs/commit/28b7e3161fb772e5309042648fe8c3a420645bac)) - -#### Features - -* args can now be parsed from arbitrary locations, not just std::env::args() ([75312528](https://github.com/kbknapp/clap-rs/commit/753125282b1b9bfff875f1557ce27610edcc59e1)) - - - - -## v1.0.0-beta (2015-06-30) - - -#### Features - -* allows waiting for user input on error ([d0da3bdd](https://github.com/kbknapp/clap-rs/commit/d0da3bdd9d1871541907ea9c645322a74d260e07), closes [#140](https://github.com/kbknapp/clap-rs/issues/140)) -* **Help** allows one to fully override the auto-generated help message ([26d5ae3e](https://github.com/kbknapp/clap-rs/commit/26d5ae3e330d1e150811d5b60b2b01a8f8df854e), closes [#141](https://github.com/kbknapp/clap-rs/issues/141)) - -#### Documentation - -* adds "whats new" section to readme ([ff149a29](https://github.com/kbknapp/clap-rs/commit/ff149a29dd9e179865e6d577cd7dc87c54f8f95c)) - -#### Improvements - -* removes deprecated functions in prep for 1.0 ([274484df](https://github.com/kbknapp/clap-rs/commit/274484dfd08fff4859cefd7e9bef3b73d3a9cb5f)) - - - - -## v0.11.0 (2015-06-17) - BREAKING CHANGE - - -#### Documentation - -* updates docs to new version flag defaults ([ebf442eb](https://github.com/kbknapp/clap-rs/commit/ebf442ebebbcd2ec6bfe2c06566c9d362bccb112)) - -#### Features - -* **Help and Version** default short for version is now `-V` but can be overridden (only breaks manual documentation) (**BREAKING CHANGE** [eb1d9320](https://github.com/kbknapp/clap-rs/commit/eb1d9320c509c1e4e57d7c7959da82bcfe06ada0)) - - - - -### v0.10.5 (2015-06-06) - - -#### Bug Fixes - -* **Global Args** global arguments propogate fully now ([1f377960](https://github.com/kbknapp/clap-rs/commit/1f377960a48c82f54ca5f39eb56bcb393140b046), closes [#137](https://github.com/kbknapp/clap-rs/issues/137)) - - - - -### v0.10.4 (2015-06-06) - - -#### Bug Fixes - -* **Global Args** global arguments propogate fully now ([8f2c0160](https://github.com/kbknapp/clap-rs/commit/8f2c0160c8d844daef375a33dbaec7d89de00a00), closes [#137](https://github.com/kbknapp/clap-rs/issues/137)) - - - - -### v0.10.3 (2015-05-31) - - -#### Bug Fixes - -* **Global Args** fixes a bug where globals only transfer to one subcommand ([a37842ee](https://github.com/kbknapp/clap-rs/commit/a37842eec1ee3162b86fdbda23420b221cdb1e3b), closes [#135](https://github.com/kbknapp/clap-rs/issues/135)) - - - - -### v0.10.2 (2015-05-30) - - -#### Improvements - -* **Binary Names** allows users to override the system determined bin name ([2191fe94](https://github.com/kbknapp/clap-rs/commit/2191fe94bda35771383b52872fb7f5421b178be1), closes [#134](https://github.com/kbknapp/clap-rs/issues/134)) - -#### Documentation - -* adds contributing guidelines ([6f76bd0a](https://github.com/kbknapp/clap-rs/commit/6f76bd0a07e8b7419b391243ab2d6687cd8a9c5f)) - - - - -### v0.10.1 (2015-05-26) - - -#### Features - -* can now specify that an app or subcommand should display help on no args or subcommands ([29ca7b2f](https://github.com/kbknapp/clap-rs/commit/29ca7b2f74376ca0cdb9d8ee3bfa99f7640cc404), closes [#133](https://github.com/kbknapp/clap-rs/issues/133)) - - - - -## v0.10.0 (2015-05-23) - - -#### Features - -* **Global Args** allows args that propagate down to child commands ([2bcc6137](https://github.com/kbknapp/clap-rs/commit/2bcc6137a83cb07757771a0afea953e68e692f0b), closes [#131](https://github.com/kbknapp/clap-rs/issues/131)) - -#### Improvements - -* **Colors** implements more structured colored output ([d6c3ed54](https://github.com/kbknapp/clap-rs/commit/d6c3ed54d21cf7b40d9f130d4280ff5448522fc5), closes [#129](https://github.com/kbknapp/clap-rs/issues/129)) - -#### Deprecations - -* **SubCommand/App** several methods and functions for stable release ([28b73855](https://github.com/kbknapp/clap-rs/commit/28b73855523ad170544afdb20665db98702fbe70)) - -#### Documentation - -* updates for deprecations and new features ([743eefe8](https://github.com/kbknapp/clap-rs/commit/743eefe8dd40c1260065ce086d572e9e9358bc4c)) - - - - -## v0.9.2 (2015-05-20) - - -#### Bug Fixes - -* **help** allows parent requirements to be ignored with help and version ([52218cc1](https://github.com/kbknapp/clap-rs/commit/52218cc1fdb06a42456c964d98cc2c7ac3432412), closes [#124](https://github.com/kbknapp/clap-rs/issues/124)) - - - - -## v0.9.1 (2015-05-18) - - -#### Bug Fixes - -* **help** fixes a bug where requirements are included as program name in help and version ([08ba3f25](https://github.com/kbknapp/clap-rs/commit/08ba3f25cf38b149229ba8b9cb37a5804fe6b789)) - - - - -## v0.9.0 (2015-05-17) - - -#### Improvements - -* **usage** usage strings now include parent command requirements ([dd8f21c7](https://github.com/kbknapp/clap-rs/commit/dd8f21c7c15cde348fdcf44fa7c205f0e98d2e4a), closes [#125](https://github.com/kbknapp/clap-rs/issues/125)) -* **args** allows consumer of clap to decide if empty values are allowed or not ([ab4ec609](https://github.com/kbknapp/clap-rs/commit/ab4ec609ccf692b9b72cccef5c9f74f5577e360d), closes [#122](https://github.com/kbknapp/clap-rs/issues/122)) - -#### Features - -* **subcommands** - * allows optionally specifying that no subcommand is an error ([7554f238](https://github.com/kbknapp/clap-rs/commit/7554f238fd3afdd60b7e4dcf00ff4a9eccf842c1), closes [#126](https://github.com/kbknapp/clap-rs/issues/126)) - * subcommands can optionally negate parent requirements ([4a4229f5](https://github.com/kbknapp/clap-rs/commit/4a4229f500e21c350e1ef78dd09ef27559653288), closes [#123](https://github.com/kbknapp/clap-rs/issues/123)) - - - - -## v0.8.6 (2015-05-17) - - -#### Bug Fixes - -* **args** `-` can now be parsed as a value for an argument ([bc12e78e](https://github.com/kbknapp/clap-rs/commit/bc12e78eadd7eaf9d008a8469fdd2dfd7990cb5d), closes [#121](https://github.com/kbknapp/clap-rs/issues/121)) - - - - -## v0.8.5 (2015-05-15) - - -#### Bug Fixes - -* **macros** makes macro errors consistent with others ([0c264a8c](https://github.com/kbknapp/clap-rs/commit/0c264a8ca57ec1cfdcb74dae79145d766cdc9b97), closes [#118](https://github.com/kbknapp/clap-rs/issues/118)) - -#### Features - -* **macros** - * arg_enum! and simple_enum! provide a Vec<&str> of variant names ([30fa87ba](https://github.com/kbknapp/clap-rs/commit/30fa87ba4e0f3189351d8f4f78b72e616a30d0bd), closes [#119](https://github.com/kbknapp/clap-rs/issues/119)) - * arg_enum! and simple_enum! auto-implement Display ([d1219f0d](https://github.com/kbknapp/clap-rs/commit/d1219f0d1371d872061bd0718057eca4ef47b739), closes [#120](https://github.com/kbknapp/clap-rs/issues/120)) - - - - -## v0.8.4 (2015-05-12) - - -#### Bug Fixes - -* **suggestions** --help and --version now get suggestions ([d2b3b1fa](https://github.com/kbknapp/clap-rs/commit/d2b3b1faa0bdc1c5d2350cc4635aba81e02e9d96), closes [#116](https://github.com/kbknapp/clap-rs/issues/116)) - - - - -## v0.8.3 (2015-05-10) - - -#### Bug Fixes - -* **usage** groups unfold their members in usage strings ([55d15582](https://github.com/kbknapp/clap-rs/commit/55d155827ea4a6b077a83669701e797ce1ad68f4), closes [#114](https://github.com/kbknapp/clap-rs/issues/114)) - -#### Performance - -* **usage** removes unneeded allocations ([fd53cd18](https://github.com/kbknapp/clap-rs/commit/fd53cd188555f5c3dc8bc341c5d7eb04b761a70f)) - - - - -## v0.8.2 (2015-05-08) - - -#### Bug Fixes - -* **usage strings** positional arguments are presented in index order ([eb0e374e](https://github.com/kbknapp/clap-rs/commit/eb0e374ecf952f1eefbc73113f21e0705936e40b), closes [#112](https://github.com/kbknapp/clap-rs/issues/112)) - - - - -## v0.8.1 (2015-05-06) - - -#### Bug Fixes - -* **subcommands** stops parsing multiple values when subcommands are found ([fc79017e](https://github.com/kbknapp/clap-rs/commit/fc79017eced04fd41cc1801331e5054df41fac17), closes [#109](https://github.com/kbknapp/clap-rs/issues/109)) - -#### Improvements - -* **color** reduces color in error messages ([aab44cca](https://github.com/kbknapp/clap-rs/commit/aab44cca6352f47e280c296e50c535f5d752dd46), closes [#110](https://github.com/kbknapp/clap-rs/issues/110)) -* **suggestions** adds suggested arguments to usage strings ([99447414](https://github.com/kbknapp/clap-rs/commit/994474146e9fb8b701af773a52da71553d74d4b7)) - - - - -## v0.8.0 (2015-05-06) - - -#### Bug Fixes - -* **did-you-mean** for review ([0535cfb0](https://github.com/kbknapp/clap-rs/commit/0535cfb0c711331568b4de8080eeef80bd254b68)) -* **Positional** positionals were ignored if they matched a subcmd, even after '--' ([90e7b081](https://github.com/kbknapp/clap-rs/commit/90e7b0818741668b47cbe3becd029bab588e3553)) -* **help** fixes bug where space between arg and help is too long ([632fb115](https://github.com/kbknapp/clap-rs/commit/632fb11514c504999ea86bdce47cdd34f8ebf646)) - -#### Features - -* **from_usage** adds ability to add value names or num of vals in usage string ([3d581976](https://github.com/kbknapp/clap-rs/commit/3d58197674ed7886ca315efb76e411608a327501), closes [#98](https://github.com/kbknapp/clap-rs/issues/98)) -* **did-you-mean** - * gate it behind 'suggestions' ([c0e38351](https://github.com/kbknapp/clap-rs/commit/c0e383515d01bdd5ca459af9c2f7e2cf49e2488b)) - * for possible values ([1cc2deb2](https://github.com/kbknapp/clap-rs/commit/1cc2deb29158e0e4e8b434e4ce26b3d819301a7d)) - * for long flags (i.e. --long) ([52a0b850](https://github.com/kbknapp/clap-rs/commit/52a0b8505c99354bdf5fd1cd256cf41197ac2d81)) - * for subcommands ([06e869b5](https://github.com/kbknapp/clap-rs/commit/06e869b5180258047ed3c60ba099de818dd25fff)) -* **Flags** adds sugestions functionality ([8745071c](https://github.com/kbknapp/clap-rs/commit/8745071c3257dd327c497013516f12a823df9530)) -* **errors** colorizes output red on error ([f8b26b13](https://github.com/kbknapp/clap-rs/commit/f8b26b13da82ba3ba9a932d3d1ab4ea45d1ab036)) - -#### Improvements - -* **arg_enum** allows ascii case insensitivity for enum variants ([b249f965](https://github.com/kbknapp/clap-rs/commit/b249f9657c6921c004764bd80d13ebca81585eec), closes [#104](https://github.com/kbknapp/clap-rs/issues/104)) -* **clap-test** simplified `make test` invocation ([d17dcb29](https://github.com/kbknapp/clap-rs/commit/d17dcb2920637a1f58c61c596b7bd362fd53047c)) - -#### Documentation - -* **README** adds details about optional and new features ([960389de](https://github.com/kbknapp/clap-rs/commit/960389de02c9872aaee9adabe86987f71f986e39)) -* **clap** fix typos caught by codespell ([8891d929](https://github.com/kbknapp/clap-rs/commit/8891d92917aa1a069cca67272be41b99e548356e)) -* **from_usage** explains new usage strings with multiple values ([05476fc6](https://github.com/kbknapp/clap-rs/commit/05476fc61cd1e5f4a4e750d258c878732a3a9c64)) - - - - -## v0.7.6 (2015-05-05) - - -#### Improvements - -* **Options** adds number of values to options in help/usage ([c1c993c4](https://github.com/kbknapp/clap-rs/commit/c1c993c419d18e35c443785053d8de9a2ef88073)) - -#### Features - -* **from_usage** adds ability to add value names or num of vals in usage string ([ad55748c](https://github.com/kbknapp/clap-rs/commit/ad55748c265cf27935c7b210307d2040b6a09125), closes [#98](https://github.com/kbknapp/clap-rs/issues/98)) - -#### Bug Fixes - -* **MultipleValues** properly distinguishes between multiple values and multiple occurrences ([dd2a7564](https://github.com/kbknapp/clap-rs/commit/dd2a75640ca68a91b973faad15f04df891356cef), closes [#99](https://github.com/kbknapp/clap-rs/issues/99)) -* **help** fixes tab alignment with multiple values ([847001ff](https://github.com/kbknapp/clap-rs/commit/847001ff6d8f4d9518e810fefb8edf746dd0f31e)) - -#### Documentation - -* **from_usage** explains new usage strings with multiple values ([5a3a42df](https://github.com/kbknapp/clap-rs/commit/5a3a42dfa3a783537f88dedc0fd5f0edcb8ea372)) - - - - -## v0.7.5 (2015-05-04) - - -#### Bug Fixes - -* **Options** fixes bug where options with no value don't error out ([a1fb94be](https://github.com/kbknapp/clap-rs/commit/a1fb94be53141572ffd97aad037295d4ffec82d0)) - - - - -## v0.7.4 (2015-05-03) - - -#### Bug Fixes - -* **Options** fixes a bug where option arguments in succession get their values skipped ([f66334d0](https://github.com/kbknapp/clap-rs/commit/f66334d0ce984e2b56e5c19abb1dd536fae9342a)) - - - - -## v0.7.3 (2015-05-03) - - -#### Bug Fixes - -* **RequiredValues** fixes a bug where missing values are parsed as missing arguments ([93c4a723](https://github.com/kbknapp/clap-rs/commit/93c4a7231ba1a08152648598f7aa4503ea82e4de)) - -#### Improvements - -* **ErrorMessages** improves error messages and corrections ([a29c3983](https://github.com/kbknapp/clap-rs/commit/a29c3983c4229906655a29146ec15a0e46dd942d)) -* **ArgGroups** improves requirement and confliction support for groups ([c236dc5f](https://github.com/kbknapp/clap-rs/commit/c236dc5ff475110d2a1b80e62903f80296163ad3)) - - - - -## v0.7.2 (2015-05-03) - - -#### Bug Fixes - -* **RequiredArgs** fixes bug where required-by-default arguments are not listed in usage ([12aea961](https://github.com/kbknapp/clap-rs/commit/12aea9612d290845ba86515c240aeeb0a21198db), closes [#96](https://github.com/kbknapp/clap-rs/issues/96)) - - - - -## v0.7.1 (2015-05-01) - - -#### Bug Fixes - -* **MultipleValues** stops evaluating values if the max or exact number of values was reached ([86d92c9f](https://github.com/kbknapp/clap-rs/commit/86d92c9fdbf9f422442e9562977bbaf268dbbae1)) - - - - -## v0.7.0 (2015-04-30) - BREAKING CHANGE - - -#### Bug Fixes - -* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83)) - -#### Features - -* **MultipleValues** - * add support for minimum and maximum number of values ([53f6b8c9](https://github.com/kbknapp/clap-rs/commit/53f6b8c9d8dc408b4fa9f833fc3a63683873c42f)) - * adds support limited number and named values ([ae09f05e](https://github.com/kbknapp/clap-rs/commit/ae09f05e92251c1b39a83d372736fcc7b504e432)) - * implement shorthand for options with multiple values ([6669f0a9](https://github.com/kbknapp/clap-rs/commit/6669f0a9687d4f668523145d7bd5c007d1eb59a8)) -* **arg** allow other types besides Vec for multiple value settings (**BREAKING CHANGE** [0cc2f698](https://github.com/kbknapp/clap-rs/commit/0cc2f69839b9b1db5d06330771b494783049a88e), closes [#87](https://github.com/kbknapp/clap-rs/issues/87)) -* **usage** implement smart usage strings on errors ([d77048ef](https://github.com/kbknapp/clap-rs/commit/d77048efb1e595ffe831f1a2bea2f2700db53b9f), closes [#88](https://github.com/kbknapp/clap-rs/issues/88)) - - - - -## v0.6.9 (2015-04-29) - - -#### Bug Fixes - -* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83)) - - - - -## 0.6.8 (2015-04-27) - - -#### Bug Fixes - -* **help** change long help --long=long -> --long ([1e25abfc](https://github.com/kbknapp/clap-rs/commit/1e25abfc36679ab89eae71bf98ced4de81992d00)) -* **RequiredArgs** required by default args should no longer be required when their exclusions are present ([4bb4c3cc](https://github.com/kbknapp/clap-rs/commit/4bb4c3cc076b49e86720e882bf8c489877199f2d)) - -#### Features - -* **ArgGroups** add ability to create arg groups ([09eb4d98](https://github.com/kbknapp/clap-rs/commit/09eb4d9893af40c347e50e2b717e1adef552357d)) - - - - -## v0.6.7 (2015-04-22) - - -#### Bug Fixes - -* **from_usage** fix bug causing args to not be required ([b76129e9](https://github.com/kbknapp/clap-rs/commit/b76129e9b71a63365d5c77a7f57b58dbd1e94d49)) - -#### Features - -* **apps** add ability to display additional help info after auto-gen'ed help msg ([65cc259e](https://github.com/kbknapp/clap-rs/commit/65cc259e4559cbe3653c865ec0c4b1e42a389b07)) - - - - -## v0.6.6 (2015-04-19) - - -#### Bug Fixes - -* **from_usage** tabs and spaces should be treated equally ([4fd44181](https://github.com/kbknapp/clap-rs/commit/4fd44181d55d8eb88caab1e625231cfa3129e347)) - -#### Features - -* **macros.rs** add macro to get version from Cargo.toml ([c630969a](https://github.com/kbknapp/clap-rs/commit/c630969aa3bbd386379219cae27ba1305b117f3e)) - - - - -## v0.6.5 (2015-04-19) - - -#### Bug Fixes - -* **macros.rs** fix use statements for trait impls ([86e4075e](https://github.com/kbknapp/clap-rs/commit/86e4075eb111937c8a7bdb344e866e350429f042)) - - - - -## v0.6.4 (2015-04-17) - - -#### Features - -* **macros** add ability to create enums pub or priv with derives ([2c499f80](https://github.com/kbknapp/clap-rs/commit/2c499f8015a199827cdf1fa3ec4f6f171722f8c7)) - - - - -## v0.6.3 (2015-04-16) - - -#### Features - -* **macros** add macro to create custom enums to use as types ([fb672aff](https://github.com/kbknapp/clap-rs/commit/fb672aff561c29db2e343d6c607138f141aca8b6)) - - - - -## v0.6.2 (2015-04-14) - - -#### Features - -* **macros** - * add ability to get multiple typed values or exit ([0b87251f](https://github.com/kbknapp/clap-rs/commit/0b87251fc088234bee51c323c2b652d7254f7a59)) - * add ability to get a typed multiple values ([e243fe38](https://github.com/kbknapp/clap-rs/commit/e243fe38ddbbf845a46c0b9baebaac3778c80927)) - * add convenience macro to get a typed value or exit ([4b7cd3ea](https://github.com/kbknapp/clap-rs/commit/4b7cd3ea4947780d9daa39f3e1ddab53ad4c7fef)) - * add convenience macro to get a typed value ([8752700f](https://github.com/kbknapp/clap-rs/commit/8752700fbb30e89ee68adbce24489ae9a24d33a9)) - - - - -## v0.6.1 (2015-04-13) - - -#### Bug Fixes - -* **from_usage** trim all whitespace before parsing ([91d29045](https://github.com/kbknapp/clap-rs/commit/91d2904599bd602deef2e515dfc65dc2863bdea0)) - - - - -## v0.6.0 (2015-04-13) - - -#### Bug Fixes - -* **tests** fix failing doc tests ([3710cd69](https://github.com/kbknapp/clap-rs/commit/3710cd69162f87221a62464f63437c1ce843ad3c)) - -#### Features - -* **app** add support for building args from usage strings ([d5d48bcf](https://github.com/kbknapp/clap-rs/commit/d5d48bcf463a4e494ef758836bd69a4c220bbbb5)) -* **args** add ability to create basic arguments from a usage string ([ab409a8f](https://github.com/kbknapp/clap-rs/commit/ab409a8f1db9e37cc70200f6f4a84a162692e618)) - - - - -## v0.5.14 (2015-04-10) - - -#### Bug Fixes - -* **usage** - * remove unneeded space ([51372789](https://github.com/kbknapp/clap-rs/commit/5137278942121bc2593ce6e5dc224ec2682549e6)) - * remove warning about unused variables ([ba817b9d](https://github.com/kbknapp/clap-rs/commit/ba817b9d815e37320650973f1bea0e7af3030fd7)) - -#### Features - -* **usage** add ability to get usage string for subcommands too ([3636afc4](https://github.com/kbknapp/clap-rs/commit/3636afc401c2caa966efb5b1869ef4f1ed3384aa)) - - - - -## v0.5.13 (2015-04-09) - - -#### Features - -* **SubCommands** add method to get name and subcommand matches together ([64e53928](https://github.com/kbknapp/clap-rs/commit/64e539280e23e567cf5de393b346eb0ca20e7eb5)) -* **ArgMatches** add method to get default usage string ([02462150](https://github.com/kbknapp/clap-rs/commit/02462150ca750bdc7012627d7e8d96379d494d7f)) - - - - -## v0.5.12 (2015-04-08) - - -#### Features - -* **help** sort arguments by name so as to not display a random order ([f4b2bf57](https://github.com/kbknapp/clap-rs/commit/f4b2bf5767386013069fb74862e6e938dacf44d2)) - - - - -## v0.5.11 (2015-04-08) - - -#### Bug Fixes - -* **flags** fix bug not allowing users to specify -v or -h ([90e72cff](https://github.com/kbknapp/clap-rs/commit/90e72cffdee321b79eea7a2207119533540062b4)) - - - - -## v0.5.10 (2015-04-08) - - -#### Bug Fixes - -* **help** fix spacing when option argument has not long version ([ca17fa49](https://github.com/kbknapp/clap-rs/commit/ca17fa494b68e92da83ee364bf64b0687006824b)) - - - - -## v0.5.9 (2015-04-08) - - -#### Bug Fixes - -* **positional args** all previous positional args become required when a latter one is required ([c14c3f31](https://github.com/kbknapp/clap-rs/commit/c14c3f31fd557c165570b60911d8ee483d89d6eb), closes [#50](https://github.com/kbknapp/clap-rs/issues/50)) -* **clap** remove unstable features for Rust 1.0 ([9abdb438](https://github.com/kbknapp/clap-rs/commit/9abdb438e36e364d41550e7f5d44ebcaa8ee6b10)) -* **args** improve error messages for arguments with mutual exclusions ([18dbcf37](https://github.com/kbknapp/clap-rs/commit/18dbcf37024daf2b76ca099a6f118b53827aa339), closes [#51](https://github.com/kbknapp/clap-rs/issues/51)) - - - - -## v0.5.8 (2015-04-08) - - -#### Bug Fixes - -* **option args** fix bug in getting the wrong number of occurrences for options ([82ad6ad7](https://github.com/kbknapp/clap-rs/commit/82ad6ad77539cf9f9a03b78db466f575ebd972cc)) -* **help** fix formatting for option arguments with no long ([e8691004](https://github.com/kbknapp/clap-rs/commit/e869100423d93fa3acff03c4620cbcc0d0e790a1)) -* **flags** add assertion to catch flags with specific value sets ([a0a2a40f](https://github.com/kbknapp/clap-rs/commit/a0a2a40fed57f7c5ad9d68970d090e9856306c7d), closes [#52](https://github.com/kbknapp/clap-rs/issues/52)) -* **args** improve error messages for arguments with mutual exclusions ([bff945fc](https://github.com/kbknapp/clap-rs/commit/bff945fc5d03bba4266533340adcffb002508d1b), closes [#51](https://github.com/kbknapp/clap-rs/issues/51)) -* **tests** add missing .takes_value(true) to option2 ([bdb0e88f](https://github.com/kbknapp/clap-rs/commit/bdb0e88f696c8595c3def3bfb0e52d538c7be085)) -* **positional args** all previous positional args become required when a latter one is required ([343d47dc](https://github.com/kbknapp/clap-rs/commit/343d47dcbf83786a45c0d0f01b27fd9dd76725de), closes [#50](https://github.com/kbknapp/clap-rs/issues/50)) - - - - -## v0.5.7 (2015-04-08) - - -#### Bug Fixes - -* **args** fix bug in arguments who are required and mutually exclusive ([6ceb88a5](https://github.com/kbknapp/clap-rs/commit/6ceb88a594caae825605abc1cdad95204996bf29)) - - - - -## v0.5.6 (2015-04-08) - - -#### Bug Fixes - -* **help** fix formatting of help and usage ([28691b52](https://github.com/kbknapp/clap-rs/commit/28691b52f67e65c599e10e4ea2a0f6f9765a06b8)) - - - - -## v0.5.5 (2015-04-08) - - -#### Bug Fixes - -* **help** fix formatting of help for flags and options ([6ec10115](https://github.com/kbknapp/clap-rs/commit/6ec1011563a746f0578a93b76d45e63878e0f9a8)) - - - - -## v0.5.4 (2015-04-08) - - -#### Features - -* **help** add '...' to indicate multiple values supported ([297ddba7](https://github.com/kbknapp/clap-rs/commit/297ddba77000e2228762ab0eca50b480f7467386)) - - - - -## v0.5.3 (2015-04-08) - - -#### Features - -* **positionals** - * add assertions for positional args with multiple vals ([b7fa72d4](https://github.com/kbknapp/clap-rs/commit/b7fa72d40f18806ec2042dd67a518401c2cf5681)) - * add support for multiple values ([80784009](https://github.com/kbknapp/clap-rs/commit/807840094109fbf90b348039ae22669ef27889ba)) - - - - -## v0.5.2 (2015-04-08) - - -#### Bug Fixes - -* **apps** allow use of hyphens in application and subcommand names ([da549dcb](https://github.com/kbknapp/clap-rs/commit/da549dcb6c7e0d773044ab17829744483a8b0f7f)) - - - - -## v0.5.1 (2015-04-08) - - -#### Bug Fixes - -* **args** determine if the only arguments allowed are also required ([0a09eb36](https://github.com/kbknapp/clap-rs/commit/0a09eb365ced9a03faf8ed24f083ef730acc90e8)) - - - - -## v0.5.0 (2015-04-08) - - -#### Features - -* **args** add support for a specific set of allowed values on options or positional arguments ([270eb889](https://github.com/kbknapp/clap-rs/commit/270eb88925b6dc2881bff1f31ee344f085d31809)) - - - - -## v0.4.18 (2015-04-08) - - -#### Bug Fixes - -* **usage** display required args in usage, even if only required by others ([1b7316d4](https://github.com/kbknapp/clap-rs/commit/1b7316d4a8df70b0aa584ccbfd33f68966ad2a54)) - -#### Features - -* **subcommands** properly list subcommands in help and usage ([4ee02344](https://github.com/kbknapp/clap-rs/commit/4ee023442abc3dba54b68138006a52b714adf331)) - - - - -## v0.4.17 (2015-04-08) - - -#### Bug Fixes - -* **tests** remove cargo test from claptests makefile ([1cf73817](https://github.com/kbknapp/clap-rs/commit/1cf73817d6fb1dccb5b6a23b46c2efa8b567ad62)) - - - - -## v0.4.16 (2015-04-08) - - -#### Bug Fixes - -* **option** fix bug with option occurrence values ([9af52e93](https://github.com/kbknapp/clap-rs/commit/9af52e93cef9e17ac9974963f132013d0b97b946)) -* **tests** fix testing script bug and formatting ([d8f03a55](https://github.com/kbknapp/clap-rs/commit/d8f03a55c4f74d126710ee06aad5a667246a8001)) - -#### Features - -* **arg** allow lifetimes other than 'static in arguments ([9e8c1fb9](https://github.com/kbknapp/clap-rs/commit/9e8c1fb9406f8448873ca58bab07fe905f1551e5)) diff --git a/third_party/rust/clap/CONTRIBUTORS.md b/third_party/rust/clap/CONTRIBUTORS.md deleted file mode 100644 index f0fd77724435..000000000000 --- a/third_party/rust/clap/CONTRIBUTORS.md +++ /dev/null @@ -1,91 +0,0 @@ -the following is a list of contributors: - - -[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) | -:---: |:---: |:---: |:---: |:---: |:---: | -[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) | - -[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) | -:---: |:---: |:---: |:---: |:---: |:---: | -[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) | - -[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) | -:---: |:---: |:---: |:---: |:---: |:---: | -[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) | - -[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) | -:---: |:---: |:---: |:---: |:---: |:---: | -[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) | - -[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) | -:---: |:---: |:---: |:---: |:---: |:---: | -[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) | - -[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) | -:---: |:---: |:---: |:---: |:---: |:---: | -[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) | - -[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) | -:---: |:---: |:---: |:---: |:---: |:---: | -[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) | - -[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) | -:---: |:---: |:---: |:---: |:---: |:---: | -[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) | - -[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) | -:---: |:---: |:---: |:---: |:---: |:---: | -[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) | - -[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) | -:---: |:---: |:---: |:---: |:---: |:---: | -[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) | - -[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) | -:---: |:---: |:---: |:---: |:---: |:---: | -[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) | - -[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) | -:---: |:---: |:---: |:---: |:---: |:---: | -[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) | - -[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) | -:---: |:---: |:---: |:---: |:---: |:---: | -[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) | - -[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) | -:---: |:---: |:---: |:---: |:---: |:---: | -[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) | - -[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) | -:---: |:---: |:---: |:---: |:---: |:---: | -[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) | - -[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) | -:---: |:---: |:---: |:---: |:---: |:---: | -[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) | - -[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) | -:---: |:---: |:---: |:---: |:---: |:---: | -[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) | - -[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) | -:---: |:---: |:---: |:---: |:---: |:---: | -[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) | - -[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) | -:---: |:---: |:---: |:---: |:---: |:---: | -[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) | - -[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) | -:---: |:---: |:---: |:---: |:---: |:---: | -[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) | - -[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) | -:---: |:---: |:---: |:---: |:---: | -[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) | - - - - -This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list) diff --git a/third_party/rust/clap/Cargo.lock b/third_party/rust/clap/Cargo.lock new file mode 100644 index 000000000000..ada324eb3de6 --- /dev/null +++ b/third_party/rust/clap/Cargo.lock @@ -0,0 +1,1019 @@ +# 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.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "backtrace" +version = "0.3.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "321629d8ba6513061f26707241fa9bc89524ff1cd7a915a97ef0c62c666ce1b6" +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 = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "lazy_static", + "memchr", + "regex-automata", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1e260c3a9040a7c19a12468758f4c16f31a81a1fe087482be9570ec864bb6c" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cast" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c24dab4283a142afa2fdca129b80ad2c6284e073930f964c3a1293c225ee39a" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "cc" +version = "1.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "2.33.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" +dependencies = [ + "bitflags", + "textwrap 0.11.0", + "unicode-width", +] + +[[package]] +name = "clap" +version = "3.0.10" +dependencies = [ + "atty", + "backtrace", + "bitflags", + "clap_derive", + "criterion", + "indexmap", + "lazy_static", + "os_str_bytes", + "regex", + "rustversion", + "strsim", + "termcolor", + "terminal_size", + "textwrap 0.14.2", + "trybuild", + "trycmd", + "unicase", + "yaml-rust", +] + +[[package]] +name = "clap_derive" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "517358c28fcef6607bf6f76108e02afad7e82297d132a6b846dcc1fc3efcd153" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "combine" +version = "4.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b2f5d0ee456f3928812dfc8c6d9a1d592b98678f6d56db9b0cd2b7bc6c8db5" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concolor-control" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7104119c2f80d887239879d0c50e033cd40eac9a3f3561e0684ba7d5d654f4da" +dependencies = [ + "atty", + "bitflags", + "concolor-query", +] + +[[package]] +name = "concolor-query" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad159cc964ac8f9d407cbc0aa44b02436c054b541f2b4b5f06972e1efdc54bc7" + +[[package]] +name = "criterion" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10" +dependencies = [ + "atty", + "cast", + "clap 2.33.3", + "criterion-plot", + "csv", + "itertools", + "lazy_static", + "num-traits", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_cbor", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec02e091aa634e2c3ada4a392989e7c3116673ef0ac5b72232439094d73b7fd" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "lazy_static", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +dependencies = [ + "cfg-if", + "lazy_static", +] + +[[package]] +name = "csv" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" +dependencies = [ + "bstr", + "csv-core", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[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 = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + +[[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.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac34a56cfd4acddb469cc7fff187ed5ac36f498ba085caf8bbc725e3ff474058" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "indexmap" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "itertools" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "js-sys" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc9ffccd38c451a86bf13657df244e9c3f37493cce8e5e21e940963777acc84" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "kstring" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b310ccceade8121d7d77fee406160e457c2f4e7c7982d589da3499bc7ea4526" +dependencies = [ + "serde", +] + +[[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.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbe5e23404da5b4f555ef85ebed98fb4083e55a00c317800bc2a50ede9f3d219" + +[[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.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" + +[[package]] +name = "memoffset" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59accc507f1338036a0477ef61afdae33cde60840f4dfe481319ce3ad116ddf9" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +dependencies = [ + "adler", + "autocfg", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67ac1d3f9a1d3616fd9a60c8d74296f22406a238b6a72f5cc1e6f314df4ffbf9" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" + +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" + +[[package]] +name = "os_pipe" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e3492ebca331b895fe23ed427dce2013d9b2e00c45964f12040b0db38b8ab27" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" +dependencies = [ + "memchr", +] + +[[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", +] + +[[package]] +name = "plotters-backend" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" + +[[package]] +name = "plotters-svg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" +dependencies = [ + "plotters-backend", +] + +[[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.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rayon" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06aca804d41dbc8ba42dfd964f0d01334eceb64314b9ecf7c5fad5188a06d90" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78120e2c850279833f1dd3582f730c4ab53ed95aeaaaa862a2a5c71b1656d8e" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "lazy_static", + "num_cpus", +] + +[[package]] +name = "regex" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" + +[[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 = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b3909d758bb75c79f23d4736fac9433868679d3ad2ea7a61e3c25cfda9a088" + +[[package]] +name = "ryu" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "semver" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "568a8e6258aa33c13358f81fd834adb854c6f7c9468520910a9b1e8fac068012" + +[[package]] +name = "serde" +version = "1.0.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_cbor" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" +dependencies = [ + "half", + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e466864e431129c7e0d3476b92f20458e5879919a0596c6472738d9fa2d342f8" +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 = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "termcolor" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" +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.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "textwrap" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80" +dependencies = [ + "terminal_size", + "unicode-width", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "toml" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2d523490d6542d4ffa1f1a7cae4d0c9f2ee634bf4e779b0f5ff5fde74dd4b6" +dependencies = [ + "combine", + "indexmap", + "itertools", + "kstring", + "serde", +] + +[[package]] +name = "trybuild" +version = "1.0.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "150e726dc059e6fbd4fce3288f5bb3cf70128cf63b0dde23b938a3cad810fb23" +dependencies = [ + "glob", + "lazy_static", + "serde", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "trycmd" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a03bb057469ddca02e598e6c84e771bfdc464f188803d3101f133d6643e638d" +dependencies = [ + "concolor-control", + "difflib", + "escargot", + "glob", + "humantime", + "humantime-serde", + "normalize-line-endings", + "os_pipe", + "rayon", + "serde", + "shlex", + "toml_edit", + "wait-timeout", + "yansi", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "version_check" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +dependencies = [ + "same-file", + "winapi", + "winapi-util", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "632f73e236b219150ea279196e54e610f5dbafa5d61786303d4da54f84e47fce" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a317bf8f9fba2476b4b2c85ef4c4af8ff39c3c7f0cdfeed4f82c34a880aa837b" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56146e7c495528bf6587663bea13a8eb588d39b36b679d83972e1a2dbbdacf9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7803e0eea25835f8abdc585cd3021b3deb11543c6fe226dcd30b228857c5c5ab" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0237232789cf037d5480773fe568aac745bfe2afbc11a863e97901780a6b47cc" + +[[package]] +name = "web-sys" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38eb105f1c59d9eaa6b5cdc92b859d85b926e82cb2e0945cd0c9259faa6fe9fb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fc79f4a1e39857fc00c3f662cbf2651c771f00e9c15fe2abc341806bd46bd71" diff --git a/third_party/rust/clap/Cargo.toml b/third_party/rust/clap/Cargo.toml index bb6bf093205f..bce95fe3e0f0 100644 --- a/third_party/rust/clap/Cargo.toml +++ b/third_party/rust/clap/Cargo.toml @@ -3,130 +3,411 @@ # 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 = "clap" -version = "2.34.0" -authors = ["Kevin K. "] -exclude = ["examples/*", "clap-test/*", "tests/*", "benches/*", "*.png", "clap-perf/*", "*.dot"] -description = "A simple to use, efficient, and full-featured Command Line Argument Parser\n" -homepage = "https://clap.rs/" +version = "3.0.10" +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" +license = "MIT OR Apache-2.0" repository = "https://github.com/clap-rs/clap" [package.metadata.docs.rs] -features = ["doc"] +cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples=examples"] +features = ["unstable-doc"] +rustdoc-args = ["--cfg", "docsrs"] + +[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" +min = 1 +replace = "{{version}}" +search = "Unreleased" + +[[package.metadata.release.pre-release-replacements]] +exactly = 1 +file = "CHANGELOG.md" +replace = "...{{tag_name}}" +search = "\\.\\.\\.HEAD" + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +min = 1 +replace = "{{date}}" +search = "ReleaseDate" + +[[package.metadata.release.pre-release-replacements]] +exactly = 1 +file = "CHANGELOG.md" +replace = "\n## [Unreleased] - ReleaseDate\n" +search = "" + +[[package.metadata.release.pre-release-replacements]] +exactly = 1 +file = "CHANGELOG.md" +replace = "\n[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD" +search = "" + +[[package.metadata.release.pre-release-replacements]] +exactly = 9 +file = "README.md" +prerelease = true +replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" +search = "github.com/clap-rs/clap/blob/[^/]+/" + +[[package.metadata.release.pre-release-replacements]] +exactly = 1 +file = "README.md" +prerelease = true +replace = "version = \"{{version}}\"" +search = "version = \"[a-z0-9\\.-]+\"" + +[[package.metadata.release.pre-release-replacements]] +exactly = 4 +file = "src/derive.rs" +prerelease = true +replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" +search = "github.com/clap-rs/clap/blob/[^/]+/" [profile.bench] -opt-level = 3 lto = true codegen-units = 1 -debug = false -debug-assertions = false -rpath = false - -[profile.dev] -opt-level = 0 -lto = false -codegen-units = 4 -debug = true -debug-assertions = true -rpath = false - -[profile.release] -opt-level = 3 -lto = true -codegen-units = 1 -debug = false -debug-assertions = false -rpath = false [profile.test] opt-level = 1 -lto = false -codegen-units = 4 -debug = true -debug-assertions = true -rpath = false + +[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 = "keyvalue-derive" +required-features = ["derive"] + +[[example]] +name = "busybox" +path = "examples/multicall-busybox.rs" +required-features = ["unstable-multicall"] + +[[example]] +name = "hostname" +path = "examples/multicall-hostname.rs" +required-features = ["unstable-multicall"] + +[[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" +required-features = ["cargo"] + +[[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_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_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_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"] + +[[bench]] +name = "01_default" +path = "benches/01_default.rs" +harness = false + +[[bench]] +name = "02_simple" +path = "benches/02_simple.rs" +harness = false + +[[bench]] +name = "03_complex" +path = "benches/03_complex.rs" +harness = false + +[[bench]] +name = "04_new_help" +path = "benches/04_new_help.rs" +harness = false + +[[bench]] +name = "05_ripgrep" +path = "benches/05_ripgrep.rs" +harness = false + +[[bench]] +name = "06_rustup" +path = "benches/06_rustup.rs" +harness = false [dependencies.atty] -version = "0.2.2" +version = "0.2" +optional = true + +[dependencies.backtrace] +version = "0.3" optional = true [dependencies.bitflags] +version = "1.2" + +[dependencies.clap_derive] +version = "3.0.0" +optional = true + +[dependencies.indexmap] version = "1.0" -[dependencies.clippy] -version = "~0.0.166" +[dependencies.lazy_static] +version = "1" +optional = true + +[dependencies.os_str_bytes] +version = "6.0" + +[dependencies.regex] +version = "1.0" optional = true [dependencies.strsim] -version = "0.8" +version = "0.10" optional = true -[dependencies.term_size] -version = "0.3.0" +[dependencies.termcolor] +version = "1.1.1" +optional = true + +[dependencies.terminal_size] +version = "0.1.12" optional = true [dependencies.textwrap] -version = "0.11.0" +version = "0.14.0" +features = [] +default-features = false -[dependencies.unicode-width] -version = "0.1.4" - -[dependencies.vec_map] -version = "0.8" +[dependencies.unicase] +version = "2.6" optional = true [dependencies.yaml-rust] -version = "0.3.5" +version = "0.4.1" optional = true -[dev-dependencies.lazy_static] -version = "1.3" +[dev-dependencies.criterion] +version = "0.3.2" -[dev-dependencies.regex] +[dev-dependencies.lazy_static] version = "1" -[dev-dependencies.version-sync] -version = "0.8" +[dev-dependencies.regex] +version = "1.0" + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.trybuild] +version = "1.0.18" + +[dev-dependencies.trycmd] +version = "0.9" +features = ["color-auto", "diff", "examples"] +default-features = false [features] -color = ["ansi_term", "atty"] -debug = [] -default = ["suggestions", "color", "vec_map"] -doc = ["yaml"] -nightly = [] -no_cargo = [] +cargo = ["lazy_static"] +color = ["atty", "termcolor"] +debug = ["clap_derive/debug", "backtrace"] +default = ["std", "color", "suggestions"] +derive = ["clap_derive", "lazy_static"] +env = [] +std = ["indexmap/std"] suggestions = ["strsim"] -unstable = [] -wrap_help = ["term_size", "textwrap/term_size"] +unicode = ["textwrap/unicode-width", "unicase"] +unstable-doc = ["derive", "cargo", "wrap_help", "yaml", "env", "unicode", "regex", "unstable-replace", "unstable-multicall", "unstable-grouped"] +unstable-grouped = [] +unstable-multicall = [] +unstable-replace = [] +wrap_help = ["terminal_size", "textwrap/terminal_size"] yaml = ["yaml-rust"] -[target."cfg(not(windows))".dependencies.ansi_term] -version = "0.12" -optional = true -[badges.appveyor] -repository = "clap-rs/clap" - -[badges.coveralls] -branch = "master" -repository = "clap-rs/clap" - -[badges.is-it-maintained-issue-resolution] -repository = "clap-rs/clap" - -[badges.is-it-maintained-open-issues] -repository = "clap-rs/clap" - -[badges.maintenance] -status = "actively-developed" - -[badges.travis-ci] -repository = "clap-rs/clap" diff --git a/third_party/rust/clap/LICENSE-APACHE b/third_party/rust/clap/LICENSE-APACHE new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/third_party/rust/clap/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/third_party/rust/clap/README.md b/third_party/rust/clap/README.md index 64085b959adf..808568427931 100644 --- a/third_party/rust/clap/README.md +++ b/third_party/rust/clap/README.md @@ -1,542 +1,158 @@ -clap -==== + +# clap -[![Crates.io](https://img.shields.io/crates/v/clap.svg)](https://crates.io/crates/clap) [![Crates.io](https://img.shields.io/crates/d/clap.svg)](https://crates.io/crates/clap) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/clap-rs/clap/blob/master/LICENSE-MIT) [![Coverage Status](https://coveralls.io/repos/kbknapp/clap-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/kbknapp/clap-rs?branch=master) [![Join the chat at https://gitter.im/kbknapp/clap-rs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kbknapp/clap-rs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +> **Command Line Argument Parser for Rust** -Linux: [![Build Status](https://travis-ci.org/clap-rs/clap.svg?branch=master)](https://travis-ci.org/clap-rs/clap) -Windows: [![Build status](https://ci.appveyor.com/api/projects/status/ejg8c33dn31nhv36/branch/master?svg=true)](https://ci.appveyor.com/project/kbknapp/clap-rs/branch/master) +[![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.0.10/LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/v3.0.10/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) -Command Line Argument Parser for Rust +Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). -It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing console/terminal applications. - -* [documentation](https://docs.rs/clap/) -* [website](https://clap.rs/) -* [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U) - -Table of Contents -================= - -* [About](#about) -* [FAQ](#faq) -* [Features](#features) -* [Quick Example](#quick-example) -* [Try it!](#try-it) - * [Pre-Built Test](#pre-built-test) - * [BYOB (Build Your Own Binary)](#byob-build-your-own-binary) -* [Usage](#usage) - * [Optional Dependencies / Features](#optional-dependencies--features) - * [Dependencies Tree](#dependencies-tree) - * [More Information](#more-information) - * [Video Tutorials](#video-tutorials) -* [How to Contribute](#how-to-contribute) - * [Compatibility Policy](#compatibility-policy) - * [Minimum Version of Rust](#minimum-version-of-rust) -* [Related Crates](#related-crates) -* [License](#license) -* [Recent Breaking Changes](#recent-breaking-changes) - * [Deprecations](#deprecations) - -Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc) +1. [About](#about) +2. Tutorial: [Builder API](https://github.com/clap-rs/clap/blob/v3.0.10/examples/tutorial_builder/README.md), [Derive API](https://github.com/clap-rs/clap/blob/v3.0.10/examples/tutorial_derive/README.md) +3. [Examples](https://github.com/clap-rs/clap/blob/v3.0.10/examples/README.md) +4. [API Reference](https://docs.rs/clap) + - [Derive Reference](https://github.com/clap-rs/clap/blob/v3.0.10/examples/derive_ref/README.md) + - [Feature Flags](#feature-flags) +5. [CHANGELOG](https://github.com/clap-rs/clap/blob/v3.0.10/CHANGELOG.md) +6. [FAQ](https://github.com/clap-rs/clap/blob/v3.0.10/docs/FAQ.md) +7. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) +8. [Contributing](https://github.com/clap-rs/clap/blob/v3.0.10/CONTRIBUTING.md) +8. [Sponsors](#sponsors) ## About -`clap` is used to parse *and validate* the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means you focus on your *applications* functionality, and less on the parsing and validating of arguments. +Create your command-line parser, with all of the bells and whistles, declaratively or procedurally. -`clap` provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, `clap` will also auto-generate a `help` subcommand and separate associated help messages. +### Example -Once `clap` parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, `clap` informs them with a friendly message and exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution. + +```rust,no_run +use clap::Parser; -## FAQ +/// 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)] + name: String, -For a full FAQ and more in depth details, see [the wiki page](https://github.com/clap-rs/clap/wiki/FAQ) - -### 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! - -#### How does `clap` compare to [getopts](https://github.com/rust-lang-nursery/getopts)? - -`getopts` is a very basic, fairly minimalist argument parsing library. This isn't a bad thing, sometimes you don't need tons of features, you just want to parse some simple arguments, and have some help text generated for you based on valid arguments you specify. The downside to this approach is that you must manually implement most of the common features (such as checking to display help messages, usage strings, etc.). If you want a highly custom argument parser, and don't mind writing the majority of the functionality yourself, `getopts` is an excellent base. - -`getopts` also doesn't allocate much, or at all. This gives it a very small performance boost. Although, as you start implementing additional features, that boost quickly disappears. - -Personally, I find many, many uses of `getopts` are manually implementing features that `clap` provides by default. Using `clap` simplifies your codebase allowing you to focus on your application, and not argument parsing. - -#### How does `clap` compare to [docopt.rs](https://github.com/docopt/docopt.rs)? - -I first want to say I'm a big a fan of BurntSushi's work, the creator of `Docopt.rs`. I aspire to produce the quality of libraries that this man does! When it comes to comparing these two libraries they are very different. `docopt` tasks you with writing a help message, and then it parsers that message for you to determine all valid arguments and their use. Some people LOVE this approach, others do not. If you're willing to write a detailed help message, it's nice that you can stick that in your program and have `docopt` do the rest. On the downside, it's far less flexible. - -`docopt` is also excellent at translating arguments into Rust types automatically. There is even a syntax extension which will do all this for you, if you're willing to use a nightly compiler (use of a stable compiler requires you to somewhat manually translate from arguments to Rust types). To use BurntSushi's words, `docopt` is also a sort of black box. You get what you get, and it's hard to tweak implementation or customize the experience for your use case. - -Because `docopt` is doing a ton of work to parse your help messages and determine what you were trying to communicate as valid arguments, it's also one of the more heavy weight parsers performance-wise. For most applications this isn't a concern and this isn't to say `docopt` is slow, in fact far from it. This is just something to keep in mind while comparing. - -#### All else being equal, 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. - -#### All else being equal, 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 fine-tuning 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. Finally, `clap` is "stringly typed" when referring to arguments which can cause typos in code. This particular paper-cut is being actively worked on, and should be gone in v3.x. - -## Features - -Below are a few of the features which `clap` supports, full descriptions and usage can be found in the [documentation](https://docs.rs/clap/) and [examples/](examples) directory - -* **Auto-generated Help, Version, and Usage information** - - Can optionally be fully, or partially overridden if you want a custom help, version, or usage statements -* **Auto-generated completion scripts at compile time (Bash, Zsh, Fish, and PowerShell)** - - Even works through many multiple levels of subcommands - - Works with options which only accept certain values - - Works with subcommand aliases -* **Flags / Switches** (i.e. bool fields) - - Both short and long versions supported (i.e. `-f` and `--flag` respectively) - - Supports combining short versions (i.e. `-fBgoZ` is the same as `-f -B -g -o -Z`) - - Supports multiple occurrences (i.e. `-vvv` or `-v -v -v`) -* **Positional Arguments** (i.e. those which are based off an index from the program name) - - Supports multiple values (i.e. `myprog ...` such as `myprog file1.txt file2.txt` being two values for the same "file" argument) - - Supports Specific Value Sets (See below) - - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values) - - Can set custom validations on values to extend the argument parsing capability to truly custom domains -* **Option Arguments** (i.e. those that take values) - - Both short and long versions supported (i.e. `-o value`, `-ovalue`, `-o=value` and `--option value` or `--option=value` respectively) - - Supports multiple values (i.e. `-o -o ` or `-o `) - - Supports delimited values (i.e. `-o=val1,val2,val3`, can also change the delimiter) - - Supports Specific Value Sets (See below) - - Supports named values so that the usage/help info appears as `-o ` etc. for when you require specific multiple values - - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values) - - Can set custom validations on values to extend the argument parsing capability to truly custom domains -* **Sub-Commands** (i.e. `git add ` where `add` is a sub-command of `git`) - - Support their own sub-arguments, and sub-sub-commands independent of the parent - - Get their own auto-generated Help, Version, and Usage independent of parent -* **Support for building CLIs from YAML** - This keeps your Rust source nice and tidy and makes supporting localized translation very simple! -* **Requirement Rules**: Arguments can define the following types of requirement rules - - Can be required by default - - Can be required only if certain arguments are present - - Can require other arguments to be present - - Can be required only if certain values of other arguments are used -* **Confliction Rules**: Arguments can optionally define the following types of exclusion rules - - Can be disallowed when certain arguments are present - - Can disallow use of other arguments when present -* **Groups**: Arguments can be made part of a group - - Fully compatible with other relational rules (requirements, conflicts, and overrides) which allows things like requiring the use of any arg in a group, or denying the use of an entire group conditionally -* **Specific Value Sets**: Positional or Option Arguments can define a specific set of allowed values (i.e. imagine a `--mode` option which may *only* have one of two values `fast` or `slow` such as `--mode fast` or `--mode slow`) -* **Default Values** - - Also supports conditional default values (i.e. a default which only applies if specific arguments are used, or specific values of those arguments) -* **Automatic Version from Cargo.toml**: `clap` is fully compatible with Rust's `env!()` macro for automatically setting the version of your application to the version in your Cargo.toml. See [09_auto_version example](examples/09_auto_version.rs) for how to do this (Thanks to [jhelwig](https://github.com/jhelwig) for pointing this out) -* **Typed Values**: You can use several convenience macros provided by `clap` to get typed values (i.e. `i32`, `u8`, etc.) from positional or option arguments so long as the type you request implements `std::str::FromStr` See the [12_typed_values example](examples/12_typed_values.rs). You can also use `clap`s `arg_enum!` macro to create an enum with variants that automatically implement `std::str::FromStr`. See [13a_enum_values_automatic example](examples/13a_enum_values_automatic.rs) for details -* **Suggestions**: Suggests corrections when the user enters a typo. For example, if you defined a `--myoption` argument, and the user mistakenly typed `--moyption` (notice `y` and `o` transposed), they would receive a `Did you mean '--myoption'?` error and exit gracefully. This also works for subcommands and flags. (Thanks to [Byron](https://github.com/Byron) for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features') -* **Colorized Errors (Non Windows OS only)**: Error message are printed in in colored text (this feature can optionally be disabled, see 'Optional Dependencies / Features'). -* **Global Arguments**: Arguments can optionally be defined once, and be available to all child subcommands. There values will also be propagated up/down throughout all subcommands. -* **Custom Validations**: You can define a function to use as a validator of argument values. Imagine defining a function to validate IP addresses, or fail parsing upon error. This means your application logic can be solely focused on *using* values. -* **POSIX Compatible Conflicts/Overrides** - In POSIX args can be conflicting, but not fail parsing because whichever arg comes *last* "wins" so to speak. This allows things such as aliases (i.e. `alias ls='ls -l'` but then using `ls -C` in your terminal which ends up passing `ls -l -C` as the final arguments. Since `-l` and `-C` aren't compatible, this effectively runs `ls -C` in `clap` if you choose...`clap` also supports hard conflicts that fail parsing). (Thanks to [Vinatorul](https://github.com/Vinatorul)!) -* Supports the Unix `--` meaning, only positional arguments follow - -## Quick Example - -The following examples show a quick example of some of the very basic functionality of `clap`. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the [documentation](https://docs.rs/clap/), [examples/](examples) directory of this repository or the [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U). - - **NOTE:** All of these examples are functionally the same, but show different styles in which to use `clap`. These different styles are purely a matter of personal preference. - -The first example shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired. - -```rust -// (Full example with detailed comments in examples/01b_quick_example.rs) -// -// This example demonstrates clap's full 'builder pattern' style of creating arguments which is -// more verbose, but allows easier editing, and at times more advanced options, or the possibility -// to generate arguments dynamically. -extern crate clap; -use clap::{Arg, App, SubCommand}; + /// Number of times to greet + #[clap(short, long, default_value_t = 1)] + count: u8, +} fn main() { - let matches = App::new("My Super Program") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .arg(Arg::with_name("config") - .short("c") - .long("config") - .value_name("FILE") - .help("Sets a custom config file") - .takes_value(true)) - .arg(Arg::with_name("INPUT") - .help("Sets the input file to use") - .required(true) - .index(1)) - .arg(Arg::with_name("v") - .short("v") - .multiple(true) - .help("Sets the level of verbosity")) - .subcommand(SubCommand::with_name("test") - .about("controls testing features") - .version("1.3") - .author("Someone E. ") - .arg(Arg::with_name("debug") - .short("d") - .help("print debug information verbosely"))) - .get_matches(); + let args = Args::parse(); - // Gets a value for config if supplied by user, or defaults to "default.conf" - let config = matches.value_of("config").unwrap_or("default.conf"); - println!("Value for config: {}", config); - - // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't - // required we could have used an 'if let' to conditionally get the value) - println!("Using input file: {}", matches.value_of("INPUT").unwrap()); - - // Vary the output based on how many times the user used the "verbose" flag - // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' - match matches.occurrences_of("v") { - 0 => println!("No verbose info"), - 1 => println!("Some verbose info"), - 2 => println!("Tons of verbose info"), - 3 | _ => println!("Don't be crazy"), + for _ in 0..args.count { + println!("Hello {}!", args.name) } - - // You can handle information about subcommands by requesting their matches by name - // (as below), requesting just the name used, or both at the same time - if let Some(matches) = matches.subcommand_matches("test") { - if matches.is_present("debug") { - println!("Printing debug info..."); - } else { - println!("Printing normally..."); - } - } - - // more program logic goes here... } ``` - -One could also optionally declare their CLI in YAML format and keep your Rust source tidy -or support multiple localized translations by having different YAML files for each localization. - -First, create the `cli.yml` file to hold your CLI options, but it could be called anything we like: - -```yaml -name: myapp -version: "1.0" -author: Kevin K. -about: Does awesome things -args: - - config: - short: c - long: config - value_name: FILE - help: Sets a custom config file - takes_value: true - - INPUT: - help: Sets the input file to use - required: true - index: 1 - - verbose: - short: v - multiple: true - help: Sets the level of verbosity -subcommands: - - test: - about: controls testing features - version: "1.3" - author: Someone E. - args: - - debug: - short: d - help: print debug information +Add this to `Cargo.toml`: +```toml +[dependencies] +clap = { version = "3.0.10", features = ["derive"] } ``` +```bash +$ demo --help +clap [..] -Since this feature requires additional dependencies that not everyone may want, it is *not* compiled in by default and we need to enable a feature flag in Cargo.toml: - -Simply change your `clap = "2.34"` to `clap = {version = "2.34", features = ["yaml"]}`. - -Finally we create our `main.rs` file just like we would have with the previous two examples: - -```rust -// (Full example with detailed comments in examples/17_yaml.rs) -// -// This example demonstrates clap's building from YAML style of creating arguments which is far -// more clean, but takes a very small performance hit compared to the other two methods. -#[macro_use] -extern crate clap; -use clap::App; - -fn main() { - // The YAML file is found relative to the current file, similar to how modules are found - let yaml = load_yaml!("cli.yml"); - let matches = App::from_yaml(yaml).get_matches(); - - // Same as previous examples... -} -``` - -If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or `help` subcommand, since we defined `test` as a subcommand) the following would be output - -```sh -$ myprog --help -My Super Program 1.0 -Kevin K. -Does awesome things +A simple to use, efficient, and full-featured Command Line Argument Parser USAGE: - MyApp [FLAGS] [OPTIONS] [SUBCOMMAND] - -FLAGS: - -h, --help Prints help information - -v Sets the level of verbosity - -V, --version Prints version information + demo[EXE] [OPTIONS] --name OPTIONS: - -c, --config Sets a custom config file - -ARGS: - INPUT The input file to use - -SUBCOMMANDS: - help Prints this message or the help of the given subcommand(s) - test Controls testing features + -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)* -**NOTE:** You could also run `myapp test --help` or `myapp help test` to see the help message for the `test` subcommand. +### Aspirations -There are also two other methods to create CLIs. Which style you choose is largely a matter of personal preference. The two other methods are: +- 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.54.0) -* Using [usage strings (examples/01a_quick_example.rs)](examples/01a_quick_example.rs) similar to (but not exact) docopt style usage statements. This is far less verbose than the above methods, but incurs a slight runtime penalty. -* Using [a macro (examples/01c_quick_example.rs)](examples/01c_quick_example.rs) which is like a hybrid of the builder and usage string style. It's less verbose, but doesn't incur the runtime penalty of the usage string style. The downside is that it's harder to debug, and more opaque. +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. -Examples of each method can be found in the [examples/](examples) directory of this repository. +### Related Projects -## Try it! +- [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) +- [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) -### Pre-Built Test +## Feature Flags -To try out the pre-built examples, use the following steps: +### Default Features -* Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/` -* Compile the example `$ cargo build --example ` -* Run the help info `$ ./target/debug/examples/ --help` -* Play with the arguments! -* You can also do a onetime run via `$ cargo run --example -- [args to example]` +* **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. -### BYOB (Build Your Own Binary) +#### Optional features -To test out `clap`'s default auto-generated help/version follow these steps: -* Create a new cargo project `$ cargo new fake --bin && cd fake` -* Add `clap` to your `Cargo.toml` +* **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. -```toml -[dependencies] -clap = "2" -``` +#### Experimental features -* Add the following to your `src/main.rs` +**Warning:** These may contain breaking changes between minor releases. -```rust -extern crate clap; -use clap::App; +* **unstable-replace**: Enable [`App::replace`](https://github.com/clap-rs/clap/issues/2836) +* **unstable-multicall**: Enable [`AppSettings::Multicall`](https://github.com/clap-rs/clap/issues/2861) +* **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) -fn main() { - App::new("fake").version("v1.0-beta").get_matches(); -} -``` +## Sponsors -* Build your program `$ cargo build --release` -* Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake --version` + +### Gold -## Usage +[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) -For full usage, add `clap` as a dependency in your `Cargo.toml` () to use from crates.io: + +### Silver -```toml -[dependencies] -clap = "~2.34" -``` +[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) -(**note**: If you are concerned with supporting a minimum version of Rust that is *older* than the current stable Rust minus 2 stable releases, it's recommended to use the `~major.minor.patch` style versions in your `Cargo.toml` which will only update the patch version automatically. For more information see the [Compatibility Policy](#compatibility-policy)) + +### Bronze -Then add `extern crate clap;` to your crate root. +[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) -Define a list of valid arguments for your program (see the [documentation](https://docs.rs/clap/) or [examples/](examples) directory of this repo) + +### Backer -Then run `cargo build` or `cargo update && cargo build` for your project. - -### Optional Dependencies / Features - -#### Features enabled by default - -* **"suggestions"**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`) -* **"color"**: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` only on non-Windows targets) -* **"vec_map"**: Use [`VecMap`](https://crates.io/crates/vec_map) internally instead of a [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html). This feature provides a _slight_ performance improvement. (builds dependency `vec_map`) - -To disable these, add this to your `Cargo.toml`: - -```toml -[dependencies.clap] -version = "2.34" -default-features = false -``` - -You can also selectively enable only the features you'd like to include, by adding: - -```toml -[dependencies.clap] -version = "2.34" -default-features = false - -# Cherry-pick the features you'd like to use -features = [ "suggestions", "color" ] -``` - -#### Opt-in features - -* **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`) -* **"unstable"**: Enables unstable `clap` features that may change from release to release -* **"wrap_help"**: Turns on the help text wrapping feature, based on the terminal size. (builds dependency `term-size`) - -### Dependencies Tree - -The following graphic depicts `clap`s dependency graph (generated using [cargo-graph](https://github.com/kbknapp/cargo-graph)). - - * **Dashed** Line: Optional dependency - * **Red** Color: **NOT** included by default (must use cargo `features` to enable) - * **Blue** Color: Dev dependency, only used while developing. - -![clap dependencies](clap_dep_graph.png) - -### More Information - -You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project. - -You can also find usage examples in the [examples/](examples) directory of this repo. - -#### Video Tutorials - -There's also the video tutorial series [Argument Parsing with Rust v2](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U). - -These videos slowly trickle out as I finish them and currently a work in progress. - -## How to Contribute - -Details on how to contribute can be found in the [CONTRIBUTING.md](.github/CONTRIBUTING.md) file. - -### Compatibility Policy - -Because `clap` takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust. - -`clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version of `clap` will be bumped. - -In order to keep from being surprised of breaking changes, it is **highly** recommended to use the `~major.minor.patch` style in your `Cargo.toml` only if you wish to target a version of Rust that is *older* than current stable minus two releases: - -```toml -[dependencies] -clap = "~2.34" -``` - -This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore cannot break due to new features, or bumped minimum versions of Rust. - -#### Warning about '~' Dependencies - -Using `~` can cause issues in certain circumstances. - -From @alexcrichton: - -Right now Cargo's version resolution is pretty naive, it's just a brute-force search of the solution space, returning the first resolvable graph. This also means that it currently won't terminate until it proves there is not possible resolvable graph. This leads to situations where workspaces with multiple binaries, for example, have two different dependencies such as: - -```toml,no_sync - -# In one Cargo.toml -[dependencies] -clap = "~2.34.0" - -# In another Cargo.toml -[dependencies] -clap = "2.34.0" -``` - -This is inherently an unresolvable crate graph in Cargo right now. Cargo requires there's only one major version of a crate, and being in the same workspace these two crates must share a version. This is impossible in this location, though, as these version constraints cannot be met. - -#### Minimum Version of Rust - -`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.41.0, meaning `clap` is guaranteed to compile with 1.39.0 and beyond. - -At the 1.42.0 stable release, `clap` will be guaranteed to compile with 1.40.0 and beyond, etc. - -Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be clearly annotated in the `CHANGELOG.md` - -#### Breaking Changes - -`clap` takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions: - - * The breaking change is to fix a security concern - * The breaking change is to be fixing a bug (i.e. relying on a bug as a feature) - * The breaking change is a feature isn't used in the wild, or all users of said feature have given approval *prior* to the change - -#### Compatibility with Wasm - -A best effort is made to ensure that `clap` will work on projects targeting `wasm32-unknown-unknown`. However there is no dedicated CI build -covering this specific target. - -## License - -`clap` is licensed under the MIT license. Please read the [LICENSE-MIT](LICENSE-MIT) file in this repository for more information. - -## Related Crates - -There are several excellent crates which can be used with `clap`, I recommend checking them all out! If you've got a crate that would be a good fit to be used with `clap` open an issue and let me know, I'd love to add it! - -* [`structopt`](https://github.com/TeXitoi/structopt) - This crate allows you to define a struct, and build a CLI from it! No more "stringly typed" and it uses `clap` behind the scenes! (*Note*: There is work underway to pull this crate into mainline `clap`). -* [`assert_cli`](https://github.com/assert-rs/assert_cli) - This crate allows you test your CLIs in a very intuitive and functional way! - -## Recent Breaking Changes - -`clap` follows semantic versioning, so breaking changes should only happen upon major version bumps. The only exception to this rule is breaking changes that happen due to implementation that was deemed to be a bug, security concerns, or it can be reasonably proved to affect no code. For the full details, see [CHANGELOG.md](./CHANGELOG.md). - -As of 2.27.0: - -* Argument values now take precedence over subcommand names. This only arises by using unrestrained multiple values and subcommands together where the subcommand name can coincide with one of the multiple values. Such as `$ prog ... `. The fix is to place restraints on number of values, or disallow the use of `$ prog ` structure. - -As of 2.0.0 (From 1.x) - -* **Fewer lifetimes! Yay!** - * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>` - * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>` - * `ArgMatches<'a, 'b>` => `ArgMatches<'a>` -* **Simply Renamed** - * `App::arg_group` => `App::group` - * `App::arg_groups` => `App::groups` - * `ArgGroup::add` => `ArgGroup::arg` - * `ArgGroup::add_all` => `ArgGroup::args` - * `ClapError` => `Error` - * struct field `ClapError::error_type` => `Error::kind` - * `ClapResult` => `Result` - * `ClapErrorType` => `ErrorKind` -* **Removed Deprecated Functions and Methods** - * `App::subcommands_negate_reqs` - * `App::subcommand_required` - * `App::arg_required_else_help` - * `App::global_version(bool)` - * `App::versionless_subcommands` - * `App::unified_help_messages` - * `App::wait_on_error` - * `App::subcommand_required_else_help` - * `SubCommand::new` - * `App::error_on_no_subcommand` - * `Arg::new` - * `Arg::mutually_excludes` - * `Arg::mutually_excludes_all` - * `Arg::mutually_overrides_with` - * `simple_enum!` -* **Renamed Error Variants** - * `InvalidUnicode` => `InvalidUtf8` - * `InvalidArgument` => `UnknownArgument` -* **Usage Parser** - * Value names can now be specified inline, i.e. `-o, --option 'some option which takes two files'` - * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code** -* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code) -* `crate_version!` returns `&'static str` instead of `String` - -### Deprecations - -Old method names will be left around for several minor version bumps, or one major version bump. - -As of 2.27.0: - -* **AppSettings::PropagateGlobalValuesDown:** this setting deprecated and is no longer required to propagate values down or up +[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) diff --git a/third_party/rust/clap/SPONSORS.md b/third_party/rust/clap/SPONSORS.md deleted file mode 100644 index 67f5544f9b46..000000000000 --- a/third_party/rust/clap/SPONSORS.md +++ /dev/null @@ -1,17 +0,0 @@ -Below is a list of sponsors for the clap-rs project - -If you are interested in becoming a sponsor for this project please our [sponsorship page](https://clap.rs/sponsorship/). - -## Recurring Sponsors: - -| [Noelia Seva-Gonzalez](https://noeliasg.com/about/) | [messense](https://github.com/messense) | [Josh](https://joshtriplett.org) | Stephen Oats | -|:-:|:-:|:-:|:-:| -|Noelia Seva-Gonzalez | Messense | Josh Triplett | Stephen Oats | - - -## Single-Donation and Former Sponsors: - -| [Rob Tsuk](https://github.com/rtsuk)| | | -|:-:|:-:|:-:| -|Rob Tsuk| | | - diff --git a/third_party/rust/clap/benches/01_default.rs b/third_party/rust/clap/benches/01_default.rs new file mode 100644 index 000000000000..07e3ad218f80 --- /dev/null +++ b/third_party/rust/clap/benches/01_default.rs @@ -0,0 +1,15 @@ +use clap::App; +use criterion::{criterion_group, criterion_main, Criterion}; + +pub fn build_empty(c: &mut Criterion) { + c.bench_function("build_empty", |b| b.iter(|| App::new("claptests"))); +} + +pub fn parse_empty(c: &mut Criterion) { + c.bench_function("parse_empty", |b| { + b.iter(|| App::new("claptests").get_matches_from(vec![""])) + }); +} + +criterion_group!(benches, build_empty, parse_empty); +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/02_simple.rs b/third_party/rust/clap/benches/02_simple.rs new file mode 100644 index 000000000000..46a725bbb5ef --- /dev/null +++ b/third_party/rust/clap/benches/02_simple.rs @@ -0,0 +1,104 @@ +use clap::{arg, App, Arg}; +use criterion::{criterion_group, criterion_main, Criterion}; + +macro_rules! create_app { + () => {{ + App::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .arg(arg!(-f --flag "tests flags")) + .arg(arg!(-o --option "tests options").required(false)) + .arg(arg!([positional] "tests positional")) + }}; +} + +pub fn build_simple(c: &mut Criterion) { + c.bench_function("build_simple", |b| b.iter(|| create_app!())); +} + +pub fn build_with_flag(c: &mut Criterion) { + c.bench_function("build_with_flag", |b| { + b.iter(|| App::new("claptests").arg(arg!(-s --some "something"))) + }); +} + +pub fn build_with_flag_ref(c: &mut Criterion) { + c.bench_function("build_with_flag_ref", |b| { + b.iter(|| { + let arg = arg!(-s --some "something"); + App::new("claptests").arg(&arg) + }) + }); +} + +pub fn build_with_opt(c: &mut Criterion) { + c.bench_function("build_with_opt", |b| { + b.iter(|| App::new("claptests").arg(arg!(-s --some "something"))) + }); +} + +pub fn build_with_opt_ref(c: &mut Criterion) { + c.bench_function("build_with_opt_ref", |b| { + b.iter(|| { + let arg = arg!(-s --some "something"); + App::new("claptests").arg(&arg) + }) + }); +} + +pub fn build_with_pos(c: &mut Criterion) { + c.bench_function("build_with_pos", |b| { + b.iter(|| App::new("claptests").arg(Arg::new("some"))) + }); +} + +pub fn build_with_pos_ref(c: &mut Criterion) { + c.bench_function("build_with_pos_ref", |b| { + b.iter(|| { + let arg = Arg::new("some"); + App::new("claptests").arg(&arg) + }) + }); +} + +pub fn parse_simple_with_flag(c: &mut Criterion) { + c.bench_function("parse_simple_with_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-f"])) + }); +} + +pub fn parse_simple_with_opt(c: &mut Criterion) { + c.bench_function("parse_simple_with_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1"])) + }); +} + +pub fn parse_simple_with_pos(c: &mut Criterion) { + c.bench_function("parse_simple_with_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "arg1"])) + }); +} + +pub fn parse_simple_with_complex(c: &mut Criterion) { + c.bench_function("parse_simple_with_complex", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1", "-f", "arg1"])) + }); +} + +criterion_group!( + benches, + parse_simple_with_complex, + parse_simple_with_pos, + parse_simple_with_opt, + parse_simple_with_flag, + build_with_pos_ref, + build_with_pos, + build_with_opt_ref, + build_with_opt, + build_with_flag_ref, + build_with_flag, + build_simple +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/03_complex.rs b/third_party/rust/clap/benches/03_complex.rs new file mode 100644 index 000000000000..377d60ccc21a --- /dev/null +++ b/third_party/rust/clap/benches/03_complex.rs @@ -0,0 +1,307 @@ +use clap::{arg, App, AppSettings, Arg}; +use criterion::{criterion_group, criterion_main, Criterion}; + +static OPT3_VALS: [&str; 2] = ["fast", "slow"]; +static POS3_VALS: [&str; 2] = ["vi", "emacs"]; + +macro_rules! create_app { + () => {{ + App::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .arg(arg!(-o --option ... "tests options").required(false)) + .arg(arg!([positional] "tests positionals")) + .arg(arg!(-f --flag ... "tests flags").global(true)) + .args(&[ + arg!(flag2: -F "tests flags with exclusions") + .conflicts_with("flag") + .requires("option2"), + arg!(option2: --"long-option-2" "tests long options with exclusions") + .required(false) + .conflicts_with("option") + .requires("positional2"), + arg!([positional2] "tests positionals with exclusions"), + arg!(-O --Option "tests options with specific value sets") + .required(false) + .possible_values(OPT3_VALS), + arg!([positional3] ... "tests positionals with specific values") + .possible_values(POS3_VALS), + arg!(--multvals "Tests multiple values not mult occs").required(false).value_names(&["one", "two"]), + arg!( + --multvalsmo "Tests multiple values, not mult occs" + ).multiple_values(true).required(false).value_names(&["one", "two"]), + arg!(--minvals2 ... "Tests 2 min vals").min_values(2).multiple_values(true).required(false), + arg!(--maxvals3 ... "Tests 3 max vals").max_values(3).multiple_values(true).required(false), + ]) + .subcommand( + App::new("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. ") + .arg(arg!(-o --option ... "tests options").required(false)) + .arg(arg!([scpositional] "tests positionals")) + ) + }}; +} + +pub fn build_from_builder(c: &mut Criterion) { + c.bench_function("build_from_builder", |b| { + b.iter(|| { + App::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .arg( + Arg::new("opt") + .help("tests options") + .short('o') + .long("option") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ) + .arg(Arg::new("positional").help("tests positionals").index(1)) + .arg( + Arg::new("flag") + .short('f') + .help("tests flags") + .long("flag") + .global(true) + .multiple_occurrences(true), + ) + .arg( + Arg::new("flag2") + .short('F') + .help("tests flags with exclusions") + .conflicts_with("flag") + .requires("option2"), + ) + .arg( + Arg::new("option2") + .help("tests long options with exclusions") + .conflicts_with("option") + .requires("positional2") + .takes_value(true) + .long("long-option-2"), + ) + .arg( + Arg::new("positional2") + .index(3) + .help("tests positionals with exclusions"), + ) + .arg( + Arg::new("option3") + .short('O') + .long("Option") + .takes_value(true) + .help("tests options with specific value sets") + .possible_values(OPT3_VALS), + ) + .arg( + Arg::new("positional3") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("tests positionals with specific values") + .index(4) + .possible_values(POS3_VALS), + ) + .arg( + Arg::new("multvals") + .long("multvals") + .help("Tests multiple values, not mult occs") + .value_names(&["one", "two"]), + ) + .arg( + Arg::new("multvalsmo") + .long("multvalsmo") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests multiple values, not mult occs") + .value_names(&["one", "two"]), + ) + .arg( + Arg::new("minvals") + .long("minvals2") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests 2 min vals") + .min_values(2), + ) + .arg( + Arg::new("maxvals") + .long("maxvals3") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests 3 max vals") + .max_values(3), + ) + .subcommand( + App::new("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. ") + .arg( + Arg::new("scoption") + .short('o') + .long("option") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("tests options"), + ) + .arg(Arg::new("scpositional").index(1).help("tests positionals")), + ) + }) + }); +} + +pub fn parse_complex(c: &mut Criterion) { + c.bench_function("parse_complex", |b| { + b.iter(|| create_app!().get_matches_from(vec![""])) + }); +} + +pub fn parse_complex_with_flag(c: &mut Criterion) { + c.bench_function("parse_complex_with_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-f"])) + }); +} + +pub fn parse_complex_with_opt(c: &mut Criterion) { + c.bench_function("parse_complex_with_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1"])) + }); +} + +pub fn parse_complex_with_pos(c: &mut Criterion) { + c.bench_function("parse_complex_with_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "arg1"])) + }); +} + +pub fn parse_complex_with_sc(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd"])) + }); +} + +pub fn parse_complex_with_sc_flag(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "-f"])) + }); +} + +pub fn parse_complex_with_sc_opt(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "-o", "option1"])) + }); +} + +pub fn parse_complex_with_sc_pos(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "arg1"])) + }); +} + +pub fn parse_complex1(c: &mut Criterion) { + c.bench_function("parse_complex1", |b| { + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "-ff", + "-o", + "option1", + "arg1", + "-O", + "fast", + "arg2", + "--multvals", + "one", + "two", + "emacs", + ]) + }) + }); +} + +pub fn parse_complex2(c: &mut Criterion) { + c.bench_function("parse_complex2", |b| { + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }) + }); +} + +pub fn parse_args_negate_scs(c: &mut Criterion) { + c.bench_function("parse_args_negate_scs", |b| { + b.iter(|| { + create_app!() + .setting(AppSettings::ArgsNegateSubcommands) + .get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }) + }); +} + +pub fn parse_complex_with_sc_complex(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_complex", |b| { + b.iter(|| { + create_app!().get_matches_from(vec!["myprog", "subcmd", "-f", "-o", "option1", "arg1"]) + }) + }); +} + +criterion_group!( + benches, + build_from_builder, + parse_complex, + parse_complex_with_flag, + parse_complex_with_opt, + parse_complex_with_pos, + parse_complex_with_sc, + parse_complex_with_sc_flag, + parse_complex_with_sc_opt, + parse_complex_with_sc_pos, + parse_complex1, + parse_complex2, + parse_args_negate_scs, + parse_complex_with_sc_complex +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/04_new_help.rs b/third_party/rust/clap/benches/04_new_help.rs new file mode 100644 index 000000000000..7a8717304a3f --- /dev/null +++ b/third_party/rust/clap/benches/04_new_help.rs @@ -0,0 +1,223 @@ +use clap::App; +use clap::{arg, Arg}; +use criterion::{criterion_group, criterion_main, Criterion}; +use std::io::Cursor; + +fn build_help(app: &mut App) -> String { + let mut buf = Cursor::new(Vec::with_capacity(50)); + app.write_help(&mut buf).unwrap(); + let content = buf.into_inner(); + String::from_utf8(content).unwrap() +} + +fn app_example1<'c>() -> App<'c> { + App::new("MyApp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .arg( + arg!( + -c --config "Sets a custom config file" + ) + .required(false), + ) + .arg(arg!( "Sets an optional output file")) + .arg(arg!(d: -d ... "Turn debugging information on")) + .subcommand( + App::new("test") + .about("does testing things") + .arg(arg!(-l --list "lists test values")), + ) +} + +fn app_example2<'c>() -> App<'c> { + App::new("MyApp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") +} + +fn app_example3<'c>() -> App<'c> { + App::new("MyApp") + .arg( + Arg::new("debug") + .help("turn on debugging information") + .short('d'), + ) + .args(&[ + Arg::new("config") + .help("sets the config file to use") + .takes_value(true) + .short('c') + .long("config"), + Arg::new("input") + .help("the input file to use") + .required(true), + ]) + .arg(arg!(--license "display the license file")) + .arg(arg!([output] "Supply an output file to use")) + .arg( + arg!( + -i --int "Set an interface to use" + ) + .required(false), + ) +} + +fn app_example4<'c>() -> App<'c> { + App::new("MyApp") + .about("Parses an input file to do awesome things") + .version("1.0") + .author("Kevin K. ") + .arg( + Arg::new("debug") + .help("turn on debugging information") + .short('d') + .long("debug"), + ) + .arg( + Arg::new("config") + .help("sets the config file to use") + .short('c') + .long("config"), + ) + .arg( + Arg::new("input") + .help("the input file to use") + .index(1) + .required(true), + ) +} + +fn app_example5<'c>() -> App<'c> { + App::new("MyApp").arg( + Arg::new("awesome") + .help("turns up the awesome") + .short('a') + .long("awesome") + .multiple_occurrences(true), + ) +} + +fn app_example6<'c>() -> App<'c> { + App::new("MyApp") + .arg( + Arg::new("input") + .help("the input file to use") + .index(1) + .requires("config") + .required(true), + ) + .arg(Arg::new("config").help("the config file to use").index(2)) +} + +fn app_example7<'c>() -> App<'c> { + App::new("MyApp") + .arg(Arg::new("config")) + .arg(Arg::new("output")) + .arg( + Arg::new("input") + .help("the input file to use") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .required(true) + .short('i') + .long("input") + .requires("config") + .conflicts_with("output"), + ) +} + +fn app_example8<'c>() -> App<'c> { + App::new("MyApp") + .arg(Arg::new("config")) + .arg(Arg::new("output")) + .arg( + Arg::new("input") + .help("the input file to use") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .required(true) + .short('i') + .long("input") + .requires("config") + .conflicts_with("output"), + ) +} + +fn app_example10<'c>() -> App<'c> { + App::new("myapp").about("does awesome things").arg( + Arg::new("CONFIG") + .help("The config file to use (default is \"config.json\")") + .short('c') + .takes_value(true), + ) +} + +pub fn example1(c: &mut Criterion) { + let mut app = app_example1(); + c.bench_function("example1", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example2(c: &mut Criterion) { + let mut app = app_example2(); + c.bench_function("example2", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example3(c: &mut Criterion) { + let mut app = app_example3(); + c.bench_function("example3", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example4(c: &mut Criterion) { + let mut app = app_example4(); + c.bench_function("example4", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example5(c: &mut Criterion) { + let mut app = app_example5(); + c.bench_function("example5", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example6(c: &mut Criterion) { + let mut app = app_example6(); + c.bench_function("example6", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example7(c: &mut Criterion) { + let mut app = app_example7(); + c.bench_function("example7", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example8(c: &mut Criterion) { + let mut app = app_example8(); + c.bench_function("example8", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example10(c: &mut Criterion) { + let mut app = app_example10(); + c.bench_function("example10", |b| b.iter(|| build_help(&mut app))); +} + +pub fn example4_template(c: &mut Criterion) { + let mut app = app_example4().help_template("{bin} {version}\n{author}\n{about}\n\nUSAGE:\n {usage}\n\nOPTIONS:\n{options}\n\nARGS:\n{args}\n"); + c.bench_function("example4_template", |b| b.iter(|| build_help(&mut app))); +} + +criterion_group!( + benches, + example1, + example2, + example3, + example4, + example5, + example6, + example7, + example8, + example10, + example4_template +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/05_ripgrep.rs b/third_party/rust/clap/benches/05_ripgrep.rs new file mode 100644 index 000000000000..3a7e4de6b4ed --- /dev/null +++ b/third_party/rust/clap/benches/05_ripgrep.rs @@ -0,0 +1,952 @@ +// Used to simulate a fairly large number of options/flags and parsing with thousands of positional +// args +// +// CLI used is adapted from ripgrep 48a8a3a691220f9e5b2b08f4051abe8655ea7e8a + +use clap::{App, Arg}; +use criterion::{criterion_group, criterion_main, Criterion}; +use std::collections::HashMap; +use std::io::Cursor; + +use lazy_static::lazy_static; + +pub fn build_rg_with_short_help(c: &mut Criterion) { + c.bench_function("build_rg_with_short_help", |b| b.iter(app_short)); +} + +pub fn build_rg_with_long_help(c: &mut Criterion) { + c.bench_function("build_rg_with_long_help", |b| b.iter(app_long)); +} + +pub fn write_rg_short_help(c: &mut Criterion) { + let mut app = app_short(); + c.bench_function("write_rg_short_help", |b| b.iter(|| build_help(&mut app))); +} + +pub fn write_rg_long_help(c: &mut Criterion) { + let mut app = app_long(); + c.bench_function("write_rg_long_help", |b| b.iter(|| build_help(&mut app))); +} + +pub fn parse_rg(c: &mut Criterion) { + c.bench_function("parse_rg", |b| { + b.iter(|| app_short().get_matches_from(vec!["rg", "pat"])) + }); +} + +pub fn parse_rg_with_complex(c: &mut Criterion) { + c.bench_function("parse_rg_with_complex", |b| { + b.iter(|| { + app_short().get_matches_from(vec![ + "rg", + "pat", + "-cFlN", + "-pqr=some", + "--null", + "--no-filename", + "--no-messages", + "-SH", + "-C5", + "--follow", + "-e some", + ]) + }) + }); +} + +pub fn parse_rg_with_lots(c: &mut Criterion) { + c.bench_function("parse_rg_with_lots", |b| { + b.iter(|| { + app_short().get_matches_from(vec![ + "rg", "pat", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", + ]) + }) + }); +} + +const ABOUT: &str = " +ripgrep (rg) recursively searches your current directory for a regex pattern. + +ripgrep's regex engine uses finite automata and guarantees linear time +searching. Because of this, features like backreferences and arbitrary +lookaround are not supported. + +Project home page: https://github.com/BurntSushi/ripgrep + +Use -h for short descriptions and --help for more details."; + +const USAGE: &str = " + rg [OPTIONS] [ ...] + rg [OPTIONS] [-e PATTERN | -f FILE ]... [ ...] + rg [OPTIONS] --files [ ...] + rg [OPTIONS] --type-list"; + +const TEMPLATE: &str = "\ +{bin} {version} +{author} +{about} + +USAGE:{usage} + +ARGS: +{positionals} + +OPTIONS: +{options}"; + +/// Build a clap application with short help strings. +fn app_short() -> App<'static> { + app(false, |k| USAGES[k].short) +} + +/// Build a clap application with long help strings. +fn app_long() -> App<'static> { + app(true, |k| USAGES[k].long) +} + +/// Build the help text of an application. +fn build_help(app: &mut App) -> String { + let mut buf = Cursor::new(Vec::with_capacity(50)); + app.write_help(&mut buf).unwrap(); + let content = buf.into_inner(); + String::from_utf8(content).unwrap() +} + +/// Build a clap application parameterized by usage strings. +/// +/// The function given should take a clap argument name and return a help +/// string. `app` will panic if a usage string is not defined. +/// +/// This is an intentionally stand-alone module so that it can be used easily +/// in a `build.rs` script to build shell completion files. +fn app(_next_line_help: bool, doc: F) -> App<'static> +where + F: Fn(&'static str) -> &'static str, +{ + let arg = |name| Arg::new(name).help(doc(name)); + let flag = |name| arg(name).long(name); + + App::new("ripgrep") + .author("BurntSushi") // simulating since it's only a bench + .version("0.4.0") // Simulating + .about(ABOUT) + .max_term_width(100) + .override_usage(USAGE) + .help_template(TEMPLATE) + // Handle help/version manually to make their output formatting + // consistent with short/long views. + .arg(arg("help-short").short('h')) + .arg(flag("help")) + .arg(flag("version").short('V')) + // First, set up primary positional/flag arguments. + .arg(arg("pattern").required_unless_present_any(&[ + "file", + "files", + "help-short", + "help", + "regexp", + "type-list", + "version", + ])) + .arg( + arg("path") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ) + .arg( + flag("regexp") + .short('e') + .allow_hyphen_values(true) + .multiple_occurrences(true) + .takes_value(true) + .value_name("pattern"), + ) + .arg( + flag("files") + // This should also conflict with `pattern`, but the first file + // path will actually be in `pattern`. + .conflicts_with_all(&["file", "regexp", "type-list"]), + ) + .arg(flag("type-list").conflicts_with_all(&["file", "files", "pattern", "regexp"])) + // Second, set up common flags. + .arg(flag("text").short('a')) + .arg(flag("count").short('c')) + .arg( + flag("color") + .value_name("WHEN") + .takes_value(true) + .hide_possible_values(true) + .possible_values(["never", "auto", "always", "ansi"]), + ) + .arg( + flag("colors") + .value_name("SPEC") + .multiple_occurrences(true) + .takes_value(true), + ) + .arg(flag("fixed-strings").short('F')) + .arg( + flag("glob") + .short('g') + .multiple_occurrences(true) + .takes_value(true) + .value_name("GLOB"), + ) + .arg(flag("ignore-case").short('i')) + .arg(flag("line-number").short('n')) + .arg(flag("no-line-number").short('N')) + .arg(flag("quiet").short('q')) + .arg( + flag("type") + .short('t') + .multiple_occurrences(true) + .takes_value(true) + .value_name("TYPE"), + ) + .arg( + flag("type-not") + .short('T') + .multiple_occurrences(true) + .takes_value(true) + .value_name("TYPE"), + ) + .arg(flag("unrestricted").short('u').multiple_occurrences(true)) + .arg(flag("invert-match").short('v')) + .arg(flag("word-regexp").short('w')) + // Third, set up less common flags. + .arg( + flag("after-context") + .short('A') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("before-context") + .short('B') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("context") + .short('C') + .value_name("NUM") + .validator(validate_number), + ) + .arg(flag("column")) + .arg(flag("context-separator").value_name("SEPARATOR")) + .arg(flag("debug")) + .arg( + flag("file") + .short('f') + .value_name("FILE") + .multiple_occurrences(true), + ) + .arg(flag("files-with-matches").short('l')) + .arg(flag("files-without-match")) + .arg(flag("with-filename").short('H')) + .arg(flag("no-filename")) + .arg(flag("heading").overrides_with("no-heading")) + .arg(flag("no-heading").overrides_with("heading")) + .arg(flag("hidden")) + .arg( + flag("ignore-file") + .value_name("FILE") + .multiple_occurrences(true), + ) + .arg(flag("follow").short('L')) + .arg( + flag("max-count") + .short('m') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("maxdepth") + .value_name("NUM") + .validator(validate_number), + ) + .arg(flag("mmap")) + .arg(flag("no-messages")) + .arg(flag("no-mmap")) + .arg(flag("no-ignore")) + .arg(flag("no-ignore-parent")) + .arg(flag("no-ignore-vcs")) + .arg(flag("null")) + .arg(flag("path-separator").value_name("SEPARATOR")) + .arg(flag("pretty").short('p')) + .arg(flag("replace").short('r').value_name("ARG")) + .arg(flag("case-sensitive").short('s')) + .arg(flag("smart-case").short('S')) + .arg(flag("sort-files")) + .arg( + flag("threads") + .short('j') + .value_name("ARG") + .validator(validate_number), + ) + .arg(flag("vimgrep")) + .arg( + flag("type-add") + .value_name("TYPE") + .multiple_occurrences(true), + ) + .arg( + flag("type-clear") + .value_name("TYPE") + .multiple_occurrences(true), + ) +} + +struct Usage { + short: &'static str, + long: &'static str, +} + +macro_rules! doc { + ($map:expr, $name:expr, $short:expr) => { + doc!($map, $name, $short, $short) + }; + ($map:expr, $name:expr, $short:expr, $long:expr) => { + $map.insert( + $name, + Usage { + short: $short, + long: concat!($long, "\n "), + }, + ); + }; +} + +lazy_static! { + static ref USAGES: HashMap<&'static str, Usage> = { + let mut h = HashMap::new(); + doc!( + h, + "help-short", + "Show short help output.", + "Show short help output. Use --help to show more details." + ); + doc!( + h, + "help", + "Show verbose help output.", + "When given, more details about flags are provided." + ); + doc!(h, "version", "Print version information."); + + doc!( + h, + "pattern", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "regexp", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "path", + "A file or directory to search.", + "A file or directory to search. Directories are searched \ + recursively." + ); + doc!( + h, + "files", + "Print each file that would be searched.", + "Print each file that would be searched without actually \ + performing the search. This is useful to determine whether a \ + particular file is being searched or not." + ); + doc!( + h, + "type-list", + "Show all supported file types.", + "Show all supported file types and their corresponding globs." + ); + + doc!(h, "text", "Search binary files as if they were text."); + doc!(h, "count", "Only show count of matches for each file."); + doc!( + h, + "color", + "When to use color. [default: auto]", + "When to use color in the output. The possible values are \ + never, auto, always or ansi. The default is auto. When always \ + is used, coloring is attempted based on your environment. When \ + ansi used, coloring is forcefully done using ANSI escape color \ + codes." + ); + doc!( + h, + "colors", + "Configure color settings and styles.", + "This flag specifies color settings for use in the output. \ + This flag may be provided multiple times. Settings are applied \ + iteratively. Colors are limited to one of eight choices: \ + red, blue, green, cyan, magenta, yellow, white and black. \ + Styles are limited to nobold, bold, nointense or intense.\n\n\ + The format of the flag is {type}:{attribute}:{value}. {type} \ + should be one of path, line or match. {attribute} can be fg, bg \ + or style. {value} is either a color (for fg and bg) or a text \ + style. A special format, {type}:none, will clear all color \ + settings for {type}.\n\nFor example, the following command will \ + change the match color to magenta and the background color for \ + line numbers to yellow:\n\n\ + rg --colors 'match:fg:magenta' --colors 'line:bg:yellow' foo." + ); + doc!( + h, + "fixed-strings", + "Treat the pattern as a literal string.", + "Treat the pattern as a literal string instead of a regular \ + expression. When this flag is used, special regular expression \ + meta characters such as (){}*+. do not need to be escaped." + ); + doc!( + h, + "glob", + "Include or exclude files/directories.", + "Include or exclude files/directories for searching that \ + match the given glob. This always overrides any other \ + ignore logic. Multiple glob flags may be used. Globbing \ + rules match .gitignore globs. Precede a glob with a ! \ + to exclude it." + ); + doc!( + h, + "ignore-case", + "Case insensitive search.", + "Case insensitive search. This is overridden by \ + --case-sensitive." + ); + doc!( + h, + "line-number", + "Show line numbers.", + "Show line numbers (1-based). This is enabled by default when \ + searching in a tty." + ); + doc!( + h, + "no-line-number", + "Suppress line numbers.", + "Suppress line numbers. This is enabled by default when NOT \ + searching in a tty." + ); + doc!( + h, + "quiet", + "Do not print anything to stdout.", + "Do not print anything to stdout. If a match is found in a file, \ + stop searching. This is useful when ripgrep is used only for \ + its exit code." + ); + doc!( + h, + "type", + "Only search files matching TYPE.", + "Only search files matching TYPE. Multiple type flags may be \ + provided. Use the --type-list flag to list all available \ + types." + ); + doc!( + h, + "type-not", + "Do not search files matching TYPE.", + "Do not search files matching TYPE. Multiple type-not flags may \ + be provided. Use the --type-list flag to list all available \ + types." + ); + doc!( + h, + "unrestricted", + "Reduce the level of \"smart\" searching.", + "Reduce the level of \"smart\" searching. A single -u \ + won't respect .gitignore (etc.) files. Two -u flags will \ + additionally search hidden files and directories. Three \ + -u flags will additionally search binary files. -uu is \ + roughly equivalent to grep -r and -uuu is roughly \ + equivalent to grep -a -r." + ); + doc!( + h, + "invert-match", + "Invert matching.", + "Invert matching. Show lines that don't match given patterns." + ); + doc!( + h, + "word-regexp", + "Only show matches surrounded by word boundaries.", + "Only show matches surrounded by word boundaries. This is \ + equivalent to putting \\b before and after all of the search \ + patterns." + ); + + doc!(h, "after-context", "Show NUM lines after each match."); + doc!(h, "before-context", "Show NUM lines before each match."); + doc!(h, "context", "Show NUM lines before and after each match."); + doc!( + h, + "column", + "Show column numbers", + "Show column numbers (1-based). This only shows the column \ + numbers for the first match on each line. This does not try \ + to account for Unicode. One byte is equal to one column. This \ + implies --line-number." + ); + doc!( + h, + "context-separator", + "Set the context separator string. [default: --]", + "The string used to separate non-contiguous context lines in the \ + output. Escape sequences like \\x7F or \\t may be used. The \ + default value is --." + ); + doc!( + h, + "debug", + "Show debug messages.", + "Show debug messages. Please use this when filing a bug report." + ); + doc!( + h, + "file", + "Search for patterns from the given file.", + "Search for patterns from the given file, with one pattern per \ + line. When this flag is used or multiple times or in \ + combination with the -e/--regexp flag, then all patterns \ + provided are searched. Empty pattern lines will match all input \ + lines, and the newline is not counted as part of the pattern." + ); + doc!( + h, + "files-with-matches", + "Only show the path of each file with at least one match." + ); + doc!( + h, + "files-without-match", + "Only show the path of each file that contains zero matches." + ); + doc!( + h, + "with-filename", + "Show file name for each match.", + "Prefix each match with the file name that contains it. This is \ + the default when more than one file is searched." + ); + doc!( + h, + "no-filename", + "Never show the file name for a match.", + "Never show the file name for a match. This is the default when \ + one file is searched." + ); + doc!( + h, + "heading", + "Show matches grouped by each file.", + "This shows the file name above clusters of matches from each \ + file instead of showing the file name for every match. This is \ + the default mode at a tty." + ); + doc!( + h, + "no-heading", + "Don't group matches by each file.", + "Don't group matches by each file. If -H/--with-filename is \ + enabled, then file names will be shown for every line matched. \ + This is the default mode when not at a tty." + ); + doc!( + h, + "hidden", + "Search hidden files and directories.", + "Search hidden files and directories. By default, hidden files \ + and directories are skipped." + ); + doc!( + h, + "ignore-file", + "Specify additional ignore files.", + "Specify additional ignore files for filtering file paths. \ + Ignore files should be in the gitignore format and are matched \ + relative to the current working directory. These ignore files \ + have lower precedence than all other ignore files. When \ + specifying multiple ignore files, earlier files have lower \ + precedence than later files." + ); + doc!(h, "follow", "Follow symbolic links."); + doc!( + h, + "max-count", + "Limit the number of matches.", + "Limit the number of matching lines per file searched to NUM." + ); + doc!( + h, + "maxdepth", + "Descend at most NUM directories.", + "Limit the depth of directory traversal to NUM levels beyond \ + the paths given. A value of zero only searches the \ + starting-points themselves.\n\nFor example, \ + 'rg --maxdepth 0 dir/' is a no-op because dir/ will not be \ + descended into. 'rg --maxdepth 1 dir/' will search only the \ + direct children of dir/." + ); + doc!( + h, + "mmap", + "Searching using memory maps when possible.", + "Search using memory maps when possible. This is enabled by \ + default when ripgrep thinks it will be faster. Note that memory \ + map searching doesn't currently support all options, so if an \ + incompatible option (e.g., --context) is given with --mmap, \ + then memory maps will not be used." + ); + doc!( + h, + "no-messages", + "Suppress all error messages.", + "Suppress all error messages. This is equivalent to redirecting \ + stderr to /dev/null." + ); + doc!( + h, + "no-mmap", + "Never use memory maps.", + "Never use memory maps, even when they might be faster." + ); + doc!( + h, + "no-ignore", + "Don't respect ignore files.", + "Don't respect ignore files (.gitignore, .ignore, etc.). This \ + implies --no-ignore-parent and --no-ignore-vcs." + ); + doc!( + h, + "no-ignore-parent", + "Don't respect ignore files in parent directories.", + "Don't respect ignore files (.gitignore, .ignore, etc.) in \ + parent directories." + ); + doc!( + h, + "no-ignore-vcs", + "Don't respect VCS ignore files", + "Don't respect version control ignore files (.gitignore, etc.). \ + This implies --no-ignore-parent. Note that .ignore files will \ + continue to be respected." + ); + doc!( + h, + "null", + "Print NUL byte after file names", + "Whenever a file name is printed, follow it with a NUL byte. \ + This includes printing file names before matches, and when \ + printing a list of matching files such as with --count, \ + --files-with-matches and --files. This option is useful for use \ + with xargs." + ); + doc!( + h, + "path-separator", + "Path separator to use when printing file paths.", + "The path separator to use when printing file paths. This \ + defaults to your platform's path separator, which is / on Unix \ + and \\ on Windows. This flag is intended for overriding the \ + default when the environment demands it (e.g., cygwin). A path \ + separator is limited to a single byte." + ); + doc!(h, "pretty", "Alias for --color always --heading -n."); + doc!( + h, + "replace", + "Replace matches with string given.", + "Replace every match with the string given when printing \ + results. Neither this flag nor any other flag will modify your \ + files.\n\nCapture group indices (e.g., $5) and names \ + (e.g., $foo) are supported in the replacement string.\n\n\ + Note that the replacement by default replaces each match, and \ + NOT the entire line. To replace the entire line, you should \ + match the entire line." + ); + doc!( + h, + "case-sensitive", + "Search case sensitively.", + "Search case sensitively. This overrides -i/--ignore-case and \ + -S/--smart-case." + ); + doc!( + h, + "smart-case", + "Smart case search.", + "Searches case insensitively if the pattern is all lowercase. \ + Search case sensitively otherwise. This is overridden by \ + either -s/--case-sensitive or -i/--ignore-case." + ); + doc!( + h, + "sort-files", + "Sort results by file path. Implies --threads=1.", + "Sort results by file path. Note that this currently \ + disables all parallelism and runs search in a single thread." + ); + doc!( + h, + "threads", + "The approximate number of threads to use.", + "The approximate number of threads to use. A value of 0 (which \ + is the default) causes ripgrep to choose the thread count \ + using heuristics." + ); + doc!( + h, + "vimgrep", + "Show results in vim compatible format.", + "Show results with every match on its own line, including \ + line numbers and column numbers. With this option, a line with \ + more than one match will be printed more than once." + ); + + doc!( + h, + "type-add", + "Add a new glob for a file type.", + "Add a new glob for a particular file type. Only one glob can be \ + added at a time. Multiple --type-add flags can be provided. \ + Unless --type-clear is used, globs are added to any existing \ + globs defined inside of ripgrep.\n\nNote that this MUST be \ + passed to every invocation of ripgrep. Type settings are NOT \ + persisted.\n\nExample: \ + rg --type-add 'foo:*.foo' -tfoo PATTERN.\n\n\ + --type-add can also be used to include rules from other types \ + with the special include directive. The include directive \ + permits specifying one or more other type names (separated by a \ + comma) that have been defined and its rules will automatically \ + be imported into the type specified. For example, to create a \ + type called src that matches C++, Python and Markdown files, one \ + can use:\n\n\ + --type-add 'src:include:cpp,py,md'\n\n\ + Additional glob rules can still be added to the src type by \ + using the --type-add flag again:\n\n\ + --type-add 'src:include:cpp,py,md' --type-add 'src:*.foo'\n\n\ + Note that type names must consist only of Unicode letters or \ + numbers. Punctuation characters are not allowed." + ); + doc!( + h, + "type-clear", + "Clear globs for given file type.", + "Clear the file type globs previously defined for TYPE. This \ + only clears the default type definitions that are found inside \ + of ripgrep.\n\nNote that this MUST be passed to every \ + invocation of ripgrep. Type settings are NOT persisted." + ); + + h + }; +} + +fn validate_number(s: &str) -> Result<(), String> { + s.parse::() + .map(|_| ()) + .map_err(|err| err.to_string()) +} + +criterion_group!( + benches, + build_rg_with_short_help, + build_rg_with_long_help, + write_rg_short_help, + write_rg_long_help, + parse_rg, + parse_rg_with_complex, + parse_rg_with_lots +); +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/06_rustup.rs b/third_party/rust/clap/benches/06_rustup.rs new file mode 100644 index 000000000000..0f23f16d271a --- /dev/null +++ b/third_party/rust/clap/benches/06_rustup.rs @@ -0,0 +1,408 @@ +// Used to simulate a fairly large number of subcommands +// +// CLI used is from rustup 408ed84f0e50511ed44a405dd91365e5da588790 + +use clap::{App, AppSettings, Arg, ArgGroup}; +use criterion::{criterion_group, criterion_main, Criterion}; + +pub fn build_rustup(c: &mut Criterion) { + c.bench_function("build_rustup", |b| b.iter(build_cli)); +} + +pub fn parse_rustup(c: &mut Criterion) { + c.bench_function("parse_rustup", |b| { + b.iter(|| build_cli().get_matches_from(vec![""])) + }); +} + +pub fn parse_rustup_with_sc(c: &mut Criterion) { + c.bench_function("parse_rustup_with_sc", |b| { + b.iter(|| build_cli().get_matches_from(vec!["rustup override add stable"])) + }); +} + +fn build_cli() -> App<'static> { + App::new("rustup") + .version("0.9.0") // Simulating + .about("The Rust toolchain installer") + .after_help(RUSTUP_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .arg( + Arg::new("verbose") + .help("Enable verbose output") + .short('v') + .long("verbose"), + ) + .subcommand( + App::new("show") + .about("Show the active and installed toolchains") + .after_help(SHOW_HELP), + ) + .subcommand( + App::new("install") + .about("Update Rust toolchains") + .after_help(TOOLCHAIN_INSTALL_HELP) + .setting(AppSettings::Hidden) // synonym for 'toolchain install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("update") + .about("Update Rust toolchains") + .after_help(UPDATE_HELP) + .arg(Arg::new("toolchain").required(true)) + .arg( + Arg::new("no-self-update") + .help("Don't perform self update when running the `rustup` command") + .long("no-self-update") + .hide(true), + ), + ) + .subcommand( + App::new("default") + .about("Set the default toolchain") + .after_help(DEFAULT_HELP) + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("toolchain") + .about("Modify or query the installed toolchains") + .after_help(TOOLCHAIN_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(App::new("list").about("List installed toolchains")) + .subcommand( + App::new("install") + .about("Install or update a given toolchain") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("uninstall") + .about("Uninstall a toolchain") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("link") + .about("Create a custom toolchain by symlinking to a directory") + .arg(Arg::new("toolchain").required(true)) + .arg(Arg::new("path").required(true)), + ) + .subcommand( + App::new("update") + .setting(AppSettings::Hidden) // synonym for 'install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("add") + .setting(AppSettings::Hidden) // synonym for 'install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("remove") + .setting(AppSettings::Hidden) // synonym for 'uninstall' + .arg(Arg::new("toolchain").required(true)), + ), + ) + .subcommand( + App::new("target") + .about("Modify a toolchain's supported targets") + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + App::new("list") + .about("List installed and available targets") + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("add") + .about("Add a target to a Rust toolchain") + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("remove") + .about("Remove a target from a Rust toolchain") + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("install") + .setting(AppSettings::Hidden) // synonym for 'add' + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("uninstall") + .setting(AppSettings::Hidden) // synonym for 'remove' + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ), + ) + .subcommand( + App::new("component") + .about("Modify a toolchain's installed components") + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + App::new("list") + .about("List installed and available components") + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("add") + .about("Add a component to a Rust toolchain") + .arg(Arg::new("component").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)) + .arg(Arg::new("target").long("target").takes_value(true)), + ) + .subcommand( + App::new("remove") + .about("Remove a component from a Rust toolchain") + .arg(Arg::new("component").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)) + .arg(Arg::new("target").long("target").takes_value(true)), + ), + ) + .subcommand( + App::new("override") + .about("Modify directory toolchain overrides") + .after_help(OVERRIDE_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(App::new("list").about("List directory toolchain overrides")) + .subcommand( + App::new("set") + .about("Set the override toolchain for a directory") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("unset") + .about("Remove the override toolchain for a directory") + .after_help(OVERRIDE_UNSET_HELP) + .arg( + Arg::new("path") + .long("path") + .takes_value(true) + .help("Path to the directory"), + ) + .arg( + Arg::new("nonexistent") + .long("nonexistent") + .help("Remove override toolchain for all nonexistent directories"), + ), + ) + .subcommand( + App::new("add") + .setting(AppSettings::Hidden) // synonym for 'set' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + App::new("remove") + .setting(AppSettings::Hidden) // synonym for 'unset' + .about("Remove the override toolchain for a directory") + .arg(Arg::new("path").long("path").takes_value(true)) + .arg( + Arg::new("nonexistent") + .long("nonexistent") + .help("Remove override toolchain for all nonexistent directories"), + ), + ), + ) + .subcommand( + App::new("run") + .about("Run a command with an environment configured for a given toolchain") + .after_help(RUN_HELP) + .setting(AppSettings::TrailingVarArg) + .arg(Arg::new("toolchain").required(true)) + .arg( + Arg::new("command") + .required(true) + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ), + ) + .subcommand( + App::new("which") + .about("Display which binary will be run for a given command") + .arg(Arg::new("command").required(true)), + ) + .subcommand( + App::new("doc") + .about("Open the documentation for the current toolchain") + .after_help(DOC_HELP) + .arg( + Arg::new("book") + .long("book") + .help("The Rust Programming Language book"), + ) + .arg( + Arg::new("std") + .long("std") + .help("Standard library API documentation"), + ) + .group(ArgGroup::new("page").args(&["book", "std"])), + ) + .subcommand( + App::new("man") + .about("View the man page for a given command") + .arg(Arg::new("command").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + App::new("self") + .about("Modify the rustup installation") + .setting(AppSettings::DeriveDisplayOrder) + .subcommand(App::new("update").about("Download and install updates to rustup")) + .subcommand( + App::new("uninstall") + .about("Uninstall rustup.") + .arg(Arg::new("no-prompt").short('y')), + ) + .subcommand(App::new("upgrade-data").about("Upgrade the internal data format.")), + ) + .subcommand( + App::new("telemetry") + .about("rustup telemetry commands") + .setting(AppSettings::Hidden) + .setting(AppSettings::DeriveDisplayOrder) + .subcommand(App::new("enable").about("Enable rustup telemetry")) + .subcommand(App::new("disable").about("Disable rustup telemetry")) + .subcommand(App::new("analyze").about("Analyze stored telemetry")), + ) + .subcommand( + App::new("set").about("Alter rustup settings").subcommand( + App::new("default-host") + .about("The triple used to identify toolchains when not specified") + .arg(Arg::new("host_triple").required(true)), + ), + ) +} + +static RUSTUP_HELP: &str = r" +rustup installs The Rust Programming Language from the official +release channels, enabling you to easily switch between stable, beta, +and nightly compilers and keep them updated. It makes cross-compiling +simpler with binary builds of the standard library for common platforms. + +If you are new to Rust consider running `rustup doc --book` +to learn Rust."; + +static SHOW_HELP: &str = r" +Shows the name of the active toolchain and the version of `rustc`. + +If the active toolchain has installed support for additional +compilation targets, then they are listed as well. + +If there are multiple toolchains installed then all installed +toolchains are listed as well."; + +static UPDATE_HELP: &str = r" +With no toolchain specified, the `update` command updates each of the +installed toolchains from the official release channels, then updates +rustup itself. + +If given a toolchain argument then `update` updates that toolchain, +the same as `rustup toolchain install`. + +'toolchain' specifies a toolchain name, such as 'stable', 'nightly', +or '1.8.0'. For more information see `rustup help toolchain`."; + +static TOOLCHAIN_INSTALL_HELP: &str = r" +Installs a specific rust toolchain. + +The 'install' command is an alias for 'rustup update '. + +'toolchain' specifies a toolchain name, such as 'stable', 'nightly', +or '1.8.0'. For more information see `rustup help toolchain`."; + +static DEFAULT_HELP: &str = r" +Sets the default toolchain to the one specified. If the toolchain is +not already installed then it is installed first."; + +static TOOLCHAIN_HELP: &str = r" +Many `rustup` commands deal with *toolchains*, a single installation +of the Rust compiler. `rustup` supports multiple types of +toolchains. The most basic track the official release channels: +'stable', 'beta' and 'nightly'; but `rustup` can also install +toolchains from the official archives, for alternate host platforms, +and from local builds. + +Standard release channel toolchain names have the following form: + + [-][-] + + = stable|beta|nightly| + = YYYY-MM-DD + = + +'channel' is either a named release channel or an explicit version +number, such as '1.8.0'. Channel names can be optionally appended with +an archive date, as in 'nightly-2014-12-18', in which case the +toolchain is downloaded from the archive for that date. + +Finally, the host may be specified as a target triple. This is most +useful for installing a 32-bit compiler on a 64-bit platform, or for +installing the [MSVC-based toolchain] on Windows. For example: + + rustup toolchain install stable-x86_64-pc-windows-msvc + +For convenience, elements of the target triple that are omitted will be +inferred, so the above could be written: + + $ rustup default stable-msvc + +Toolchain names that don't name a channel instead can be used to name +custom toolchains with the `rustup toolchain link` command."; + +static OVERRIDE_HELP: &str = r" +Overrides configure rustup to use a specific toolchain when +running in a specific directory. + +Directories can be assigned their own Rust toolchain with +`rustup override`. When a directory has an override then +any time `rustc` or `cargo` is run inside that directory, +or one of its child directories, the override toolchain +will be invoked. + +To pin to a specific nightly: + + rustup override set nightly-2014-12-18 + +Or a specific stable release: + + rustup override set 1.0.0 + +To see the active toolchain use `rustup show`. To remove the override +and use the default toolchain again, `rustup override unset`."; + +static OVERRIDE_UNSET_HELP: &str = r" +If `--path` argument is present, removes the override toolchain for +the specified directory. If `--nonexistent` argument is present, removes +the override toolchain for all nonexistent directories. Otherwise, +removes the override toolchain for the current directory."; + +static RUN_HELP: &str = r" +Configures an environment to use the given toolchain and then runs +the specified program. The command may be any program, not just +rustc or cargo. This can be used for testing arbitrary toolchains +without setting an override. + +Commands explicitly proxied by `rustup` (such as `rustc` and `cargo`) +also have a shorthand for this available. The toolchain can be set by +using `+toolchain` as the first argument. These are equivalent: + + cargo +nightly build + + rustup run nightly cargo build"; + +static DOC_HELP: &str = r" +Opens the documentation for the currently active toolchain with the +default browser. + +By default, it opens the documentation index. Use the various flags to +open specific pieces of documentation."; + +criterion_group!(benches, build_rustup, parse_rustup, parse_rustup_with_sc); + +criterion_main!(benches); diff --git a/third_party/rust/clap/clap-test.rs b/third_party/rust/clap/clap-test.rs deleted file mode 100644 index 7d57ac4f3083..000000000000 --- a/third_party/rust/clap/clap-test.rs +++ /dev/null @@ -1,86 +0,0 @@ -#[allow(unused_imports, dead_code)] -mod test { - use std::str; - use std::io::{Cursor, Write}; - - use regex::Regex; - - use clap::{App, Arg, SubCommand, ArgGroup}; - - fn compare(l: S, r: S2) -> bool - where S: AsRef, - S2: AsRef - { - let re = Regex::new("\x1b[^m]*m").unwrap(); - // Strip out any mismatching \r character on windows that might sneak in on either side - let ls = l.as_ref().trim().replace("\r", ""); - let rs = r.as_ref().trim().replace("\r", ""); - let left = re.replace_all(&*ls, ""); - let right = re.replace_all(&*rs, ""); - let b = left == right; - if !b { - println!(); - println!("--> left"); - println!("{}", left); - println!("--> right"); - println!("{}", right); - println!("--") - } - b - } - - pub fn compare_output(l: App, args: &str, right: &str, stderr: bool) -> bool { - let mut buf = Cursor::new(Vec::with_capacity(50)); - let res = l.get_matches_from_safe(args.split(' ').collect::>()); - let err = res.unwrap_err(); - err.write_to(&mut buf).unwrap(); - let content = buf.into_inner(); - let left = String::from_utf8(content).unwrap(); - assert_eq!(stderr, err.use_stderr()); - compare(left, right) - } - pub fn compare_output2(l: App, args: &str, right1: &str, right2: &str, stderr: bool) -> bool { - let mut buf = Cursor::new(Vec::with_capacity(50)); - let res = l.get_matches_from_safe(args.split(' ').collect::>()); - let err = res.unwrap_err(); - err.write_to(&mut buf).unwrap(); - let content = buf.into_inner(); - let left = String::from_utf8(content).unwrap(); - assert_eq!(stderr, err.use_stderr()); - compare(&*left, right1) || compare(&*left, right2) - } - - // Legacy tests from the Python script days - - pub fn complex_app() -> App<'static, 'static> { - let args = "-o --option=[opt]... 'tests options' - [positional] 'tests positionals'"; - let opt3_vals = ["fast", "slow"]; - let pos3_vals = ["vi", "emacs"]; - App::new("clap-test") - .version("v1.4.8") - .about("tests clap library") - .author("Kevin K. ") - .args_from_usage(args) - .arg(Arg::from_usage("-f --flag... 'tests flags'") - .global(true)) - .args(&[ - Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("long-option-2"), - Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"), - Arg::from_usage("[positional2] 'tests positionals with exclusions'"), - Arg::from_usage("-O --Option [option3] 'specific vals'").possible_values(&opt3_vals), - Arg::from_usage("[positional3]... 'tests specific values'").possible_values(&pos3_vals), - Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"), - Arg::from_usage("--multvalsmo... [one] [two] 'Tests multiple values, and mult occs'"), - Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2), - Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3) - ]) - .subcommand(SubCommand::with_name("subcmd") - .about("tests subcommands") - .version("0.1") - .author("Kevin K. ") - .arg_from_usage("-o --option [scoption]... 'tests options'") - .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests other args'") - .arg_from_usage("[scpositional] 'tests positionals'")) - } -} diff --git a/third_party/rust/clap/examples/README.md b/third_party/rust/clap/examples/README.md new file mode 100644 index 000000000000..946822ddb08a --- /dev/null +++ b/third_party/rust/clap/examples/README.md @@ -0,0 +1,20 @@ +# Examples + +- Basic demo: [derive](demo.md) +- Key-value pair arguments: [derive](keyvalue-derive.md) +- Custom cargo command: [builder](cargo-example.md), [derive](cargo-example-derive.md) +- git-like interface: [builder](git.md), [derive](git-derive.md) +- pacman-like interface: [builder](pacman.md) +- Escaped positionals with `--`: [builder](escaped-positional.md), [derive](escaped-positional-derive.md) +- Multi-call + - busybox: [builder](multicall-busybox.md) + - hostname: [builder](multicall-hostname.md) + +## 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/third_party/rust/clap/examples/cargo-example-derive.md b/third_party/rust/clap/examples/cargo-example-derive.md new file mode 100644 index 000000000000..994c6d4d80c7 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example-derive.md @@ -0,0 +1,45 @@ +*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/third_party/rust/clap/examples/cargo-example-derive.rs b/third_party/rust/clap/examples/cargo-example-derive.rs new file mode 100644 index 000000000000..c714480e0edc --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example-derive.rs @@ -0,0 +1,20 @@ +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, parse(from_os_str))] + manifest_path: Option, +} + +fn main() { + let Cargo::ExampleDerive(args) = Cargo::parse(); + println!("{:?}", args.manifest_path); +} diff --git a/third_party/rust/clap/examples/cargo-example.md b/third_party/rust/clap/examples/cargo-example.md new file mode 100644 index 000000000000..9279cc492503 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example.md @@ -0,0 +1,45 @@ +*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/third_party/rust/clap/examples/cargo-example.rs b/third_party/rust/clap/examples/cargo-example.rs new file mode 100644 index 000000000000..742697a02149 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example.rs @@ -0,0 +1,21 @@ +fn main() { + let app = clap::App::new("cargo") + .bin_name("cargo") + .setting(clap::AppSettings::SubcommandRequired) + .subcommand( + clap::app_from_crate!().name("example").arg( + clap::arg!(--"manifest-path" ) + .required(false) + .allow_invalid_utf8(true), + ), + ); + let matches = app.get_matches(); + let matches = match matches.subcommand() { + Some(("example", matches)) => matches, + _ => unreachable!("clap should ensure we don't get here"), + }; + let manifest_path = matches + .value_of_os("manifest-path") + .map(std::path::PathBuf::from); + println!("{:?}", manifest_path); +} diff --git a/third_party/rust/clap/examples/demo.md b/third_party/rust/clap/examples/demo.md new file mode 100644 index 000000000000..9b0e7e260f19 --- /dev/null +++ b/third_party/rust/clap/examples/demo.md @@ -0,0 +1,20 @@ +*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/third_party/rust/clap/examples/demo.rs b/third_party/rust/clap/examples/demo.rs new file mode 100644 index 000000000000..262a81a2c1af --- /dev/null +++ b/third_party/rust/clap/examples/demo.rs @@ -0,0 +1,24 @@ +// 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)] + name: String, + + /// Number of times to greet + #[clap(short, long, default_value_t = 1)] + count: u8, +} + +fn main() { + let args = Args::parse(); + + for _ in 0..args.count { + println!("Hello {}!", args.name) + } +} diff --git a/third_party/rust/clap/examples/derive_ref/README.md b/third_party/rust/clap/examples/derive_ref/README.md new file mode 100644 index 000000000000..fbc88a913b57 --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/README.md @@ -0,0 +1,351 @@ +# Derive Reference + +1. [Overview](#overview) +2. [Raw Attributes](#raw-attributes) +3. [Magic Attributes](#magic-attributes) + 1. [App Attributes](#app-attributes) + 2. [Arg Attributes](#arg-attributes) + 3. [Arg Types](#arg-types) + 4. [Arg Enum Attributes](#arg-enum-attributes) + 5. [Possible Value Attributes](#possible-value-attributes) + 6. [Doc Comments](#doc-comments) + +## 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 what can go where: +```rust +use clap::{Parser, Args, Subcommand, ArgEnum}; + +/// Doc comment +#[derive(Parser)] +#[clap(APP ATTRIBUTE)] +struct Cli { + /// Doc comment + #[clap(ARG ATTRIBUTE)] + field: Type, + + #[clap(flatten)] + delegate: Struct, + + #[clap(subcommand)] + command: Command, +} + +/// Doc comment +#[derive(Args)] +#[clap(PARENT APP ATTRIBUTE)] +struct Struct { + /// Doc comment + #[clap(ARG ATTRIBUTE)] + field: Type, +} + +/// 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: Type, + } +} + +/// Doc comment +#[derive(ArgEnum)] +#[clap(ARG ENUM ATTRIBUTE)] +enum Mode { + /// 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. +- `ArgEnum` allows parsing a value directly into an `enum`, erroring on unsupported values. + +See also the [tutorial](../tutorial_derive/README.md) and [examples](../README.md). + +## Raw Attributes + +**Raw attributes** are forwarded directly to the underlying `clap` builder. Any +`App`, `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 + +**Magic attributes** have post-processing done to them, whether that is +- Providing of defaults +- Special behavior is triggered off of it + +### App Attributes + +These correspond to a `clap::App` which is used for both top-level parsers and +when defining subcommands. + +In addition to the raw attributes, the following magic attributes are supported: +- `name = `: `clap::App::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::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 [= ]`: `clap::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 [= ]`: `clap::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` 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::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` / `long_about` +- `help_heading`: `clap::App::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 `App::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::AppSettings::AllowExternalSubcommand` + - Variant must be either `Variant(Vec)` or `Variant(Vec)` + +### Arg Attributes + +These correspond to a `clap::Arg`. + +In addition to the raw attributes, the following magic attributes are supported: +- `name = `: `clap::Arg::new` + - When not present: case-converted field name is used +- `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` + - 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 App Attributes, this + makes reuse harder. Generally prefer putting the app 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` +- `arg_enum`: Parse the value using the `ArgEnum` 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(arg_enum)]` + - Without ``, relies on `Default::default()` + +### Arg Types + +`clap` assumes some intent based on the type used: + +| Type | Effect | Implies | +|---------------------|--------------------------------------|------------------------------------------------------------------| +| `bool` | flag | `#[clap(parser(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 `value_of` function +- `from_flag` + - Implies `arg.takes_value(false)` + - Reads from `clap::ArgMatches::is_present` rather than a `value_of` function + +**Warning:** +- To support non-UTF8 paths, you must use `parse(from_os_str)`, otherwise + `clap` will use `clap::ArgMatches::value_of` with `PathBuf::FromStr`. + +### 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`. + +- `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) + +### Doc Comments + +In clap, help messages for the whole binary can be specified +via [`App::about`] and [`App::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 `App::about/long_about` calls!** +If you really want to use the `App::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)] + 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 `App::about` / `Arg::help`. When a blank line is +present, the whole doc comment will be passed to `App::long_about` / +`Arg::long_help`. Or in other words, a doc may result in just a `App::about` / +`Arg::help` or `App::about` / `Arg::help` and `App::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 diff --git a/third_party/rust/clap/examples/derive_ref/custom-bool.md b/third_party/rust/clap/examples/derive_ref/custom-bool.md new file mode 100644 index 000000000000..2769f20e8f9a --- /dev/null +++ b/third_party/rust/clap/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: + + +OPTIONS: + --bar [default: false] + --foo + -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/third_party/rust/clap/examples/derive_ref/custom-bool.rs b/third_party/rust/clap/examples/derive_ref/custom-bool.rs new file mode 100644 index 000000000000..10f93f40ac6c --- /dev/null +++ b/third_party/rust/clap/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 `try_from_str` is FromStr::from_str. + // `impl FromStr for bool` parses `true` or `false` so this + // works as expected. + #[clap(long, parse(try_from_str))] + foo: bool, + + // Of course, this could be done with an explicit parser function. + #[clap(long, parse(try_from_str = true_or_false), default_value_t)] + bar: bool, + + // `bool` can be positional only with explicit `parse(...)` annotation + #[clap(parse(try_from_str))] + 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/third_party/rust/clap/examples/escaped-positional-derive.md b/third_party/rust/clap/examples/escaped-positional-derive.md new file mode 100644 index 000000000000..3b5f8fe5652f --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional-derive.md @@ -0,0 +1,65 @@ +*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/third_party/rust/clap/examples/escaped-positional-derive.rs b/third_party/rust/clap/examples/escaped-positional-derive.rs new file mode 100644 index 000000000000..8038395aff23 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional-derive.rs @@ -0,0 +1,27 @@ +// Note: this requires the `derive` feature + +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short = 'f')] + eff: bool, + + #[clap(short = 'p', value_name = "PEAR")] + pea: Option, + + #[clap(last = true)] + 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/third_party/rust/clap/examples/escaped-positional.md b/third_party/rust/clap/examples/escaped-positional.md new file mode 100644 index 000000000000..1f71a87369d2 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional.md @@ -0,0 +1,65 @@ +*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/third_party/rust/clap/examples/escaped-positional.rs b/third_party/rust/clap/examples/escaped-positional.rs new file mode 100644 index 000000000000..814e2a7cbdf4 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional.rs @@ -0,0 +1,26 @@ +// Note: this requires the `cargo` feature + +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg(arg!(eff: -f)) + .arg(arg!(pea: -p ).required(false)) + .arg( + arg!(slop: [SLOP]).multiple_occurrences(true).last(true), // Indicates that `slop` is only accessible after `--`. + ) + .get_matches(); + + // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... + println!("-f used: {:?}", matches.is_present("eff")); // -f used: true + println!("-p's value: {:?}", matches.value_of("pea")); // -p's value: Some("bob") + println!( + "'slops' values: {:?}", + matches + .values_of("slop") + .map(|vals| vals.collect::>()) + .unwrap_or_default() + ); // 'slops' values: Some(["sloppy", "slop", "slop"]) + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/git-derive.md b/third_party/rust/clap/examples/git-derive.md new file mode 100644 index 000000000000..d33ce19bcada --- /dev/null +++ b/third_party/rust/clap/examples/git-derive.md @@ -0,0 +1,83 @@ +*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 + +$ 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 + +$ 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"] + +``` + +External subcommands: +```console +$ git-derive custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/third_party/rust/clap/examples/git-derive.rs b/third_party/rust/clap/examples/git-derive.rs new file mode 100644 index 000000000000..4f0cf80e07e9 --- /dev/null +++ b/third_party/rust/clap/examples/git-derive.rs @@ -0,0 +1,61 @@ +// Note: this requires the `derive` feature + +use std::ffi::OsString; +use std::path::PathBuf; + +use clap::{AppSettings, Parser, Subcommand}; + +/// A fictional versioning CLI +#[derive(Parser)] +#[clap(name = "git")] +#[clap(about = "A fictional versioning CLI", long_about = None)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Clones repos + #[clap(setting(AppSettings::ArgRequiredElseHelp))] + Clone { + /// The remote to clone + remote: String, + }, + /// pushes things + #[clap(setting(AppSettings::ArgRequiredElseHelp))] + Push { + /// The remote to target + remote: String, + }, + /// adds things + #[clap(setting(AppSettings::ArgRequiredElseHelp))] + Add { + /// Stuff to add + #[clap(required = true, parse(from_os_str))] + path: Vec, + }, + #[clap(external_subcommand)] + External(Vec), +} + +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::External(args) => { + println!("Calling out to {:?} with {:?}", &args[0], &args[1..]); + } + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/git.md b/third_party/rust/clap/examples/git.md new file mode 100644 index 000000000000..64c2f9413e1c --- /dev/null +++ b/third_party/rust/clap/examples/git.md @@ -0,0 +1,81 @@ +*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 + +$ 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 + +$ 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"] + +``` + +External subcommands: +```console +$ git custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/third_party/rust/clap/examples/git.rs b/third_party/rust/clap/examples/git.rs new file mode 100644 index 000000000000..77394dccb302 --- /dev/null +++ b/third_party/rust/clap/examples/git.rs @@ -0,0 +1,63 @@ +use std::path::PathBuf; + +use clap::{arg, App, AppSettings}; + +fn main() { + let matches = App::new("git") + .about("A fictional versioning CLI") + .setting(AppSettings::SubcommandRequiredElseHelp) + .setting(AppSettings::AllowExternalSubcommands) + .setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + .subcommand( + App::new("clone") + .about("Clones repos") + .arg(arg!( "The remote to clone")) + .setting(AppSettings::ArgRequiredElseHelp), + ) + .subcommand( + App::new("push") + .about("pushes things") + .arg(arg!( "The remote to target")) + .setting(AppSettings::ArgRequiredElseHelp), + ) + .subcommand( + App::new("add") + .about("adds things") + .setting(AppSettings::ArgRequiredElseHelp) + .arg(arg!( ... "Stuff to add").allow_invalid_utf8(true)), + ) + .get_matches(); + + match matches.subcommand() { + Some(("clone", sub_matches)) => { + println!( + "Cloning {}", + sub_matches.value_of("REMOTE").expect("required") + ); + } + Some(("push", sub_matches)) => { + println!( + "Pushing to {}", + sub_matches.value_of("REMOTE").expect("required") + ); + } + Some(("add", sub_matches)) => { + let paths = sub_matches + .values_of_os("PATH") + .unwrap_or_default() + .map(PathBuf::from) + .collect::>(); + println!("Adding {:?}", paths); + } + Some((ext, sub_matches)) => { + let args = sub_matches + .values_of_os("") + .unwrap_or_default() + .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/third_party/rust/clap/examples/keyvalue-derive.md b/third_party/rust/clap/examples/keyvalue-derive.md new file mode 100644 index 000000000000..65748bc39253 --- /dev/null +++ b/third_party/rust/clap/examples/keyvalue-derive.md @@ -0,0 +1,31 @@ +*Jump to [source](keyvalue-derive.rs)* + +**This requires enabling the `derive` feature flag.** + +```console +$ keyvalue-derive --help +clap + +USAGE: + keyvalue-derive[EXE] [OPTIONS] + +OPTIONS: + -D + -h, --help Print help information + +$ keyvalue-derive -D Foo=10 -D Alice=30 +Args { defines: [("Foo", 10), ("Alice", 30)] } + +$ keyvalue-derive -D Foo +? failed +error: Invalid value for '-D ': invalid KEY=value: no `=` found in `Foo` + +For more information try --help + +$ keyvalue-derive -D Foo=Bar +? failed +error: Invalid value for '-D ': invalid digit found in string + +For more information try --help + +``` diff --git a/third_party/rust/clap/examples/keyvalue-derive.rs b/third_party/rust/clap/examples/keyvalue-derive.rs new file mode 100644 index 000000000000..c31a1a79bd20 --- /dev/null +++ b/third_party/rust/clap/examples/keyvalue-derive.rs @@ -0,0 +1,29 @@ +// Note: this requires the `derive` feature + +use clap::Parser; +use std::error::Error; + +#[derive(Parser, Debug)] +struct Args { + #[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true))] + 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/third_party/rust/clap/examples/multicall-busybox.md b/third_party/rust/clap/examples/multicall-busybox.md new file mode 100644 index 000000000000..040b0088fe98 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-busybox.md @@ -0,0 +1,46 @@ +*Jump to [source](multicall-busybox.rs)* + +Example of a busybox-style multicall program + +See the documentation for clap::AppSettings::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/third_party/rust/clap/examples/multicall-busybox.rs b/third_party/rust/clap/examples/multicall-busybox.rs new file mode 100644 index 000000000000..9f07aef195a3 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-busybox.rs @@ -0,0 +1,46 @@ +use std::process::exit; + +use clap::{App, AppSettings, Arg}; + +fn applet_commands() -> [App<'static>; 2] { + [ + App::new("true").about("does nothing successfully"), + App::new("false").about("does nothing unsuccessfully"), + ] +} + +fn main() { + let app = App::new(env!("CARGO_CRATE_NAME")) + .setting(AppSettings::Multicall) + .subcommand( + App::new("busybox") + .setting(AppSettings::ArgRequiredElseHelp) + .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") + .use_delimiter(false), + ) + .subcommands(applet_commands()), + ) + .subcommands(applet_commands()); + + let matches = app.get_matches(); + let mut subcommand = matches.subcommand(); + if let Some(("busybox", cmd)) = subcommand { + if cmd.occurrences_of("install") > 0 { + 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/third_party/rust/clap/examples/multicall-hostname.md b/third_party/rust/clap/examples/multicall-hostname.md new file mode 100644 index 000000000000..a59aa0ab8cd0 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-hostname.md @@ -0,0 +1,14 @@ +*Jump to [source](multicall-hostname.rs)* + +Example of a `hostname-style` multicall program + +See the documentation for clap::AppSettings::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/third_party/rust/clap/examples/multicall-hostname.rs b/third_party/rust/clap/examples/multicall-hostname.rs new file mode 100644 index 000000000000..904c70035073 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-hostname.rs @@ -0,0 +1,18 @@ +use clap::{App, AppSettings}; + +fn main() { + let app = App::new(env!("CARGO_CRATE_NAME")) + .setting(AppSettings::ArgRequiredElseHelp) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .subcommand(App::new("hostname").about("show hostname part of FQDN")) + .subcommand(App::new("dnsdomainname").about("show domain name part of FQDN")); + + let app = app.setting(AppSettings::Multicall); + + match app.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/third_party/rust/clap/examples/pacman.md b/third_party/rust/clap/examples/pacman.md new file mode 100644 index 000000000000..daa26dc8b216 --- /dev/null +++ b/third_party/rust/clap/examples/pacman.md @@ -0,0 +1,38 @@ +*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)* + +**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/third_party/rust/clap/examples/pacman.rs b/third_party/rust/clap/examples/pacman.rs new file mode 100644 index 000000000000..5b42f0d5b23f --- /dev/null +++ b/third_party/rust/clap/examples/pacman.rs @@ -0,0 +1,101 @@ +use clap::{App, AppSettings, Arg}; + +fn main() { + let matches = App::new("pacman") + .about("package manager utility") + .version("5.2.1") + .setting(AppSettings::SubcommandRequiredElseHelp) + .author("Pacman Development Team") + // Query subcommand + // + // Only a few of its arguments are implemented below. + .subcommand( + App::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( + App::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') + .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.is_present("search") { + let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect(); + let values = packages.join(", "); + println!("Searching for {}...", values); + return; + } + + let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect(); + let values = packages.join(", "); + + if sync_matches.is_present("info") { + println!("Retrieving info for {}...", values); + } else { + println!("Installing {}...", values); + } + } + Some(("query", query_matches)) => { + if let Some(packages) = query_matches.values_of("info") { + let comma_sep = packages.collect::>().join(", "); + println!("Retrieving info for {}...", comma_sep); + } else if let Some(queries) = query_matches.values_of("search") { + let comma_sep = queries.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/third_party/rust/clap/examples/tutorial_builder/01_quick.rs b/third_party/rust/clap/examples/tutorial_builder/01_quick.rs new file mode 100644 index 000000000000..f14a91814355 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/01_quick.rs @@ -0,0 +1,58 @@ +use clap::{app_from_crate, arg, App}; +use std::path::Path; + +fn main() { + let matches = app_from_crate!() + .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) + // Support non-UTF8 paths + .allow_invalid_utf8(true), + ) + .arg(arg!( + -d --debug ... "Turn debugging information on" + )) + .subcommand( + App::new("test") + .about("does testing things") + .arg(arg!(-l --list "lists test values")), + ) + .get_matches(); + + // You can check the value provided by positional arguments, or option arguments + if let Some(name) = matches.value_of("name") { + println!("Value for name: {}", name); + } + + if let Some(raw_config) = matches.value_of_os("config") { + let config_path = Path::new(raw_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.occurrences_of("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 app + if let Some(matches) = matches.subcommand_matches("test") { + // "$ myapp test" was run + if matches.is_present("list") { + // "$ myapp test -l" was run + println!("Printing testing lists..."); + } else { + println!("Not printing testing lists..."); + } + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs b/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs new file mode 100644 index 000000000000..6cfca11f6f84 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs @@ -0,0 +1,14 @@ +use clap::{app_from_crate, arg, AppSettings}; + +fn main() { + let matches = app_from_crate!() + .global_setting(AppSettings::AllArgsOverrideSelf) + .global_setting(AppSettings::DeriveDisplayOrder) + .global_setting(AppSettings::AllowNegativeNumbers) + .arg(arg!(--two )) + .arg(arg!(--one )) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_apps.rs b/third_party/rust/clap/examples/tutorial_builder/02_apps.rs new file mode 100644 index 000000000000..b607b7f19a79 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_apps.rs @@ -0,0 +1,14 @@ +use clap::{arg, App}; + +fn main() { + let matches = App::new("MyApp") + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .arg(arg!(--two )) + .arg(arg!(--one )) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_crate.rs b/third_party/rust/clap/examples/tutorial_builder/02_crate.rs new file mode 100644 index 000000000000..c36299dab62e --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_crate.rs @@ -0,0 +1,11 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg(arg!(--two )) + .arg(arg!(--one )) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs new file mode 100644 index 000000000000..f19b65b88ee9 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs @@ -0,0 +1,7 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!().arg(arg!(-v - -verbose)).get_matches(); + + println!("verbose: {:?}", matches.is_present("verbose")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs new file mode 100644 index 000000000000..6fc15b26816f --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs @@ -0,0 +1,7 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!().arg(arg!(-v --verbose ...)).get_matches(); + + println!("verbose: {:?}", matches.occurrences_of("verbose")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs b/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs new file mode 100644 index 000000000000..d03afe0f7b41 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs @@ -0,0 +1,9 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg(arg!(-n --name ).required(false)) + .get_matches(); + + println!("name: {:?}", matches.value_of("name")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs b/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs new file mode 100644 index 000000000000..ea77ccc2ea2c --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs @@ -0,0 +1,7 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!().arg(arg!([NAME])).get_matches(); + + println!("NAME: {:?}", matches.value_of("NAME")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs b/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs new file mode 100644 index 000000000000..f414ccd5dfb1 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs @@ -0,0 +1,22 @@ +use clap::{app_from_crate, arg, App, AppSettings}; + +fn main() { + let matches = app_from_crate!() + .global_setting(AppSettings::PropagateVersion) + .global_setting(AppSettings::UseLongFormatForHelpSubcommand) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + App::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.value_of("NAME") + ), + _ => unreachable!(), + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs b/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs new file mode 100644 index 000000000000..28bef52b6d87 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs @@ -0,0 +1,14 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg(arg!([NAME]).default_value("alice")) + .get_matches(); + + println!( + "NAME: {:?}", + matches + .value_of("NAME") + .expect("default ensures there is always a value") + ); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs b/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs new file mode 100644 index 000000000000..c3ac8be1bdd7 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs @@ -0,0 +1,60 @@ +use clap::{app_from_crate, arg, ArgEnum, PossibleValue}; + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum)] +enum Mode { + Fast, + Slow, +} + +impl Mode { + pub fn possible_values() -> impl Iterator> { + Mode::value_variants() + .iter() + .filter_map(ArgEnum::to_possible_value) + } +} + +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 = app_from_crate!() + .arg( + arg!() + .help("What mode to run the program in") + .possible_values(Mode::possible_values()), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .value_of_t("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs b/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs new file mode 100644 index 000000000000..33ca131a1379 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs @@ -0,0 +1,25 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg( + arg!() + .help("What mode to run the program in") + .possible_values(["fast", "slow"]), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .value_of("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + { + "fast" => { + println!("Hare"); + } + "slow" => { + println!("Tortoise"); + } + _ => unreachable!(), + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs b/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs new file mode 100644 index 000000000000..ff2bebbe8336 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs @@ -0,0 +1,17 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app_from_crate!() + .arg( + arg!() + .help("Network port to use") + .validator(|s| s.parse::()), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = matches + .value_of_t("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs b/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs new file mode 100644 index 000000000000..fdd74411b38d --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs @@ -0,0 +1,67 @@ +use clap::{app_from_crate, arg, ArgGroup}; + +fn main() { + // Create application like normal + let matches = app_from_crate!() + // Add the version arguments + .arg(arg!(--"set-ver" "set version manually").required(false)) + .arg(arg!(--major "auto inc major")) + .arg(arg!(--minor "auto inc minor")) + .arg(arg!(--patch "auto inc patch")) + // 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").group("input")) + .arg( + arg!(--"spec-in" "some special input argument") + .required(false) + .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).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.value_of("set-ver") { + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = ( + matches.is_present("major"), + matches.is_present("minor"), + matches.is_present("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.is_present("config") { + let input = matches + .value_of("INPUT_FILE") + .unwrap_or_else(|| matches.value_of("spec-in").unwrap()); + println!( + "Doing work using input {} and config {}", + input, + matches.value_of("config").unwrap() + ); + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs b/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs new file mode 100644 index 000000000000..2a4e9b8556c2 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs @@ -0,0 +1,78 @@ +use clap::{app_from_crate, arg, ErrorKind}; + +fn main() { + // Create application like normal + let mut app = app_from_crate!() + // Add the version arguments + .arg(arg!(--"set-ver" "set version manually").required(false)) + .arg(arg!(--major "auto inc major")) + .arg(arg!(--minor "auto inc minor")) + .arg(arg!(--patch "auto inc 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")) + .arg(arg!(--"spec-in" "some special input argument").required(false)) + // 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)); + let matches = app.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.value_of("set-ver") { + if matches.is_present("major") || matches.is_present("minor") || matches.is_present("patch") + { + app.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.is_present("major"), + matches.is_present("minor"), + matches.is_present("patch"), + ); + match (maj, min, pat) { + (true, false, false) => major += 1, + (false, true, false) => minor += 1, + (false, false, true) => patch += 1, + _ => { + app.error( + ErrorKind::ArgumentConflict, + "Cam only modify one version field", + ) + .exit(); + } + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if matches.is_present("config") { + let input = matches + .value_of("INPUT_FILE") + .or_else(|| matches.value_of("spec-in")) + .unwrap_or_else(|| { + app.error( + ErrorKind::MissingRequiredArgument, + "INPUT_FILE or --spec-in is required when using --config", + ) + .exit() + }); + println!( + "Doing work using input {} and config {}", + input, + matches.value_of("config").unwrap() + ); + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs b/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs new file mode 100644 index 000000000000..034367e79647 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs @@ -0,0 +1,24 @@ +use clap::{app_from_crate, arg}; + +fn main() { + let matches = app().get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = matches + .value_of_t("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +fn app() -> clap::App<'static> { + app_from_crate!().arg( + arg!() + .help("Network port to use") + .validator(|s| s.parse::()), + ) +} + +#[test] +fn verify_app() { + app().debug_assert(); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/README.md b/third_party/rust/clap/examples/tutorial_builder/README.md new file mode 100644 index 000000000000..2679806f926b --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/README.md @@ -0,0 +1,622 @@ +# 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. [Flags](#flags) + 2. [Options](#options) + 3. [Positionals](#positionals) + 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 `App` 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 `app_from_crate!()` 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 `AppSettings` to change the application level behavior of clap. You +can apply the setting to the top level command (`app.setting()`) or to it and +all subcommands (`app.global_setting()`). + +[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 + +### Flags + +Flags are 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 +? failed +error: The argument '--verbose' was provided more than once, but cannot be used multiple times + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +For more information try --help + +``` + +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 + +``` + +### Options + +Flags can also accept a value. + +[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") + +``` + +### Positionals + +Or 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") + +``` + +### Subcommands + +Subcommands are defined as `App`s that get added via `App::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 +? 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) + +$ 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 `AppSettings::PropagateVersion`: +```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 +`Arg::possible_values()`. + +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] + +USAGE: + 04_01_possible[EXE] + +For more information try --help + +``` + +When enabling the `derive` feature, you can use `ArgEnum` 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] + +USAGE: + 04_01_enum[EXE] + +For more information try --help + +``` + +### Validated values + +More generally, you can validate and parse into any data type. + +[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 for '': invalid digit found in string + +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: Cam 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: Cam 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 + +- Proactively check for bad `App` configurations by calling `App::debug_assert` ([example](05_01_assert.rs)) + +## Contributing + +New example code: +- 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/third_party/rust/clap/examples/tutorial_derive/01_quick.rs b/third_party/rust/clap/examples/tutorial_derive/01_quick.rs new file mode 100644 index 000000000000..9bd1c52ccc60 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/01_quick.rs @@ -0,0 +1,68 @@ +use std::path::PathBuf; + +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Optional name to operate on + name: Option, + + /// Sets a custom config file + #[clap(short, long, parse(from_os_str), value_name = "FILE")] + config: Option, + + /// Turn debugging information on + #[clap(short, long, parse(from_occurrences))] + debug: usize, + + #[clap(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Commands { + /// does testing things + Test { + /// lists test values + #[clap(short, long)] + 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 app + 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/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs b/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs new file mode 100644 index 000000000000..6c9fbd73cb98 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs @@ -0,0 +1,20 @@ +use clap::{AppSettings, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(global_setting(AppSettings::AllArgsOverrideSelf))] +#[clap(global_setting(AppSettings::DeriveDisplayOrder))] +#[clap(global_setting(AppSettings::AllowNegativeNumbers))] +struct Cli { + #[clap(long)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/02_apps.rs b/third_party/rust/clap/examples/tutorial_derive/02_apps.rs new file mode 100644 index 000000000000..442e928a9f6d --- /dev/null +++ b/third_party/rust/clap/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)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/02_crate.rs b/third_party/rust/clap/examples/tutorial_derive/02_crate.rs new file mode 100644 index 000000000000..93f7888af31e --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/02_crate.rs @@ -0,0 +1,17 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(long)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_01_flag_bool.rs b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_bool.rs new file mode 100644 index 000000000000..8b574b7481ec --- /dev/null +++ b/third_party/rust/clap/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)] + verbose: bool, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_01_flag_count.rs b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_count.rs new file mode 100644 index 000000000000..2ab883977aeb --- /dev/null +++ b/third_party/rust/clap/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, parse(from_occurrences))] + verbose: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_02_option.rs b/third_party/rust/clap/examples/tutorial_derive/03_02_option.rs new file mode 100644 index 000000000000..b09aadf20de3 --- /dev/null +++ b/third_party/rust/clap/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)] + name: Option, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs b/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs new file mode 100644 index 000000000000..f7850ddccfe5 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs @@ -0,0 +1,13 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + name: Option, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs new file mode 100644 index 000000000000..8e272dcdd0a2 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs @@ -0,0 +1,28 @@ +use clap::{AppSettings, Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(global_setting(AppSettings::PropagateVersion))] +#[clap(global_setting(AppSettings::UseLongFormatForHelpSubcommand))] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Adds files to myapp + Add { 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 app + match &cli.command { + Commands::Add { name } => { + println!("'myapp add' was used, name is: {:?}", name) + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_05_default_values.rs b/third_party/rust/clap/examples/tutorial_derive/03_05_default_values.rs new file mode 100644 index 000000000000..af4532bbc7dd --- /dev/null +++ b/third_party/rust/clap/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"))] + name: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs b/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs new file mode 100644 index 000000000000..3a2df391ffba --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs @@ -0,0 +1,28 @@ +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)] + 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/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs b/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs new file mode 100644 index 000000000000..5f4cbadc0452 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs @@ -0,0 +1,15 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(parse(try_from_str))] + port: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_03_relations.rs b/third_party/rust/clap/examples/tutorial_derive/04_03_relations.rs new file mode 100644 index 000000000000..f0e1e5913bac --- /dev/null +++ b/third_party/rust/clap/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")] + set_ver: Option, + + /// auto inc major + #[clap(long)] + major: bool, + + /// auto inc minor + #[clap(long)] + minor: bool, + + /// auto inc patch + #[clap(long)] + patch: bool, + + /// some regular input + #[clap(group = "input")] + input_file: Option, + + /// some special input argument + #[clap(long, group = "input")] + spec_in: Option, + + #[clap(short, requires = "input")] + 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/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs b/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs new file mode 100644 index 000000000000..e3c1387d4621 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs @@ -0,0 +1,92 @@ +use clap::{ErrorKind, IntoApp, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// set version manually + #[clap(long, value_name = "VER")] + set_ver: Option, + + /// auto inc major + #[clap(long)] + major: bool, + + /// auto inc minor + #[clap(long)] + minor: bool, + + /// auto inc patch + #[clap(long)] + patch: bool, + + /// some regular input + input_file: Option, + + /// some special input argument + #[clap(long)] + spec_in: Option, + + #[clap(short)] + 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 app = Cli::into_app(); + app.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 app = Cli::into_app(); + app.error( + ErrorKind::ArgumentConflict, + "Cam 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 app = Cli::into_app(); + app.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/third_party/rust/clap/examples/tutorial_derive/05_01_assert.rs b/third_party/rust/clap/examples/tutorial_derive/05_01_assert.rs new file mode 100644 index 000000000000..52dd5d2cbaba --- /dev/null +++ b/third_party/rust/clap/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(parse(try_from_str))] + port: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} + +#[test] +fn verify_app() { + use clap::IntoApp; + Cli::into_app().debug_assert() +} diff --git a/third_party/rust/clap/examples/tutorial_derive/README.md b/third_party/rust/clap/examples/tutorial_derive/README.md new file mode 100644 index 000000000000..14e627fae401 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/README.md @@ -0,0 +1,588 @@ +# 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. [Flags](#flags) + 2. [Options](#options) + 3. [Positionals](#positionals) + 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 the `App` 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 `app_from_crate!()` 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 `AppSettings` to change the application level behavior of clap. You +can apply the setting to the top level command (`app.setting()`) or to it and +all subcommands (`app.global_setting()`). + +[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 + +### Flags + +Flags are switches that can be on/off: + +[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 +? failed +error: The argument '--verbose' was provided more than once, but cannot be used multiple times + +USAGE: + 03_01_flag_bool_derive[EXE] [OPTIONS] + +For more information try --help + +``` + +Or counted. + +[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 + +``` + +### Options + +Flags can also accept a value. + +[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") + +``` + +### Positionals + +Or 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") + +``` + +### Subcommands + +Subcommands are defined as `App`s that get added via `App::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_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) + +$ 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 set `AppSettings::PropagateVersion`: +```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 a `Option` and can `unwrap_or`. Alternatively, you can +set `Arg::default_value`. + +[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 +`ArgEnum`. + +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] + +USAGE: + 04_01_enum_derive[EXE] + +For more information try --help + +``` + +### Validated values + +More generally, you can validate and parse into any data type. + +[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 for '': invalid digit found in string + +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: Cam 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: Cam 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 + +- Proactively check for bad `App` configurations by calling `App::debug_assert` ([example](05_01_assert.rs)) + +## Contributing + +New example code: +- 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/third_party/rust/clap/justfile b/third_party/rust/clap/justfile deleted file mode 100644 index 0768764b30c2..000000000000 --- a/third_party/rust/clap/justfile +++ /dev/null @@ -1,39 +0,0 @@ -@update-contributors: - echo 'Removing old CONTRIBUTORS.md' - mv CONTRIBUTORS.md CONTRIBUTORS.md.bak - echo 'Downloading a list of new contributors' - echo "the following is a list of contributors:" > CONTRIBUTORS.md - echo "" >> CONTRIBUTORS.md - echo "" >> CONTRIBUTORS.md - githubcontrib --owner clap-rs --repo clap --sha master --cols 6 --format md --showlogin true --sortBy contributions --sortOrder desc >> CONTRIBUTORS.md - echo "" >> CONTRIBUTORS.md - echo "" >> CONTRIBUTORS.md - echo "This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)" >> CONTRIBUTORS.md - rm CONTRIBUTORS.md.bak - -run-test TEST: - cargo test --test {{TEST}} - -debug TEST: - cargo test --test {{TEST}} --features debug - -run-tests: - cargo test --features "yaml unstable" - -@bench: nightly - cargo bench && just remove-nightly - -nightly: - rustup override add nightly - -remove-nightly: - rustup override remove - -@lint: nightly - cargo build --features lints && just remove-nightly - -clean: - cargo clean - find . -type f -name "*.orig" -exec rm {} \; - find . -type f -name "*.bk" -exec rm {} \; - find . -type f -name ".*~" -exec rm {} \; diff --git a/third_party/rust/clap/src/app/help.rs b/third_party/rust/clap/src/app/help.rs deleted file mode 100644 index e5f2a608daf1..000000000000 --- a/third_party/rust/clap/src/app/help.rs +++ /dev/null @@ -1,1032 +0,0 @@ -// Std -use std::{ - borrow::Cow, - cmp, - collections::BTreeMap, - fmt::Display, - io::{self, Cursor, Read, Write}, - usize, -}; - -// Third Party -#[cfg(feature = "wrap_help")] -use term_size; -#[cfg(feature = "wrap_help")] -use textwrap; -use unicode_width::UnicodeWidthStr; - -// Internal -use crate::{ - app::{parser::Parser, usage, App, AppSettings}, - args::{AnyArg, ArgSettings, DispOrder}, - errors::{Error, Result as ClapResult}, - fmt::{Colorizer, ColorizerOption, Format}, - map::VecMap, - INTERNAL_ERROR_MSG, -}; - -#[cfg(not(feature = "wrap_help"))] -mod term_size { - pub fn dimensions() -> Option<(usize, usize)> { - None - } -} - -fn str_width(s: &str) -> usize { - UnicodeWidthStr::width(s) -} - -const TAB: &str = " "; - -// These are just convenient traits to make the code easier to read. -trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {} -impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T where T: AnyArg<'b, 'c> + Display {} - -trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder { - fn as_base(&self) -> &ArgWithDisplay<'b, 'c>; -} -impl<'b, 'c, T> ArgWithOrder<'b, 'c> for T -where - T: ArgWithDisplay<'b, 'c> + DispOrder, -{ - fn as_base(&self) -> &ArgWithDisplay<'b, 'c> { - self - } -} - -fn as_arg_trait<'a, 'b, T: ArgWithOrder<'a, 'b>>(x: &T) -> &ArgWithOrder<'a, 'b> { - x -} - -impl<'b, 'c> DispOrder for App<'b, 'c> { - fn disp_ord(&self) -> usize { - 999 - } -} - -macro_rules! color { - ($_self:ident, $s:expr, $c:ident) => { - if $_self.color { - write!($_self.writer, "{}", $_self.cizer.$c($s)) - } else { - write!($_self.writer, "{}", $s) - } - }; - ($_self:ident, $fmt_s:expr, $v:expr, $c:ident) => { - if $_self.color { - write!($_self.writer, "{}", $_self.cizer.$c(format!($fmt_s, $v))) - } else { - write!($_self.writer, $fmt_s, $v) - } - }; -} - -/// `clap` Help Writer. -/// -/// Wraps a writer stream providing different methods to generate help for `clap` objects. -pub struct Help<'a> { - writer: &'a mut Write, - next_line_help: bool, - hide_pv: bool, - term_w: usize, - color: bool, - cizer: Colorizer, - longest: usize, - force_next_line: bool, - use_long: bool, -} - -// Public Functions -impl<'a> Help<'a> { - /// Create a new `Help` instance. - #[cfg_attr(feature = "cargo-clippy", allow(clippy::too_many_arguments))] - pub fn new( - w: &'a mut Write, - next_line_help: bool, - hide_pv: bool, - color: bool, - cizer: Colorizer, - term_w: Option, - max_w: Option, - use_long: bool, - ) -> Self { - debugln!("Help::new;"); - Help { - writer: w, - next_line_help, - hide_pv, - term_w: match term_w { - Some(width) => { - if width == 0 { - usize::MAX - } else { - width - } - } - None => cmp::min( - term_size::dimensions().map_or(120, |(w, _)| w), - match max_w { - None | Some(0) => usize::MAX, - Some(mw) => mw, - }, - ), - }, - color, - cizer, - longest: 0, - force_next_line: false, - use_long, - } - } - - /// Reads help settings from an App - /// and write its help to the wrapped stream. - pub fn write_app_help(w: &'a mut Write, app: &App, use_long: bool) -> ClapResult<()> { - debugln!("Help::write_app_help;"); - Self::write_parser_help(w, &app.p, use_long) - } - - /// Reads help settings from a Parser - /// and write its help to the wrapped stream. - pub fn write_parser_help(w: &'a mut Write, parser: &Parser, use_long: bool) -> ClapResult<()> { - debugln!("Help::write_parser_help;"); - Self::_write_parser_help(w, parser, false, use_long) - } - - /// Reads help settings from a Parser - /// and write its help to the wrapped stream which will be stderr. This method prevents - /// formatting when required. - pub fn write_parser_help_to_stderr(w: &'a mut Write, parser: &Parser) -> ClapResult<()> { - debugln!("Help::write_parser_help;"); - Self::_write_parser_help(w, parser, true, false) - } - - #[doc(hidden)] - pub fn _write_parser_help( - w: &'a mut Write, - parser: &Parser, - stderr: bool, - use_long: bool, - ) -> ClapResult<()> { - debugln!("Help::write_parser_help;"); - let nlh = parser.is_set(AppSettings::NextLineHelp); - let hide_v = parser.is_set(AppSettings::HidePossibleValuesInHelp); - let color = parser.is_set(AppSettings::ColoredHelp); - let cizer = Colorizer::new(ColorizerOption { - use_stderr: stderr, - when: parser.color(), - }); - Self::new( - w, - nlh, - hide_v, - color, - cizer, - parser.meta.term_w, - parser.meta.max_w, - use_long, - ) - .write_help(parser) - } - - /// Writes the parser help to the wrapped stream. - pub fn write_help(&mut self, parser: &Parser) -> ClapResult<()> { - debugln!("Help::write_help;"); - if let Some(h) = parser.meta.help_str { - write!(self.writer, "{}", h).map_err(Error::from)?; - } else if let Some(tmpl) = parser.meta.template { - self.write_templated_help(parser, tmpl)?; - } else { - self.write_default_help(parser)?; - } - Ok(()) - } -} - -// Methods to write AnyArg help. -impl<'a> Help<'a> { - /// Writes help for each argument in the order they were declared to the wrapped stream. - fn write_args_unsorted<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> - where - I: Iterator>, - { - debugln!("Help::write_args_unsorted;"); - // The shortest an arg can legally be is 2 (i.e. '-x') - self.longest = 2; - let mut arg_v = Vec::with_capacity(10); - let use_long = self.use_long; - for arg in args.filter(|arg| should_show_arg(use_long, *arg)) { - if arg.longest_filter() { - self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); - } - arg_v.push(arg) - } - let mut first = true; - for arg in arg_v { - if first { - first = false; - } else { - self.writer.write_all(b"\n")?; - } - self.write_arg(arg.as_base())?; - } - Ok(()) - } - - /// Sorts arguments by length and display order and write their help to the wrapped stream. - fn write_args<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> - where - I: Iterator>, - { - debugln!("Help::write_args;"); - // The shortest an arg can legally be is 2 (i.e. '-x') - self.longest = 2; - let mut ord_m = VecMap::new(); - let use_long = self.use_long; - // Determine the longest - for arg in args.filter(|arg| { - // If it's NextLineHelp, but we don't care to compute how long because it may be - // NextLineHelp on purpose *because* it's so long and would throw off all other - // args alignment - should_show_arg(use_long, *arg) - }) { - if arg.longest_filter() { - debugln!("Help::write_args: Current Longest...{}", self.longest); - self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); - debugln!("Help::write_args: New Longest...{}", self.longest); - } - let btm = ord_m.entry(arg.disp_ord()).or_insert(BTreeMap::new()); - btm.insert(arg.name(), arg); - } - let mut first = true; - for btm in ord_m.values() { - for arg in btm.values() { - if first { - first = false; - } else { - self.writer.write_all(b"\n")?; - } - self.write_arg(arg.as_base())?; - } - } - Ok(()) - } - - /// Writes help for an argument to the wrapped stream. - fn write_arg<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { - debugln!("Help::write_arg;"); - self.short(arg)?; - self.long(arg)?; - let spec_vals = self.val(arg)?; - self.help(arg, &*spec_vals)?; - Ok(()) - } - - /// Writes argument's short command to the wrapped stream. - fn short<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { - debugln!("Help::short;"); - write!(self.writer, "{}", TAB)?; - if let Some(s) = arg.short() { - color!(self, "-{}", s, good) - } else if arg.has_switch() { - write!(self.writer, "{}", TAB) - } else { - Ok(()) - } - } - - /// Writes argument's long command to the wrapped stream. - fn long<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { - debugln!("Help::long;"); - if !arg.has_switch() { - return Ok(()); - } - if arg.takes_value() { - if let Some(l) = arg.long() { - if arg.short().is_some() { - write!(self.writer, ", ")?; - } - color!(self, "--{}", l, good)? - } - - let sep = if arg.is_set(ArgSettings::RequireEquals) { - "=" - } else { - " " - }; - write!(self.writer, "{}", sep)?; - } else if let Some(l) = arg.long() { - if arg.short().is_some() { - write!(self.writer, ", ")?; - } - color!(self, "--{}", l, good)?; - } - Ok(()) - } - - /// Writes argument's possible values to the wrapped stream. - fn val<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> Result { - debugln!("Help::val: arg={}", arg); - if arg.takes_value() { - let delim = if arg.is_set(ArgSettings::RequireDelimiter) { - arg.val_delim().expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }; - if let Some(vec) = arg.val_names() { - let mut it = vec.iter().peekable(); - while let Some((_, val)) = it.next() { - color!(self, "<{}>", val, good)?; - if it.peek().is_some() { - write!(self.writer, "{}", delim)?; - } - } - let num = vec.len(); - if arg.is_set(ArgSettings::Multiple) && num == 1 { - color!(self, "...", good)?; - } - } else if let Some(num) = arg.num_vals() { - let mut it = (0..num).peekable(); - while let Some(_) = it.next() { - color!(self, "<{}>", arg.name(), good)?; - if it.peek().is_some() { - write!(self.writer, "{}", delim)?; - } - } - if arg.is_set(ArgSettings::Multiple) && num == 1 { - color!(self, "...", good)?; - } - } else if arg.has_switch() { - color!(self, "<{}>", arg.name(), good)?; - if arg.is_set(ArgSettings::Multiple) { - color!(self, "...", good)?; - } - } else { - color!(self, "{}", arg, good)?; - } - } - - let spec_vals = self.spec_vals(arg); - let h = arg.help().unwrap_or(""); - let h_w = str_width(h) + str_width(&*spec_vals); - let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp); - let taken = self.longest + 12; - self.force_next_line = !nlh - && self.term_w >= taken - && (taken as f32 / self.term_w as f32) > 0.40 - && h_w > (self.term_w - taken); - - debug!("Help::val: Has switch..."); - if arg.has_switch() { - sdebugln!("Yes"); - debugln!("Help::val: force_next_line...{:?}", self.force_next_line); - debugln!("Help::val: nlh...{:?}", nlh); - debugln!("Help::val: taken...{}", taken); - debugln!( - "Help::val: help_width > (width - taken)...{} > ({} - {})", - h_w, - self.term_w, - taken - ); - debugln!("Help::val: longest...{}", self.longest); - debug!("Help::val: next_line..."); - if !(nlh || self.force_next_line) { - sdebugln!("No"); - let self_len = str_width(arg.to_string().as_str()); - // subtract ourself - let mut spcs = self.longest - self_len; - // Since we're writing spaces from the tab point we first need to know if we - // had a long and short, or just short - if arg.long().is_some() { - // Only account 4 after the val - spcs += 4; - } else { - // Only account for ', --' + 4 after the val - spcs += 8; - } - - write_nspaces!(self.writer, spcs); - } else { - sdebugln!("Yes"); - } - } else if !(nlh || self.force_next_line) { - sdebugln!("No, and not next_line"); - write_nspaces!( - self.writer, - self.longest + 4 - (str_width(arg.to_string().as_str())) - ); - } else { - sdebugln!("No"); - } - Ok(spec_vals) - } - - fn write_before_after_help(&mut self, h: &str) -> io::Result<()> { - debugln!("Help::write_before_after_help;"); - let mut help = String::from(h); - // determine if our help fits or needs to wrap - debugln!( - "Help::write_before_after_help: Term width...{}", - self.term_w - ); - let too_long = str_width(h) >= self.term_w; - - debug!("Help::write_before_after_help: Too long..."); - if too_long || h.contains("{n}") { - sdebugln!("Yes"); - debugln!("Help::write_before_after_help: help: {}", help); - debugln!( - "Help::write_before_after_help: help width: {}", - str_width(&*help) - ); - // Determine how many newlines we need to insert - debugln!( - "Help::write_before_after_help: Usable space: {}", - self.term_w - ); - help = wrap_help(&help.replace("{n}", "\n"), self.term_w); - } else { - sdebugln!("No"); - } - write!(self.writer, "{}", help)?; - Ok(()) - } - - /// Writes argument's help to the wrapped stream. - fn help<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>, spec_vals: &str) -> io::Result<()> { - debugln!("Help::help;"); - let h = if self.use_long && arg.name() != "" { - arg.long_help().unwrap_or_else(|| arg.help().unwrap_or("")) - } else { - arg.help().unwrap_or_else(|| arg.long_help().unwrap_or("")) - }; - let mut help = String::from(h) + spec_vals; - let nlh = self.next_line_help - || arg.is_set(ArgSettings::NextLineHelp) - || (self.use_long && arg.name() != ""); - debugln!("Help::help: Next Line...{:?}", nlh); - - let spcs = if nlh || self.force_next_line { - 12 // "tab" * 3 - } else { - self.longest + 12 - }; - - let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w; - - // Is help on next line, if so then indent - if nlh || self.force_next_line { - write!(self.writer, "\n{}{}{}", TAB, TAB, TAB)?; - } - - debug!("Help::help: Too long..."); - if too_long && spcs <= self.term_w || h.contains("{n}") { - sdebugln!("Yes"); - debugln!("Help::help: help...{}", help); - debugln!("Help::help: help width...{}", str_width(&*help)); - // Determine how many newlines we need to insert - let avail_chars = self.term_w - spcs; - debugln!("Help::help: Usable space...{}", avail_chars); - help = wrap_help(&help.replace("{n}", "\n"), avail_chars); - } else { - sdebugln!("No"); - } - if let Some(part) = help.lines().next() { - write!(self.writer, "{}", part)?; - } - for part in help.lines().skip(1) { - writeln!(self.writer)?; - if nlh || self.force_next_line { - write!(self.writer, "{}{}{}", TAB, TAB, TAB)?; - } else if arg.has_switch() { - write_nspaces!(self.writer, self.longest + 12); - } else { - write_nspaces!(self.writer, self.longest + 8); - } - write!(self.writer, "{}", part)?; - } - if !help.contains('\n') && (nlh || self.force_next_line) { - writeln!(self.writer)?; - } - Ok(()) - } - - fn spec_vals(&self, a: &ArgWithDisplay) -> String { - debugln!("Help::spec_vals: a={}", a); - let mut spec_vals = vec![]; - if let Some(ref env) = a.env() { - debugln!( - "Help::spec_vals: Found environment variable...[{:?}:{:?}]", - env.0, - env.1 - ); - let env_val = if !a.is_set(ArgSettings::HideEnvValues) { - format!( - "={}", - env.1.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_set(ArgSettings::HideDefaultValue) { - if let Some(pv) = a.default_val() { - debugln!("Help::spec_vals: Found default value...[{:?}]", pv); - spec_vals.push(format!( - " [default: {}]", - if self.color { - self.cizer.good(pv.to_string_lossy()) - } else { - Format::None(pv.to_string_lossy()) - } - )); - } - } - if let Some(ref aliases) = a.aliases() { - debugln!("Help::spec_vals: Found aliases...{:?}", aliases); - spec_vals.push(format!( - " [aliases: {}]", - if self.color { - aliases - .iter() - .map(|v| format!("{}", self.cizer.good(v))) - .collect::>() - .join(", ") - } else { - aliases.join(", ") - } - )); - } - if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) { - if let Some(pv) = a.possible_vals() { - debugln!("Help::spec_vals: Found possible vals...{:?}", pv); - spec_vals.push(if self.color { - format!( - " [possible values: {}]", - pv.iter() - .map(|v| format!("{}", self.cizer.good(v))) - .collect::>() - .join(", ") - ) - } else { - format!(" [possible values: {}]", pv.join(", ")) - }); - } - } - spec_vals.join(" ") - } -} - -fn should_show_arg(use_long: bool, arg: &ArgWithOrder) -> bool { - if arg.is_set(ArgSettings::Hidden) { - return false; - } - - (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long) - || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long) - || arg.is_set(ArgSettings::NextLineHelp) -} - -// Methods to write Parser help. -impl<'a> Help<'a> { - /// Writes help for all arguments (options, flags, args, subcommands) - /// including titles of a Parser Object to the wrapped stream. - pub fn write_all_args(&mut self, parser: &Parser) -> ClapResult<()> { - debugln!("Help::write_all_args;"); - let flags = parser.has_flags(); - let pos = parser - .positionals() - .filter(|arg| !arg.is_set(ArgSettings::Hidden)) - .count() - > 0; - let opts = parser.has_opts(); - let subcmds = parser.has_visible_subcommands(); - - let unified_help = parser.is_set(AppSettings::UnifiedHelpMessage); - - let mut first = true; - - if unified_help && (flags || opts) { - let opts_flags = parser - .flags() - .map(as_arg_trait) - .chain(parser.opts().map(as_arg_trait)); - color!(self, "OPTIONS:\n", warning)?; - self.write_args(opts_flags)?; - first = false; - } else { - if flags { - color!(self, "FLAGS:\n", warning)?; - self.write_args(parser.flags().map(as_arg_trait))?; - first = false; - } - if opts { - if !first { - self.writer.write_all(b"\n\n")?; - } - color!(self, "OPTIONS:\n", warning)?; - self.write_args(parser.opts().map(as_arg_trait))?; - first = false; - } - } - - if pos { - if !first { - self.writer.write_all(b"\n\n")?; - } - color!(self, "ARGS:\n", warning)?; - self.write_args_unsorted(parser.positionals().map(as_arg_trait))?; - first = false; - } - - if subcmds { - if !first { - self.writer.write_all(b"\n\n")?; - } - color!(self, "SUBCOMMANDS:\n", warning)?; - self.write_subcommands(parser)?; - } - - Ok(()) - } - - /// Writes help for subcommands of a Parser Object to the wrapped stream. - fn write_subcommands(&mut self, parser: &Parser) -> io::Result<()> { - debugln!("Help::write_subcommands;"); - // The shortest an arg can legally be is 2 (i.e. '-x') - self.longest = 2; - let mut ord_m = VecMap::new(); - for sc in parser - .subcommands - .iter() - .filter(|s| !s.p.is_set(AppSettings::Hidden)) - { - let btm = ord_m.entry(sc.p.meta.disp_ord).or_insert(BTreeMap::new()); - self.longest = cmp::max(self.longest, str_width(sc.p.meta.name.as_str())); - //self.longest = cmp::max(self.longest, sc.p.meta.name.len()); - btm.insert(sc.p.meta.name.clone(), sc.clone()); - } - - let mut first = true; - for btm in ord_m.values() { - for sc in btm.values() { - if first { - first = false; - } else { - self.writer.write_all(b"\n")?; - } - self.write_arg(sc)?; - } - } - Ok(()) - } - - /// Writes version of a Parser Object to the wrapped stream. - fn write_version(&mut self, parser: &Parser) -> io::Result<()> { - debugln!("Help::write_version;"); - write!(self.writer, "{}", parser.meta.version.unwrap_or(""))?; - Ok(()) - } - - /// Writes binary name of a Parser Object to the wrapped stream. - fn write_bin_name(&mut self, parser: &Parser) -> io::Result<()> { - debugln!("Help::write_bin_name;"); - macro_rules! write_name { - () => {{ - let mut name = parser.meta.name.clone(); - name = name.replace("{n}", "\n"); - color!(self, wrap_help(&name, self.term_w), good)?; - }}; - } - if let Some(bn) = parser.meta.bin_name.as_ref() { - if bn.contains(' ') { - // Incase we're dealing with subcommands i.e. git mv is translated to git-mv - color!(self, bn.replace(" ", "-"), good)? - } else { - write_name!(); - } - } else { - write_name!(); - } - Ok(()) - } - - /// Writes default help for a Parser Object to the wrapped stream. - pub fn write_default_help(&mut self, parser: &Parser) -> ClapResult<()> { - debugln!("Help::write_default_help;"); - if let Some(h) = parser.meta.pre_help { - self.write_before_after_help(h)?; - self.writer.write_all(b"\n\n")?; - } - - macro_rules! write_thing { - ($thing:expr) => {{ - let mut owned_thing = $thing.to_owned(); - owned_thing = owned_thing.replace("{n}", "\n"); - write!(self.writer, "{}\n", wrap_help(&owned_thing, self.term_w))? - }}; - } - // Print the version - self.write_bin_name(parser)?; - self.writer.write_all(b" ")?; - self.write_version(parser)?; - self.writer.write_all(b"\n")?; - if let Some(author) = parser.meta.author { - write_thing!(author) - } - // if self.use_long { - // if let Some(about) = parser.meta.long_about { - // debugln!("Help::write_default_help: writing long about"); - // write_thing!(about) - // } else if let Some(about) = parser.meta.about { - // debugln!("Help::write_default_help: writing about"); - // write_thing!(about) - // } - // } else - if let Some(about) = parser.meta.long_about { - debugln!("Help::write_default_help: writing long about"); - write_thing!(about) - } else if let Some(about) = parser.meta.about { - debugln!("Help::write_default_help: writing about"); - write_thing!(about) - } - - color!(self, "\nUSAGE:", warning)?; - write!( - self.writer, - "\n{}{}\n\n", - TAB, - usage::create_usage_no_title(parser, &[]) - )?; - - let flags = parser.has_flags(); - let pos = parser.has_positionals(); - let opts = parser.has_opts(); - let subcmds = parser.has_subcommands(); - - if flags || opts || pos || subcmds { - self.write_all_args(parser)?; - } - - if let Some(h) = parser.meta.more_help { - if flags || opts || pos || subcmds { - self.writer.write_all(b"\n\n")?; - } - self.write_before_after_help(h)?; - } - - self.writer.flush().map_err(Error::from) - } -} - -/// Possible results for a copying function that stops when a given -/// byte was found. -enum CopyUntilResult { - DelimiterFound(usize), - DelimiterNotFound(usize), - ReaderEmpty, - ReadError(io::Error), - WriteError(io::Error), -} - -/// Copies the contents of a reader into a writer until a delimiter byte is found. -/// On success, the total number of bytes that were -/// copied from reader to writer is returned. -fn copy_until(r: &mut R, w: &mut W, delimiter_byte: u8) -> CopyUntilResult { - debugln!("copy_until;"); - - let mut count = 0; - for wb in r.bytes() { - match wb { - Ok(b) => { - if b == delimiter_byte { - return CopyUntilResult::DelimiterFound(count); - } - match w.write(&[b]) { - Ok(c) => count += c, - Err(e) => return CopyUntilResult::WriteError(e), - } - } - Err(e) => return CopyUntilResult::ReadError(e), - } - } - if count > 0 { - CopyUntilResult::DelimiterNotFound(count) - } else { - CopyUntilResult::ReaderEmpty - } -} - -/// Copies the contents of a reader into a writer until a {tag} is found, -/// copying the tag content to a buffer and returning its size. -/// In addition to errors, there are three possible outputs: -/// - `None`: The reader was consumed. -/// - `Some(Ok(0))`: No tag was captured but the reader still contains data. -/// - `Some(Ok(length>0))`: a tag with `length` was captured to the `tag_buffer`. -fn copy_and_capture( - r: &mut R, - w: &mut W, - tag_buffer: &mut Cursor>, -) -> Option> { - use self::CopyUntilResult::*; - debugln!("copy_and_capture;"); - - // Find the opening byte. - match copy_until(r, w, b'{') { - // The end of the reader was reached without finding the opening tag. - // (either with or without having copied data to the writer) - // Return None indicating that we are done. - ReaderEmpty | DelimiterNotFound(_) => None, - - // Something went wrong. - ReadError(e) | WriteError(e) => Some(Err(e)), - - // The opening byte was found. - // (either with or without having copied data to the writer) - DelimiterFound(_) => { - // Lets reset the buffer first and find out how long it is. - tag_buffer.set_position(0); - let buffer_size = tag_buffer.get_ref().len(); - - // Find the closing byte,limiting the reader to the length of the buffer. - let mut rb = r.take(buffer_size as u64); - match copy_until(&mut rb, tag_buffer, b'}') { - // We were already at the end of the reader. - // Return None indicating that we are done. - ReaderEmpty => None, - - // The closing tag was found. - // Return the tag_length. - DelimiterFound(tag_length) => Some(Ok(tag_length)), - - // The end of the reader was found without finding the closing tag. - // Write the opening byte and captured text to the writer. - // Return 0 indicating that nothing was captured but the reader still contains data. - DelimiterNotFound(not_tag_length) => match w.write(b"{") { - Err(e) => Some(Err(e)), - _ => match w.write(&tag_buffer.get_ref()[0..not_tag_length]) { - Err(e) => Some(Err(e)), - _ => Some(Ok(0)), - }, - }, - - ReadError(e) | WriteError(e) => Some(Err(e)), - } - } - } -} - -// Methods to write Parser help using templates. -impl<'a> Help<'a> { - /// Write help to stream for the parser in the format defined by the template. - /// - /// Tags arg given inside curly brackets: - /// Valid tags are: - /// * `{bin}` - Binary name. - /// * `{version}` - Version number. - /// * `{author}` - Author information. - /// * `{usage}` - Automatically generated or given usage string. - /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, - /// and subcommands) including titles. - /// * `{unified}` - Unified help for options and flags. - /// * `{flags}` - Help for flags. - /// * `{options}` - Help for options. - /// * `{positionals}` - Help for positionals arguments. - /// * `{subcommands}` - Help for subcommands. - /// * `{after-help}` - Info to be displayed after the help message. - /// * `{before-help}` - Info to be displayed before the help message. - /// - /// The template system is, on purpose, very simple. Therefore the tags have to written - /// in the lowercase and without spacing. - fn write_templated_help(&mut self, parser: &Parser, template: &str) -> ClapResult<()> { - debugln!("Help::write_templated_help;"); - let mut tmplr = Cursor::new(&template); - let mut tag_buf = Cursor::new(vec![0u8; 15]); - - // 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. - - loop { - let tag_length = match copy_and_capture(&mut tmplr, &mut self.writer, &mut tag_buf) { - None => return Ok(()), - Some(Err(e)) => return Err(Error::from(e)), - Some(Ok(val)) if val > 0 => val, - _ => continue, - }; - - debugln!("Help::write_template_help:iter: tag_buf={};", unsafe { - String::from_utf8_unchecked( - tag_buf.get_ref()[0..tag_length] - .iter() - .map(|&i| i) - .collect::>(), - ) - }); - match &tag_buf.get_ref()[0..tag_length] { - b"?" => { - self.writer.write_all(b"Could not decode tag name")?; - } - b"bin" => { - self.write_bin_name(parser)?; - } - b"version" => { - write!( - self.writer, - "{}", - parser.meta.version.unwrap_or("unknown version") - )?; - } - b"author" => { - write!( - self.writer, - "{}", - parser.meta.author.unwrap_or("unknown author") - )?; - } - b"about" => { - write!( - self.writer, - "{}", - parser.meta.about.unwrap_or("unknown about") - )?; - } - b"long-about" => { - write!( - self.writer, - "{}", - parser.meta.long_about.unwrap_or("unknown about") - )?; - } - b"usage" => { - write!(self.writer, "{}", usage::create_usage_no_title(parser, &[]))?; - } - b"all-args" => { - self.write_all_args(parser)?; - } - b"unified" => { - let opts_flags = parser - .flags() - .map(as_arg_trait) - .chain(parser.opts().map(as_arg_trait)); - self.write_args(opts_flags)?; - } - b"flags" => { - self.write_args(parser.flags().map(as_arg_trait))?; - } - b"options" => { - self.write_args(parser.opts().map(as_arg_trait))?; - } - b"positionals" => { - self.write_args(parser.positionals().map(as_arg_trait))?; - } - b"subcommands" => { - self.write_subcommands(parser)?; - } - b"after-help" => { - write!( - self.writer, - "{}", - parser.meta.more_help.unwrap_or("unknown after-help") - )?; - } - b"before-help" => { - write!( - self.writer, - "{}", - parser.meta.pre_help.unwrap_or("unknown before-help") - )?; - } - // Unknown tag, write it back. - r => { - self.writer.write_all(b"{")?; - self.writer.write_all(r)?; - self.writer.write_all(b"}")?; - } - } - } - } -} - -fn wrap_help(help: &str, avail_chars: usize) -> String { - let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false); - help.lines() - .map(|line| wrapper.fill(line)) - .collect::>() - .join("\n") -} - -#[cfg(test)] -mod test { - use super::wrap_help; - - #[test] - fn wrap_help_last_word() { - let help = String::from("foo bar baz"); - assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz"); - } -} diff --git a/third_party/rust/clap/src/app/meta.rs b/third_party/rust/clap/src/app/meta.rs deleted file mode 100644 index 8916101015be..000000000000 --- a/third_party/rust/clap/src/app/meta.rs +++ /dev/null @@ -1,35 +0,0 @@ -#[doc(hidden)] -#[allow(missing_debug_implementations)] -#[derive(Default, Clone)] -pub struct AppMeta<'b> { - pub name: String, - pub bin_name: Option, - pub author: Option<&'b str>, - pub version: Option<&'b str>, - pub long_version: Option<&'b str>, - pub about: Option<&'b str>, - pub long_about: Option<&'b str>, - pub more_help: Option<&'b str>, - pub pre_help: Option<&'b str>, - pub aliases: Option>, // (name, visible) - pub usage_str: Option<&'b str>, - pub usage: Option, - pub help_str: Option<&'b str>, - pub disp_ord: usize, - pub term_w: Option, - pub max_w: Option, - pub template: Option<&'b str>, -} - -impl<'b> AppMeta<'b> { - pub fn new() -> Self { - Default::default() - } - pub fn with_name(s: String) -> Self { - AppMeta { - name: s, - disp_ord: 999, - ..Default::default() - } - } -} diff --git a/third_party/rust/clap/src/app/mod.rs b/third_party/rust/clap/src/app/mod.rs deleted file mode 100644 index c8ae912bc7ce..000000000000 --- a/third_party/rust/clap/src/app/mod.rs +++ /dev/null @@ -1,1909 +0,0 @@ -mod help; -mod meta; -pub mod parser; -mod settings; -mod usage; -mod validator; - -// Std -use std::result::Result as StdResult; -use std::{ - env, - ffi::{OsStr, OsString}, - fmt, - io::{self, BufRead, BufWriter, Write}, - path::Path, - process, - rc::Rc, -}; - -// Third Party -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -// Internal -use crate::errors::Result as ClapResult; -use crate::{ - app::{help::Help, parser::Parser}, - args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings}, - completions::Shell, - map::{self, VecMap}, -}; -pub use settings::AppSettings; - -/// Used to create a representation of a command line program and all possible command line -/// arguments. Application settings are set using the "builder pattern" with the -/// [`App::get_matches`] family of methods being the terminal methods that starts the -/// runtime-parsing process. These methods then return information about the user supplied -/// arguments (or lack there of). -/// -/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may -/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method -/// called). -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{App, Arg}; -/// let m = App::new("My Program") -/// .author("Me, me@mail.com") -/// .version("1.0.2") -/// .about("Explains in brief what the program does") -/// .arg( -/// Arg::with_name("in_file").index(1) -/// ) -/// .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`]: ./struct.App.html#method.get_matches -#[allow(missing_debug_implementations)] -pub struct App<'a, 'b> -where - 'a: 'b, -{ - #[doc(hidden)] - pub p: Parser<'a, 'b>, -} - -impl<'a, 'b> App<'a, 'b> { - /// Creates a new instance of an application requiring a name. The name may be, but doesn't - /// have to be same as the binary. The name will be displayed to the user when they request to - /// print version or help and usage information. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let prog = App::new("My Program") - /// # ; - /// ``` - pub fn new>(n: S) -> Self { - App { - p: Parser::with_name(n.into()), - } - } - - /// Get the name of the app - pub fn get_name(&self) -> &str { - &self.p.meta.name - } - - /// Get the name of the binary - pub fn get_bin_name(&self) -> Option<&str> { - self.p.meta.bin_name.as_deref() - } - - /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`] - /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let prog = App::with_defaults("My Program") - /// # ; - /// ``` - /// [`crate_authors!`]: ./macro.crate_authors!.html - /// [`crate_version!`]: ./macro.crate_version!.html - /// [`App::author`]: ./struct.App.html#method.author - /// [`App::version`]: ./struct.App.html#method.author - #[deprecated( - since = "2.14.1", - note = "Can never work; use explicit App::author() and App::version() calls instead" - )] - pub fn with_defaults>(n: S) -> Self { - let mut a = App { - p: Parser::with_name(n.into()), - }; - a.p.meta.author = Some("Kevin K. "); - a.p.meta.version = Some("2.19.2"); - a - } - - /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML - /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use - /// for using YAML is when supporting multiple languages and dialects, as each language could - /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your - /// `Cargo.toml` - /// - /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in - /// your settings for the `[dependencies.clap]` table of your `Cargo.toml` - /// - /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading - /// the YAML file at compile time (relative to the current file, like modules work). That YAML - /// object can then be passed to this function. - /// - /// # Panics - /// - /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to - /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes - /// without error, you needn't worry because the YAML is properly formatted. - /// - /// # Examples - /// - /// The following example shows how to load a properly formatted YAML file to build an instance - /// of an [`App`] struct. - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::App; - /// # fn main() { - /// let yml = load_yaml!("app.yml"); - /// let app = App::from_yaml(yml); - /// - /// // continued logic goes here, such as `app.get_matches()` etc. - /// # } - /// ``` - /// [`App`]: ./struct.App.html - /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.rs - /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.yml - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - #[cfg(feature = "yaml")] - pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> { - App::from(yaml) - } - - /// Sets a string of author(s) that will be displayed to the user when they - /// request the help information with `--help` or `-h`. - /// - /// **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. See the [`examples/`] - /// directory for more information - /// - /// See the [`examples/`] - /// directory for more information - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .author("Me, me@mymain.com") - /// # ; - /// ``` - /// [`crate_authors!`]: ./macro.crate_authors!.html - /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples - pub fn author>(mut self, author: S) -> Self { - self.p.meta.author = Some(author.into()); - self - } - - /// Overrides the system-determined binary name. 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 command **should not** be used for [`SubCommand`]s. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("My Program") - /// .bin_name("my_binary") - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - pub fn bin_name>(mut self, name: S) -> Self { - self.p.meta.bin_name = Some(name.into()); - self - } - - /// Sets a string describing what the program does. This will be displayed when displaying help - /// information with `-h`. - /// - /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests - /// `--help` clap will still display the contents of `about` appropriately - /// - /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be - /// concise - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .about("Does really amazing things to great people") - /// # ; - /// ``` - /// [`App::long_about`]: ./struct.App.html#method.long_about - pub fn about>(mut self, about: S) -> Self { - self.p.meta.about = Some(about.into()); - self - } - - /// Sets a string describing what the program does. This will be displayed when displaying help - /// information. - /// - /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests - /// `-h` clap will still display the contents of `long_about` appropriately - /// - /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be - /// concise - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::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`]: ./struct.App.html#method.about - pub fn long_about>(mut self, about: S) -> Self { - self.p.meta.long_about = Some(about.into()); - self - } - - /// Sets the program's name. This will be displayed when displaying help information. - /// - /// **Pro-top:** This function is particularly useful when configuring a program via - /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's - /// name from its `Cargo.toml`. - /// - /// # Examples - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::App; - /// # fn main() { - /// let yml = load_yaml!("app.yml"); - /// let app = App::from_yaml(yml) - /// .name(crate_name!()); - /// - /// // continued logic goes here, such as `app.get_matches()` etc. - /// # } - /// ``` - /// - /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml - /// [`crate_name!`]: ./macro.crate_name.html - pub fn name>(mut self, name: S) -> Self { - self.p.meta.name = name.into(); - self - } - - /// Adds additional help information to be displayed in addition to auto-generated help. This - /// information is displayed **after** the auto-generated help information. This is often used - /// to describe how to use the arguments, or caveats to be noted. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::App; - /// App::new("myprog") - /// .after_help("Does really amazing things to great people...but be careful with -R") - /// # ; - /// ``` - pub fn after_help>(mut self, help: S) -> Self { - self.p.meta.more_help = Some(help.into()); - self - } - - /// Adds additional help information to be displayed in addition to auto-generated help. This - /// information is displayed **before** the auto-generated help information. This is often used - /// for header information. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::App; - /// App::new("myprog") - /// .before_help("Some info I'd like to appear before the help info") - /// # ; - /// ``` - pub fn before_help>(mut self, help: S) -> Self { - self.p.meta.pre_help = Some(help.into()); - self - } - - /// Sets a string of the version number to be displayed when displaying version or help - /// information with `-V`. - /// - /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user - /// requests `--version` clap will still display the contents of `version` appropriately - /// - /// **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. See the [`examples/`] - /// directory for more information - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .version("v0.1.24") - /// # ; - /// ``` - /// [`crate_version!`]: ./macro.crate_version!.html - /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples - /// [`App::long_version`]: ./struct.App.html#method.long_version - pub fn version>(mut self, ver: S) -> Self { - self.p.meta.version = Some(ver.into()); - self - } - - /// Sets a string of the version number to be displayed when displaying version or help - /// information with `--version`. - /// - /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user - /// requests `-V` clap will still display the contents of `long_version` appropriately - /// - /// **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. See the [`examples/`] - /// directory for more information - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .long_version( - /// "v0.1.24 - /// commit: abcdef89726d - /// revision: 123 - /// release: 2 - /// binary: myprog") - /// # ; - /// ``` - /// [`crate_version!`]: ./macro.crate_version!.html - /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples - /// [`App::version`]: ./struct.App.html#method.version - pub fn long_version>(mut self, ver: S) -> Self { - self.p.meta.long_version = Some(ver.into()); - self - } - - /// Sets a custom usage string to override the auto-generated usage string. - /// - /// This will be displayed to the user when errors are found in argument parsing, or when you - /// call [`ArgMatches::usage`] - /// - /// **CAUTION:** 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:** You do not need to specify the "USAGE: \n\t" portion, as that will - /// still be applied by `clap`, you only need to specify the portion starting - /// with the binary name. - /// - /// **NOTE:** This will not replace the entire help message, *only* the portion - /// showing the usage. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .usage("myapp [-clDas] ") - /// # ; - /// ``` - /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage - pub fn usage>(mut self, usage: S) -> Self { - self.p.meta.usage_str = Some(usage.into()); - self - } - - /// Sets a custom help message and overrides the auto-generated one. This should only be used - /// when the auto-generated message does not suffice. - /// - /// This will be displayed to the user when they use `--help` or `-h` - /// - /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated. - /// - /// **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 [`Arg::help`] for them as well. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myapp") - /// .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\ - /// - /// Commmands:\n\ - /// help Prints this message\n\ - /// work Do some work") - /// # ; - /// ``` - /// [`Arg::help`]: ./struct.Arg.html#method.help - pub fn help>(mut self, help: S) -> Self { - self.p.meta.help_str = Some(help.into()); - self - } - - /// Sets the [`short`] for the auto-generated `help` argument. - /// - /// By default `clap` automatically assigns `h`, but this can be overridden if you have a - /// different argument which you'd prefer to use the `-h` short with. This can be done by - /// defining your own argument with a lowercase `h` as the [`short`]. - /// - /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of - /// your own. - /// - /// **NOTE:** Any leading `-` characters will be stripped, and only the first - /// non `-` character will be used as the [`short`] version - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h` - /// # ; - /// ``` - /// [`short`]: ./struct.Arg.html#method.short - pub fn help_short + 'b>(mut self, s: S) -> Self { - self.p.help_short(s.as_ref()); - self - } - - /// Sets the [`short`] for the auto-generated `version` argument. - /// - /// By default `clap` automatically assigns `V`, but this can be overridden if you have a - /// different argument which you'd prefer to use the `-V` short with. This can be done by - /// defining your own argument with an uppercase `V` as the [`short`]. - /// - /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of - /// your own. - /// - /// **NOTE:** Any leading `-` characters will be stripped, and only the first - /// non `-` character will be used as the `short` version - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .version_short("v") // Using a lowercase `v` instead of the default capital `V` - /// # ; - /// ``` - /// [`short`]: ./struct.Arg.html#method.short - pub fn version_short>(mut self, s: S) -> Self { - self.p.version_short(s.as_ref()); - self - } - - /// Sets the help text for the auto-generated `help` argument. - /// - /// By default `clap` sets this to `"Prints help information"`, but if you're using a - /// different convention for your help messages and would prefer a different phrasing you can - /// override it. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .help_message("Print help information") // Perhaps you want imperative help messages - /// - /// # ; - /// ``` - pub fn help_message>(mut self, s: S) -> Self { - self.p.help_message = Some(s.into()); - self - } - - /// Sets the help text for the auto-generated `version` argument. - /// - /// By default `clap` sets this to `"Prints version information"`, but if you're using a - /// different convention for your help messages and would prefer a different phrasing then you - /// can change it. - /// - /// # Examples - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .version_message("Print version information") // Perhaps you want imperative help messages - /// # ; - /// ``` - pub fn version_message>(mut self, s: S) -> Self { - self.p.version_message = Some(s.into()); - self - } - - /// Sets the help template to be used, overriding the default format. - /// - /// Tags arg given inside curly brackets. - /// - /// Valid tags are: - /// - /// * `{bin}` - Binary name. - /// * `{version}` - Version number. - /// * `{author}` - Author information. - /// * `{about}` - General description (from [`App::about`]) - /// * `{usage}` - Automatically generated or given usage string. - /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, - /// and subcommands) including titles. - /// * `{unified}` - Unified help for options and flags. Note, you must *also* set - /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and - /// flags, otherwise the ordering is "best effort" - /// * `{flags}` - Help for flags. - /// * `{options}` - Help for options. - /// * `{positionals}` - Help for positionals arguments. - /// * `{subcommands}` - Help for subcommands. - /// * `{after-help}` - Help from [`App::after_help`] - /// * `{before-help}` - Help from [`App::before_help`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .version("1.0") - /// .template("{bin} ({version}) - {usage}") - /// # ; - /// ``` - /// **NOTE:** The template system is, on purpose, very simple. Therefore the tags have to be - /// written in lowercase and without spacing. - /// - /// [`App::about`]: ./struct.App.html#method.about - /// [`App::after_help`]: ./struct.App.html#method.after_help - /// [`App::before_help`]: ./struct.App.html#method.before_help - /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage - pub fn template>(mut self, s: S) -> Self { - self.p.meta.template = Some(s.into()); - self - } - - /// Enables a single command, or [`SubCommand`], level settings. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::SubcommandRequired) - /// .setting(AppSettings::WaitOnError) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn setting(mut self, setting: AppSettings) -> Self { - self.p.set(setting); - self - } - - /// Enables multiple command, or [`SubCommand`], level settings - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .settings(&[AppSettings::SubcommandRequired, - /// AppSettings::WaitOnError]) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.p.set(*s); - } - self - } - - /// Enables a single setting that is propagated down through all child [`SubCommand`]s. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .global_setting(AppSettings::SubcommandRequired) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn global_setting(mut self, setting: AppSettings) -> Self { - self.p.set(setting); - self.p.g_settings.set(setting); - self - } - - /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .global_settings(&[AppSettings::SubcommandRequired, - /// AppSettings::ColoredHelp]) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.p.set(*s); - self.p.g_settings.set(*s) - } - self - } - - /// Disables a single command, or [`SubCommand`], level setting. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, AppSettings}; - /// App::new("myprog") - /// .unset_setting(AppSettings::ColorAuto) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn unset_setting(mut self, setting: AppSettings) -> Self { - self.p.unset(setting); - self - } - - /// Disables multiple command, or [`SubCommand`], level settings. - /// - /// See [`AppSettings`] for a full list of possibilities and examples. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, AppSettings}; - /// App::new("myprog") - /// .unset_settings(&[AppSettings::ColorAuto, - /// AppSettings::AllowInvalidUtf8]) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings`]: ./enum.AppSettings.html - pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { - for s in settings { - self.p.unset(*s); - } - self - } - - /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will - /// ignore terminal widths and use source formatting. - /// - /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows - /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width - /// cannot be determined, `clap` defaults to `120`. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This setting must be set **before** any subcommands are added! - /// - /// # Platform Specific - /// - /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. - /// Even on those platforms, this setting is useful if for any reason the terminal width - /// cannot be determined. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::App; - /// App::new("myprog") - /// .set_term_width(80) - /// # ; - /// ``` - pub fn set_term_width(mut self, width: usize) -> Self { - self.p.meta.term_w = Some(width); - self - } - - /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal - /// widths and use source formatting. - /// - /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows - /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to - /// limit the size (e.g. when the terminal is running fullscreen). - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This setting must be set **before** any subcommands are added! - /// - /// # Platform Specific - /// - /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::App; - /// App::new("myprog") - /// .max_term_width(100) - /// # ; - /// ``` - pub fn max_term_width(mut self, w: usize) -> Self { - self.p.meta.max_w = Some(w); - self - } - - /// Adds an [argument] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// // Adding a single "flag" argument with a short and help text, using Arg::with_name() - /// .arg( - /// Arg::with_name("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_usage() - /// .arg( - /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'") - /// ) - /// # ; - /// ``` - /// [argument]: ./struct.Arg.html - pub fn arg>>(mut self, a: A) -> Self { - self.p.add_arg(a.into()); - self - } - - /// Adds multiple [arguments] to the list of valid possibilities - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .args( - /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"), - /// Arg::with_name("input").index(1).help("the input file to use")] - /// ) - /// # ; - /// ``` - /// [arguments]: ./struct.Arg.html - pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self { - for arg in args { - self.p.add_arg_ref(arg); - } - self - } - - /// A convenience method for adding a single [argument] from a usage type string. The string - /// used follows the same rules and syntax as [`Arg::from_usage`] - /// - /// **NOTE:** The downside to using this method is that you can not set any additional - /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .arg_from_usage("-c --config= 'Sets a configuration file to use'") - /// # ; - /// ``` - /// [argument]: ./struct.Arg.html - /// [`Arg`]: ./struct.Arg.html - /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage - pub fn arg_from_usage(mut self, usage: &'a str) -> Self { - self.p.add_arg(Arg::from_usage(usage)); - self - } - - /// Adds multiple [arguments] at once from a usage string, one per line. See - /// [`Arg::from_usage`] for details on the syntax and rules supported. - /// - /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the - /// [`Arg`]s which [`Arg::from_usage`] supports. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// App::new("myprog") - /// .args_from_usage( - /// "-c --config=[FILE] 'Sets a configuration file to use' - /// [debug]... -d 'Sets the debugging level' - /// 'The input file to use'" - /// ) - /// # ; - /// ``` - /// [arguments]: ./struct.Arg.html - /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage - /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage - /// [`Arg`]: ./struct.Arg.html - pub fn args_from_usage(mut self, usage: &'a str) -> Self { - for line in usage.lines() { - let l = line.trim(); - if l.is_empty() { - continue; - } - self.p.add_arg(Arg::from_usage(l)); - } - self - } - - /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that - /// 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::{App, Arg, SubCommand}; - /// let m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test") - /// .alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - pub fn alias>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.p.meta.aliases { - als.push((name.into(), false)); - } else { - self.p.meta.aliases = Some(vec![(name.into(), false)]); - } - self - } - - /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that - /// 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::{App, Arg, SubCommand}; - /// let m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test") - /// .aliases(&["do-stuff", "do-tests", "tests"])) - /// .arg(Arg::with_name("input") - /// .help("the file to add") - /// .index(1) - /// .required(false)) - /// .get_matches_from(vec!["myprog", "do-tests"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - pub fn aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.p.meta.aliases { - for n in names { - als.push((n, false)); - } - } else { - self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::>()); - } - self - } - - /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with - /// [`App::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test") - /// .visible_alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`App::alias`]: ./struct.App.html#method.alias - pub fn visible_alias>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.p.meta.aliases { - als.push((name.into(), true)); - } else { - self.p.meta.aliases = Some(vec![(name.into(), true)]); - } - self - } - - /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined - /// with [`App::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test") - /// .visible_aliases(&["do-stuff", "tests"])) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`App::aliases`]: ./struct.App.html#method.aliases - pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.p.meta.aliases { - for n in names { - als.push((n, true)); - } - } else { - self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::>()); - } - 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. - /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only* - /// one) argument from that group must be present at runtime. - /// - /// You can also do things such as 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. - /// - /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead - /// of determining exactly which argument was used. - /// - /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common - /// use - /// - /// # 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::{App, ArgGroup}; - /// App::new("app") - /// .args_from_usage( - /// "--set-ver [ver] 'set the version manually' - /// --major 'auto increase major' - /// --minor 'auto increase minor' - /// --patch 'auto increase patch'") - /// .group(ArgGroup::with_name("vers") - /// .args(&["set-ver", "major", "minor","patch"]) - /// .required(true)) - /// # ; - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - pub fn group(mut self, group: ArgGroup<'a>) -> Self { - self.p.add_group(group); - self - } - - /// Adds multiple [`ArgGroup`]s to the [`App`] at once. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, ArgGroup}; - /// App::new("app") - /// .args_from_usage( - /// "--set-ver [ver] 'set the version manually' - /// --major 'auto increase major' - /// --minor 'auto increase minor' - /// --patch 'auto increase patch' - /// -c [FILE] 'a config file' - /// -i [IFACE] 'an interface'") - /// .groups(&[ - /// ArgGroup::with_name("vers") - /// .args(&["set-ver", "major", "minor","patch"]) - /// .required(true), - /// ArgGroup::with_name("input") - /// .args(&["c", "i"]) - /// ]) - /// # ; - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - /// [`App`]: ./struct.App.html - pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self { - for g in groups { - self = self.group(g.into()); - } - self - } - - /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively - /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage, - /// etc. They also function just like [`App`]s, in that they get their own auto generated help, - /// version, and usage. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// App::new("myprog") - /// .subcommand(SubCommand::with_name("config") - /// .about("Controls configuration features") - /// .arg_from_usage(" 'Required configuration file to use'")) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - pub fn subcommand(mut self, subcmd: App<'a, 'b>) -> Self { - self.p.add_subcommand(subcmd); - self - } - - /// Adds multiple subcommands to the list of valid possibilities by iterating over an - /// [`IntoIterator`] of [`SubCommand`]s - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// # App::new("myprog") - /// .subcommands( vec![ - /// SubCommand::with_name("config").about("Controls configuration functionality") - /// .arg(Arg::with_name("config_file").index(1)), - /// SubCommand::with_name("debug").about("Controls debug functionality")]) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html - pub fn subcommands(mut self, subcmds: I) -> Self - where - I: IntoIterator>, - { - for subcmd in subcmds { - self.p.add_subcommand(subcmd); - } - self - } - - /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower - /// value will be displayed first in the help message. This is helpful when one would like to - /// emphasise frequently used subcommands, or prioritize those towards the top of the list. - /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be - /// displayed in alphabetical order. - /// - /// **NOTE:** The default is 999 for all subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, SubCommand}; - /// let m = App::new("cust-ord") - /// .subcommand(SubCommand::with_name("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(SubCommand::with_name("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 [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// SUBCOMMANDS: - /// beta I should be first! - /// alpha Some help and text - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - pub fn display_order(mut self, ord: usize) -> Self { - self.p.meta.disp_ord = ord; - self - } - - /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same - /// method as if someone ran `-h` to request the help message - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages - /// depending on if the user ran [`-h` (short)] or [`--help` (long)] - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// let mut app = App::new("myprog"); - /// app.print_help(); - /// ``` - /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html - /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html - /// [`-h` (short)]: ./struct.Arg.html#method.help - /// [`--help` (long)]: ./struct.Arg.html#method.long_help - pub fn print_help(&mut self) -> ClapResult<()> { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - self.p.propagate_globals(); - self.p.propagate_settings(); - self.p.derive_display_order(); - - self.p.create_help_and_version(); - let out = io::stdout(); - let mut buf_w = BufWriter::new(out.lock()); - self.write_help(&mut buf_w) - } - - /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same - /// method as if someone ran `--help` to request the help message - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages - /// depending on if the user ran [`-h` (short)] or [`--help` (long)] - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// let mut app = App::new("myprog"); - /// app.print_long_help(); - /// ``` - /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html - /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html - /// [`-h` (short)]: ./struct.Arg.html#method.help - /// [`--help` (long)]: ./struct.Arg.html#method.long_help - pub fn print_long_help(&mut self) -> ClapResult<()> { - let out = io::stdout(); - let mut buf_w = BufWriter::new(out.lock()); - self.write_long_help(&mut buf_w) - } - - /// Writes the full help message to the user to a [`io::Write`] object in the same method as if - /// the user ran `-h` - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages - /// depending on if the user ran [`-h` (short)] or [`--help` (long)] - /// - /// **NOTE:** There is a known bug where this method does not write propagated global arguments - /// or autogenerated arguments (i.e. the default help/version args). Prefer - /// [`App::write_long_help`] instead if possible! - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// use std::io; - /// let mut app = App::new("myprog"); - /// let mut out = io::stdout(); - /// app.write_help(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html - /// [`-h` (short)]: ./struct.Arg.html#method.help - /// [`--help` (long)]: ./struct.Arg.html#method.long_help - pub fn write_help(&self, w: &mut W) -> ClapResult<()> { - // PENDING ISSUE: 808 - // https://github.com/clap-rs/clap/issues/808 - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - // self.p.propagate_globals(); - // self.p.propagate_settings(); - // self.p.derive_display_order(); - // self.p.create_help_and_version(); - - Help::write_app_help(w, self, false) - } - - /// Writes the full help message to the user to a [`io::Write`] object in the same method as if - /// the user ran `--help` - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages - /// depending on if the user ran [`-h` (short)] or [`--help` (long)] - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// use std::io; - /// let mut app = App::new("myprog"); - /// let mut out = io::stdout(); - /// app.write_long_help(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html - /// [`-h` (short)]: ./struct.Arg.html#method.help - /// [`--help` (long)]: ./struct.Arg.html#method.long_help - pub fn write_long_help(&mut self, w: &mut W) -> ClapResult<()> { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - self.p.propagate_globals(); - self.p.propagate_settings(); - self.p.derive_display_order(); - self.p.create_help_and_version(); - - Help::write_app_help(w, self, true) - } - - /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`. - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages - /// depending on if the user ran [`-V` (short)] or [`--version` (long)] - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// use std::io; - /// let mut app = App::new("myprog"); - /// let mut out = io::stdout(); - /// app.write_version(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html - /// [`-V` (short)]: ./struct.App.html#method.version - /// [`--version` (long)]: ./struct.App.html#method.long_version - pub fn write_version(&self, w: &mut W) -> ClapResult<()> { - self.p.write_version(w, false).map_err(From::from) - } - - /// Writes the version message to the user to a [`io::Write`] object - /// - /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages - /// depending on if the user ran [`-V` (short)] or [`--version` (long)] - /// - /// # Examples - /// - /// ```rust - /// # use clap::App; - /// use std::io; - /// let mut app = App::new("myprog"); - /// let mut out = io::stdout(); - /// app.write_long_version(&mut out).expect("failed to write to stdout"); - /// ``` - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html - /// [`-V` (short)]: ./struct.App.html#method.version - /// [`--version` (long)]: ./struct.App.html#method.long_version - pub fn write_long_version(&self, w: &mut W) -> ClapResult<()> { - self.p.write_version(w, true).map_err(From::from) - } - - /// Generate a completions file for a specified shell at compile time. - /// - /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script" - /// - /// # Examples - /// - /// The following example generates a bash completion script via a `build.rs` script. In this - /// simple example, we'll demo a very small application with only a single subcommand and two - /// args. Real applications could be many multiple levels deep in subcommands, and have tens or - /// potentially hundreds of arguments. - /// - /// First, it helps if we separate out our `App` definition into a separate file. Whether you - /// do this as a function, or bare App definition is a matter of personal preference. - /// - /// ``` - /// // src/cli.rs - /// - /// use clap::{App, Arg, SubCommand}; - /// - /// pub fn build_cli() -> App<'static, 'static> { - /// App::new("compl") - /// .about("Tests completions") - /// .arg(Arg::with_name("file") - /// .help("some input file")) - /// .subcommand(SubCommand::with_name("test") - /// .about("tests things") - /// .arg(Arg::with_name("case") - /// .long("case") - /// .takes_value(true) - /// .help("the case to test"))) - /// } - /// ``` - /// - /// In our regular code, we can simply call this `build_cli()` function, then call - /// `get_matches()`, or any of the other normal methods directly after. For example: - /// - /// ```ignore - /// // src/main.rs - /// - /// mod cli; - /// - /// fn main() { - /// let m = cli::build_cli().get_matches(); - /// - /// // normal logic continues... - /// } - /// ``` - /// - /// Next, we set up our `Cargo.toml` to use a `build.rs` build script. - /// - /// ```toml - /// # Cargo.toml - /// build = "build.rs" - /// - /// [build-dependencies] - /// clap = "2.23" - /// ``` - /// - /// Next, we place a `build.rs` in our project root. - /// - /// ```ignore - /// extern crate clap; - /// - /// use clap::Shell; - /// - /// include!("src/cli.rs"); - /// - /// fn main() { - /// let outdir = match env::var_os("OUT_DIR") { - /// None => return, - /// Some(outdir) => outdir, - /// }; - /// let mut app = build_cli(); - /// app.gen_completions("myapp", // We need to specify the bin name manually - /// Shell::Bash, // Then say which shell to build completions for - /// outdir); // Then say where write the completions to - /// } - /// ``` - /// Now, once we compile there will be a `{bin_name}.bash` file in the directory. - /// Assuming we compiled with debug mode, it would be somewhere similar to - /// `/target/debug/build/myapp-/out/myapp.bash`. - /// - /// Fish shell completions will use the file format `{bin_name}.fish` - pub fn gen_completions, S: Into>( - &mut self, - bin_name: S, - for_shell: Shell, - out_dir: T, - ) { - self.p.meta.bin_name = Some(bin_name.into()); - self.p.gen_completions(for_shell, out_dir.into()); - } - - /// Generate a completions file for a specified shell at runtime. Until `cargo install` can - /// install extra files like a completion script, this may be used e.g. in a command that - /// outputs the contents of the completion script, to be redirected into a file by the user. - /// - /// # Examples - /// - /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions), - /// we can let users generate a completion script using a command: - /// - /// ```ignore - /// // src/main.rs - /// - /// mod cli; - /// use std::io; - /// - /// fn main() { - /// let matches = cli::build_cli().get_matches(); - /// - /// if matches.is_present("generate-bash-completions") { - /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout()); - /// } - /// - /// // normal logic continues... - /// } - /// - /// ``` - /// - /// Usage: - /// - /// ```shell - /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash - /// ``` - pub fn gen_completions_to>( - &mut self, - bin_name: S, - for_shell: Shell, - buf: &mut W, - ) { - self.p.meta.bin_name = Some(bin_name.into()); - self.p.gen_completions_to(for_shell, buf); - } - - /// Starts the parsing process, upon a failed parse an error will be displayed to the user and - /// the process will exit with the appropriate error code. By default this method gets all user - /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points, - /// which are legal on many platforms. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let matches = App::new("myprog") - /// // Args and options go here... - /// .get_matches(); - /// ``` - /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html - pub fn get_matches(self) -> ArgMatches<'a> { - self.get_matches_from(&mut env::args_os()) - } - - /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting - /// the process on failed parse. By default this method gets matches from [`env::args_os`] - /// - /// **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::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call - /// [`Error::exit`] or perform a [`std::process::exit`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let matches = App::new("myprog") - /// // Args and options go here... - /// .get_matches_safe() - /// .unwrap_or_else( |e| e.exit() ); - /// ``` - /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html - /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed - /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed - /// [`Error::exit`]: ./struct.Error.html#method.exit - /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html - /// [`clap::Result`]: ./type.Result.html - /// [`clap::Error`]: ./struct.Error.html - /// [`kind`]: ./struct.Error.html - pub fn get_matches_safe(self) -> ClapResult> { - // Start the parsing - self.get_matches_from_safe(&mut env::args_os()) - } - - /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`] - /// and will automatically exit with an error message. This method, however, lets you specify - /// what iterator to use when performing matches, such as a [`Vec`] of your making. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`AppSettings::NoBinaryName`] is used - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = App::new("myprog") - /// // Args and options go here... - /// .get_matches_from(arg_vec); - /// ``` - /// [`App::get_matches`]: ./struct.App.html#method.get_matches - /// [`clap::Result`]: ./type.Result.html - /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html - /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName - pub fn get_matches_from(mut self, itr: I) -> ArgMatches<'a> - where - I: IntoIterator, - T: Into + Clone, - { - self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| { - // Otherwise, write to stderr and exit - if e.use_stderr() { - wlnerr!("{}", e.message); - if self.p.is_set(AppSettings::WaitOnError) { - wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); - let mut s = String::new(); - let i = io::stdin(); - i.lock().read_line(&mut s).unwrap(); - } - drop(self); - drop(e); - process::exit(1); - } - - drop(self); - e.exit() - }) - } - - /// Starts the parsing process. A combination of [`App::get_matches_from`], and - /// [`App::get_matches_safe`] - /// - /// **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::HelpDisplayed`] - /// or [`ErrorKind::VersionDisplayed`] 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 - /// [`AppSettings::NoBinaryName`] is used - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = App::new("myprog") - /// // Args and options go here... - /// .get_matches_from_safe(arg_vec) - /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); - /// ``` - /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from - /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe - /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed - /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed - /// [`Error::exit`]: ./struct.Error.html#method.exit - /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html - /// [`clap::Error`]: ./struct.Error.html - /// [`Error::exit`]: ./struct.Error.html#method.exit - /// [`kind`]: ./struct.Error.html - /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName - pub fn get_matches_from_safe(mut self, itr: I) -> ClapResult> - where - I: IntoIterator, - T: Into + Clone, - { - self.get_matches_from_safe_borrow(itr) - } - - /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not - /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does* - /// consume `self`. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`AppSettings::NoBinaryName`] is used - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let mut app = App::new("myprog"); - /// // Args and options go here... - /// let matches = app.get_matches_from_safe_borrow(arg_vec) - /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); - /// ``` - /// [`App`]: ./struct.App.html - /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe - /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName - pub fn get_matches_from_safe_borrow(&mut self, itr: I) -> ClapResult> - where - I: IntoIterator, - T: Into + Clone, - { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - if !self.p.is_set(AppSettings::Propagated) { - self.p.propagate_globals(); - self.p.propagate_settings(); - self.p.derive_display_order(); - self.p.set(AppSettings::Propagated); - } - - let mut matcher = ArgMatcher::new(); - - let mut it = itr.into_iter(); - // 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.p.is_set(AppSettings::NoBinaryName) { - if let Some(name) = it.next() { - let bn_os = name.into(); - let p = Path::new(&*bn_os); - if let Some(f) = p.file_name() { - if let Some(s) = f.to_os_string().to_str() { - if self.p.meta.bin_name.is_none() { - self.p.meta.bin_name = Some(s.to_owned()); - } - } - } - } - } - - // do the real parsing - if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) { - return Err(e); - } - - let global_arg_vec: Vec<&str> = self.p.global_args.iter().map(|ga| ga.b.name).collect(); - matcher.propagate_globals(&global_arg_vec); - - Ok(matcher.into()) - } -} - -#[cfg(feature = "yaml")] -impl<'a> From<&'a Yaml> for App<'a, 'a> { - fn from(mut yaml: &'a Yaml) -> Self { - use crate::args::SubCommand; - // We WANT this to panic on error...so expect() is good. - let mut is_sc = None; - let mut a = if let Some(name) = yaml["name"].as_str() { - App::new(name) - } else { - let yaml_hash = yaml.as_hash().unwrap(); - let sc_key = yaml_hash.keys().nth(0).unwrap(); - is_sc = Some(yaml_hash.get(sc_key).unwrap()); - App::new(sc_key.as_str().unwrap()) - }; - yaml = if let Some(sc) = is_sc { sc } else { yaml }; - - macro_rules! yaml_str { - ($a:ident, $y:ident, $i:ident) => { - if let Some(v) = $y[stringify!($i)].as_str() { - $a = $a.$i(v); - } else if $y[stringify!($i)] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to a string", - $y[stringify!($i)] - ); - } - }; - } - - yaml_str!(a, yaml, version); - yaml_str!(a, yaml, long_version); - yaml_str!(a, yaml, author); - yaml_str!(a, yaml, bin_name); - yaml_str!(a, yaml, about); - yaml_str!(a, yaml, long_about); - yaml_str!(a, yaml, before_help); - yaml_str!(a, yaml, after_help); - yaml_str!(a, yaml, template); - yaml_str!(a, yaml, usage); - yaml_str!(a, yaml, help); - yaml_str!(a, yaml, help_short); - yaml_str!(a, yaml, version_short); - yaml_str!(a, yaml, help_message); - yaml_str!(a, yaml, version_message); - yaml_str!(a, yaml, alias); - yaml_str!(a, yaml, visible_alias); - - if let Some(v) = yaml["display_order"].as_i64() { - a = a.display_order(v as usize); - } else if yaml["display_order"] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to a u64", - yaml["display_order"] - ); - } - if let Some(v) = yaml["setting"].as_str() { - a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); - } else if yaml["setting"] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to an AppSetting", - yaml["setting"] - ); - } - if let Some(v) = yaml["settings"].as_vec() { - for ys in v { - if let Some(s) = ys.as_str() { - a = a.setting(s.parse().expect("unknown AppSetting found in YAML file")); - } - } - } else if let Some(v) = yaml["settings"].as_str() { - a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); - } else if yaml["settings"] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to a string", - yaml["settings"] - ); - } - if let Some(v) = yaml["global_setting"].as_str() { - a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); - } else if yaml["global_setting"] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to an AppSetting", - yaml["setting"] - ); - } - if let Some(v) = yaml["global_settings"].as_vec() { - for ys in v { - if let Some(s) = ys.as_str() { - a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file")); - } - } - } else if let Some(v) = yaml["global_settings"].as_str() { - a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file")); - } else if yaml["global_settings"] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to a string", - yaml["global_settings"] - ); - } - - macro_rules! vec_or_str { - ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{ - let maybe_vec = $y[stringify!($as_vec)].as_vec(); - if let Some(vec) = maybe_vec { - for ys in vec { - if let Some(s) = ys.as_str() { - $a = $a.$as_single(s); - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - } - } else { - if let Some(s) = $y[stringify!($as_vec)].as_str() { - $a = $a.$as_single(s); - } else if $y[stringify!($as_vec)] != Yaml::BadValue { - panic!( - "Failed to convert YAML value {:?} to either a vec or string", - $y[stringify!($as_vec)] - ); - } - } - $a - }}; - } - - a = vec_or_str!(a, yaml, aliases, alias); - a = vec_or_str!(a, yaml, visible_aliases, visible_alias); - - if let Some(v) = yaml["args"].as_vec() { - for arg_yaml in v { - a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap())); - } - } - if let Some(v) = yaml["subcommands"].as_vec() { - for sc_yaml in v { - a = a.subcommand(SubCommand::from_yaml(sc_yaml)); - } - } - if let Some(v) = yaml["groups"].as_vec() { - for ag_yaml in v { - a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap())); - } - } - - a - } -} - -impl<'a, 'b> Clone for App<'a, 'b> { - fn clone(&self) -> Self { - App { p: self.p.clone() } - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> { - fn name(&self) -> &'n str { - "" - } - fn overrides(&self) -> Option<&[&'e str]> { - None - } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - None - } - fn blacklist(&self) -> Option<&[&'e str]> { - None - } - fn required_unless(&self) -> Option<&[&'e str]> { - None - } - fn val_names(&self) -> Option<&VecMap<&'e str>> { - None - } - fn is_set(&self, _: ArgSettings) -> bool { - false - } - fn val_terminator(&self) -> Option<&'e str> { - None - } - fn set(&mut self, _: ArgSettings) { - unreachable!("App struct does not support AnyArg::set, this is a bug!") - } - fn has_switch(&self) -> bool { - false - } - fn max_vals(&self) -> Option { - None - } - fn num_vals(&self) -> Option { - None - } - fn possible_vals(&self) -> Option<&[&'e str]> { - None - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { - None - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { - None - } - fn min_vals(&self) -> Option { - None - } - fn short(&self) -> Option { - None - } - fn long(&self) -> Option<&'e str> { - None - } - fn val_delim(&self) -> Option { - None - } - fn takes_value(&self) -> bool { - true - } - fn help(&self) -> Option<&'e str> { - self.p.meta.about - } - fn long_help(&self) -> Option<&'e str> { - self.p.meta.long_about - } - fn default_val(&self) -> Option<&'e OsStr> { - None - } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { - None - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - None - } - fn longest_filter(&self) -> bool { - true - } - fn aliases(&self) -> Option> { - if let Some(ref aliases) = self.p.meta.aliases { - let vis_aliases: Vec<_> = aliases - .iter() - .filter_map(|&(n, v)| if v { Some(n) } else { None }) - .collect(); - if vis_aliases.is_empty() { - None - } else { - Some(vis_aliases) - } - } else { - None - } - } -} - -impl<'n, 'e> fmt::Display for App<'n, 'e> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.p.meta.name) - } -} diff --git a/third_party/rust/clap/src/app/parser.rs b/third_party/rust/clap/src/app/parser.rs deleted file mode 100644 index 12cb2c131170..000000000000 --- a/third_party/rust/clap/src/app/parser.rs +++ /dev/null @@ -1,2236 +0,0 @@ -// Std -#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] -use std::os::unix::ffi::OsStrExt; -use std::{ - cell::Cell, - ffi::{OsStr, OsString}, - fmt::Display, - fs::File, - io::{self, BufWriter, Write}, - iter::Peekable, - path::PathBuf, - slice::Iter, -}; - -// Internal -#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))] -use crate::osstringext::OsStrExt3; -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use crate::osstringext::OsStrExt3; -use crate::{ - app::{ - help::Help, meta::AppMeta, settings::AppFlags, settings::AppSettings as AS, usage, - validator::Validator, App, - }, - args::{ - settings::ArgSettings, AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, - PosBuilder, Switched, - }, - completions::{ComplGen, Shell}, - errors::Result as ClapResult, - errors::{Error, ErrorKind}, - fmt::ColorWhen, - map::{self, VecMap}, - osstringext::OsStrExt2, - suggestions, SubCommand, INTERNAL_ERROR_MSG, INVALID_UTF8, -}; - -#[derive(Debug, PartialEq, Copy, Clone)] -#[doc(hidden)] -pub enum ParseResult<'a> { - Flag, - Opt(&'a str), - Pos(&'a str), - MaybeHyphenValue, - MaybeNegNum, - NotFound, - ValuesDone, -} - -#[allow(missing_debug_implementations)] -#[doc(hidden)] -#[derive(Clone, Default)] -pub struct Parser<'a, 'b> -where - 'a: 'b, -{ - pub meta: AppMeta<'b>, - settings: AppFlags, - pub g_settings: AppFlags, - pub flags: Vec>, - pub opts: Vec>, - pub positionals: VecMap>, - pub subcommands: Vec>, - pub groups: Vec>, - pub global_args: Vec>, - pub required: Vec<&'a str>, - pub r_ifs: Vec<(&'a str, &'b str, &'a str)>, - pub overrides: Vec<(&'b str, &'a str)>, - help_short: Option, - version_short: Option, - cache: Option<&'a str>, - pub help_message: Option<&'a str>, - pub version_message: Option<&'a str>, - cur_idx: Cell, -} - -impl<'a, 'b> Parser<'a, 'b> -where - 'a: 'b, -{ - pub fn with_name(n: String) -> Self { - Parser { - meta: AppMeta::with_name(n), - g_settings: AppFlags::zeroed(), - cur_idx: Cell::new(0), - ..Default::default() - } - } - - pub fn help_short(&mut self, s: &str) { - let c = s - .trim_left_matches(|c| c == '-') - .chars() - .next() - .unwrap_or('h'); - self.help_short = Some(c); - } - - pub fn version_short(&mut self, s: &str) { - let c = s - .trim_left_matches(|c| c == '-') - .chars() - .next() - .unwrap_or('V'); - self.version_short = Some(c); - } - - pub fn gen_completions_to(&mut self, for_shell: Shell, buf: &mut W) { - if !self.is_set(AS::Propagated) { - self.propagate_help_version(); - self.build_bin_names(); - self.propagate_globals(); - self.propagate_settings(); - self.set(AS::Propagated); - } - - ComplGen::new(self).generate(for_shell, buf) - } - - pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) { - use std::error::Error; - - let out_dir = PathBuf::from(od); - let name = &*self.meta.bin_name.as_ref().unwrap().clone(); - let file_name = match for_shell { - Shell::Bash => format!("{}.bash", name), - Shell::Fish => format!("{}.fish", name), - Shell::Zsh => format!("_{}", name), - Shell::PowerShell => format!("_{}.ps1", name), - Shell::Elvish => format!("{}.elv", name), - }; - - let mut file = match File::create(out_dir.join(file_name)) { - Err(why) => panic!("couldn't create completion file: {}", why.description()), - Ok(file) => file, - }; - self.gen_completions_to(for_shell, &mut file) - } - - #[inline] - fn app_debug_asserts(&self) -> bool { - assert!(self.verify_positionals()); - let should_err = self.groups.iter().all(|g| { - g.args.iter().all(|arg| { - self.flags.iter().any(|f| &f.b.name == arg) - || self.opts.iter().any(|o| &o.b.name == arg) - || self.positionals.values().any(|p| &p.b.name == arg) - || self.groups.iter().any(|g| &g.name == arg) - }) - }); - let g = self.groups.iter().find(|g| { - g.args.iter().any(|arg| { - !(self.flags.iter().any(|f| &f.b.name == arg) - || self.opts.iter().any(|o| &o.b.name == arg) - || self.positionals.values().any(|p| &p.b.name == arg) - || self.groups.iter().any(|g| &g.name == arg)) - }) - }); - assert!( - should_err, - "The group '{}' contains the arg '{}' that doesn't actually exist.", - g.unwrap().name, - g.unwrap() - .args - .iter() - .find(|arg| !(self.flags.iter().any(|f| &&f.b.name == arg) - || self.opts.iter().any(|o| &&o.b.name == arg) - || self.positionals.values().any(|p| &&p.b.name == arg) - || self.groups.iter().any(|g| &&g.name == arg))) - .unwrap() - ); - true - } - - #[inline] - fn debug_asserts(&self, a: &Arg) -> bool { - assert!( - !arg_names!(self).any(|name| name == a.b.name), - "Non-unique argument name: {} is already in use", - a.b.name - ); - if let Some(l) = a.s.long { - assert!( - !self.contains_long(l), - "Argument long must be unique\n\n\t--{} is already in use", - l - ); - } - if let Some(s) = a.s.short { - assert!( - !self.contains_short(s), - "Argument short must be unique\n\n\t-{} is already in use", - s - ); - } - let i = if a.index.is_none() { - self.positionals.len() + 1 - } else { - a.index.unwrap() as usize - }; - assert!( - !self.positionals.contains_key(i), - "Argument \"{}\" has the same index as another positional \ - argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \ - to take multiple values", - a.b.name - ); - assert!( - !(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)), - "Global arguments cannot be required.\n\n\t'{}' is marked as \ - global and required", - a.b.name - ); - if a.b.is_set(ArgSettings::Last) { - assert!( - !self - .positionals - .values() - .any(|p| p.b.is_set(ArgSettings::Last)), - "Only one positional argument may have last(true) set. Found two." - ); - assert!(a.s.long.is_none(), - "Flags or Options may not have last(true) set. {} has both a long and last(true) set.", - a.b.name); - assert!(a.s.short.is_none(), - "Flags or Options may not have last(true) set. {} has both a short and last(true) set.", - a.b.name); - } - true - } - - #[inline] - fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) { - if let Some(ref r_ifs) = a.r_ifs { - for &(arg, val) in r_ifs { - self.r_ifs.push((arg, val, a.b.name)); - } - } - } - - #[inline] - fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) { - if let Some(ref grps) = a.b.groups { - for g in grps { - let mut found = false; - if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) { - ag.args.push(a.b.name); - found = true; - } - if !found { - let mut ag = ArgGroup::with_name(g); - ag.args.push(a.b.name); - self.groups.push(ag); - } - } - } - } - - #[inline] - fn add_reqs(&mut self, a: &Arg<'a, 'b>) { - if a.is_set(ArgSettings::Required) { - // If the arg is required, add all it's requirements to master required list - self.required.push(a.b.name); - if let Some(ref areqs) = a.b.requires { - for name in areqs - .iter() - .filter(|&&(val, _)| val.is_none()) - .map(|&(_, name)| name) - { - self.required.push(name); - } - } - } - } - - #[inline] - fn implied_settings(&mut self, a: &Arg<'a, 'b>) { - if a.is_set(ArgSettings::Last) { - // 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.set(AS::DontCollapseArgsInUsage); - self.set(AS::ContainsLast); - } - if let Some(l) = a.s.long { - if l == "version" { - self.unset(AS::NeedsLongVersion); - } else if l == "help" { - self.unset(AS::NeedsLongHelp); - } - } - } - - // actually adds the arguments - pub fn add_arg(&mut self, a: Arg<'a, 'b>) { - // if it's global we have to clone anyways - if a.is_set(ArgSettings::Global) { - return self.add_arg_ref(&a); - } - debug_assert!(self.debug_asserts(&a)); - self.add_conditional_reqs(&a); - self.add_arg_groups(&a); - self.add_reqs(&a); - self.implied_settings(&a); - if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { - let i = if a.index.is_none() { - self.positionals.len() + 1 - } else { - a.index.unwrap() as usize - }; - self.positionals - .insert(i, PosBuilder::from_arg(a, i as u64)); - } else if a.is_set(ArgSettings::TakesValue) { - let mut ob = OptBuilder::from(a); - ob.s.unified_ord = self.flags.len() + self.opts.len(); - self.opts.push(ob); - } else { - let mut fb = FlagBuilder::from(a); - fb.s.unified_ord = self.flags.len() + self.opts.len(); - self.flags.push(fb); - } - } - // actually adds the arguments but from a borrow (which means we have to do some cloning) - pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) { - debug_assert!(self.debug_asserts(a)); - self.add_conditional_reqs(a); - self.add_arg_groups(a); - self.add_reqs(a); - self.implied_settings(a); - if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { - let i = if a.index.is_none() { - self.positionals.len() + 1 - } else { - a.index.unwrap() as usize - }; - let pb = PosBuilder::from_arg_ref(a, i as u64); - self.positionals.insert(i, pb); - } else if a.is_set(ArgSettings::TakesValue) { - let mut ob = OptBuilder::from(a); - ob.s.unified_ord = self.flags.len() + self.opts.len(); - self.opts.push(ob); - } else { - let mut fb = FlagBuilder::from(a); - fb.s.unified_ord = self.flags.len() + self.opts.len(); - self.flags.push(fb); - } - if a.is_set(ArgSettings::Global) { - self.global_args.push(a.into()); - } - } - - pub fn add_group(&mut self, group: ArgGroup<'a>) { - if group.required { - self.required.push(group.name); - if let Some(ref reqs) = group.requires { - self.required.extend_from_slice(reqs); - } - // if let Some(ref bl) = group.conflicts { - // self.blacklist.extend_from_slice(bl); - // } - } - if self.groups.iter().any(|g| g.name == group.name) { - let grp = self - .groups - .iter_mut() - .find(|g| g.name == group.name) - .expect(INTERNAL_ERROR_MSG); - grp.args.extend_from_slice(&group.args); - grp.requires = group.requires.clone(); - grp.conflicts = group.conflicts.clone(); - grp.required = group.required; - } else { - self.groups.push(group); - } - } - - pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) { - debugln!( - "Parser::add_subcommand: term_w={:?}, name={}", - self.meta.term_w, - subcmd.p.meta.name - ); - subcmd.p.meta.term_w = self.meta.term_w; - if subcmd.p.meta.name == "help" { - self.unset(AS::NeedsSubcommandHelp); - } - - self.subcommands.push(subcmd); - } - - pub fn propagate_settings(&mut self) { - debugln!( - "Parser::propagate_settings: self={}, g_settings={:#?}", - self.meta.name, - self.g_settings - ); - for sc in &mut self.subcommands { - debugln!( - "Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}", - sc.p.meta.name, - sc.p.settings, - sc.p.g_settings - ); - // We have to create a new scope in order to tell rustc the borrow of `sc` is - // done and to recursively call this method - { - let vsc = self.settings.is_set(AS::VersionlessSubcommands); - let gv = self.settings.is_set(AS::GlobalVersion); - - if vsc { - sc.p.set(AS::DisableVersion); - } - if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() { - sc.p.set(AS::GlobalVersion); - sc.p.meta.version = Some(self.meta.version.unwrap()); - } - sc.p.settings = sc.p.settings | self.g_settings; - sc.p.g_settings = sc.p.g_settings | self.g_settings; - sc.p.meta.term_w = self.meta.term_w; - sc.p.meta.max_w = self.meta.max_w; - } - sc.p.propagate_settings(); - } - } - - pub fn derive_display_order(&mut self) { - if self.is_set(AS::DeriveDisplayOrder) { - let unified = self.is_set(AS::UnifiedHelpMessage); - for (i, o) in self - .opts - .iter_mut() - .enumerate() - .filter(|&(_, ref o)| o.s.disp_ord == 999) - { - o.s.disp_ord = if unified { o.s.unified_ord } else { i }; - } - for (i, f) in self - .flags - .iter_mut() - .enumerate() - .filter(|&(_, ref f)| f.s.disp_ord == 999) - { - f.s.disp_ord = if unified { f.s.unified_ord } else { i }; - } - for (i, sc) in &mut self - .subcommands - .iter_mut() - .enumerate() - .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999) - { - sc.p.meta.disp_ord = i; - } - } - for sc in &mut self.subcommands { - sc.p.derive_display_order(); - } - } - - pub fn required(&self) -> Iter<&str> { - self.required.iter() - } - - #[inline] - pub fn has_args(&self) -> bool { - !(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty()) - } - - #[inline] - pub fn has_opts(&self) -> bool { - !self.opts.is_empty() - } - - #[inline] - pub fn has_flags(&self) -> bool { - !self.flags.is_empty() - } - - #[inline] - pub fn has_positionals(&self) -> bool { - !self.positionals.is_empty() - } - - #[inline] - pub fn has_subcommands(&self) -> bool { - !self.subcommands.is_empty() - } - - #[inline] - pub fn has_visible_opts(&self) -> bool { - if self.opts.is_empty() { - return false; - } - self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden)) - } - - #[inline] - pub fn has_visible_flags(&self) -> bool { - if self.flags.is_empty() { - return false; - } - self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden)) - } - - #[inline] - pub fn has_visible_positionals(&self) -> bool { - if self.positionals.is_empty() { - return false; - } - self.positionals - .values() - .any(|p| !p.is_set(ArgSettings::Hidden)) - } - - #[inline] - pub fn has_visible_subcommands(&self) -> bool { - self.has_subcommands() - && self - .subcommands - .iter() - .filter(|sc| sc.p.meta.name != "help") - .any(|sc| !sc.p.is_set(AS::Hidden)) - } - - #[inline] - pub fn is_set(&self, s: AS) -> bool { - self.settings.is_set(s) - } - - #[inline] - pub fn set(&mut self, s: AS) { - self.settings.set(s) - } - - #[inline] - pub fn unset(&mut self, s: AS) { - self.settings.unset(s) - } - - pub fn verify_positionals(&self) -> bool { - // 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) - if let Some((idx, p)) = self.positionals.iter().rev().next() { - assert!( - !(idx != self.positionals.len()), - "Found positional argument \"{}\" whose index is {} but there \ - are only {} positional arguments defined", - p.b.name, - idx, - self.positionals.len() - ); - } - - // Next we verify that only the highest index has a .multiple(true) (if any) - if self.positionals.values().any(|a| { - a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) - }) { - let mut it = self.positionals.values().rev(); - let last = it.next().unwrap(); - let second_to_last = it.next().unwrap(); - // Either the final positional is required - // Or the second to last has a terminator or .last(true) set - let ok = last.is_set(ArgSettings::Required) - || (second_to_last.v.terminator.is_some() - || second_to_last.b.is_set(ArgSettings::Last)) - || last.is_set(ArgSettings::Last); - assert!( - ok, - "When using a positional argument with .multiple(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." - ); - let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last); - assert!( - ok, - "Only the last positional argument, or second to last positional \ - argument may be set to .multiple(true)" - ); - - let count = self - .positionals - .values() - .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none()) - .count(); - let ok = count <= 1 - || (last.is_set(ArgSettings::Last) - && last.is_set(ArgSettings::Multiple) - && second_to_last.is_set(ArgSettings::Multiple) - && count == 2); - assert!( - ok, - "Only one positional argument with .multiple(true) set is allowed per \ - command, unless the second one also has .last(true) set" - ); - } - - let mut found = false; - if self.is_set(AS::AllowMissingPositional) { - // 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 self.positionals.values().rev() { - if foundx2 && !p.b.settings.is_set(ArgSettings::Required) { - assert!( - p.b.is_set(ArgSettings::Required), - "Found positional argument which is not required with a lower \ - index than a required positional argument by two or more: {:?} \ - index {}", - p.b.name, - p.index - ); - } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { - // 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 self.positionals.values().rev() { - if found { - assert!( - p.b.is_set(ArgSettings::Required), - "Found positional argument which is not required with a lower \ - index than a required positional argument: {:?} index {}", - p.b.name, - p.index - ); - } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { - // 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; - } - } - } - if self - .positionals - .values() - .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required)) - && self.has_subcommands() - && !self.is_set(AS::SubcommandsNegateReqs) - { - panic!( - "Having a required positional argument with .last(true) set *and* child \ - subcommands without setting SubcommandsNegateReqs isn't compatible." - ); - } - - true - } - - pub fn propagate_globals(&mut self) { - for sc in &mut self.subcommands { - // We have to create a new scope in order to tell rustc the borrow of `sc` is - // done and to recursively call this method - { - for a in &self.global_args { - sc.p.add_arg_ref(a); - } - } - sc.p.propagate_globals(); - } - } - - // Checks if the arg matches a subcommand name, or any of it's aliases (if defined) - fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) { - debugln!("Parser::possible_subcommand: arg={:?}", arg_os); - fn starts(h: &str, n: &OsStr) -> bool { - let n_bytes = n.as_bytes(); - let h_bytes = OsStr::new(h).as_bytes(); - - h_bytes.starts_with(n_bytes) - } - - if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) { - return (false, None); - } - if !self.is_set(AS::InferSubcommands) { - if let Some(sc) = find_subcmd!(self, arg_os) { - return (true, Some(&sc.p.meta.name)); - } - } else { - let v = self - .subcommands - .iter() - .filter(|s| { - starts(&s.p.meta.name[..], &*arg_os) - || (s.p.meta.aliases.is_some() - && s.p - .meta - .aliases - .as_ref() - .unwrap() - .iter() - .filter(|&&(a, _)| starts(a, &*arg_os)) - .count() - == 1) - }) - .map(|sc| &sc.p.meta.name) - .collect::>(); - - for sc in &v { - if OsStr::new(sc) == arg_os { - return (true, Some(sc)); - } - } - - if v.len() == 1 { - return (true, Some(v[0])); - } - } - (false, None) - } - - fn parse_help_subcommand(&self, it: &mut I) -> ClapResult> - where - I: Iterator, - T: Into, - { - debugln!("Parser::parse_help_subcommand;"); - let cmds: Vec = it.map(|c| c.into()).collect(); - let mut help_help = false; - let mut bin_name = self - .meta - .bin_name - .as_ref() - .unwrap_or(&self.meta.name) - .clone(); - let mut sc = { - let mut sc: &Parser = self; - for (i, cmd) in cmds.iter().enumerate() { - if &*cmd.to_string_lossy() == "help" { - // cmd help help - help_help = true; - } - if let Some(c) = sc - .subcommands - .iter() - .find(|s| &*s.p.meta.name == cmd) - .map(|sc| &sc.p) - { - sc = c; - if i == cmds.len() - 1 { - break; - } - } else if let Some(c) = sc - .subcommands - .iter() - .find(|s| { - if let Some(ref als) = s.p.meta.aliases { - als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy()) - } else { - false - } - }) - .map(|sc| &sc.p) - { - sc = c; - if i == cmds.len() - 1 { - break; - } - } else { - return Err(Error::unrecognized_subcommand( - cmd.to_string_lossy().into_owned(), - self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), - self.color(), - )); - } - bin_name = format!("{} {}", bin_name, &*sc.meta.name); - } - sc.clone() - }; - if help_help { - let mut pb = PosBuilder::new("subcommand", 1); - pb.b.help = Some("The subcommand whose help message to display"); - pb.set(ArgSettings::Multiple); - sc.positionals.insert(1, pb); - sc.settings = sc.settings | self.g_settings; - } else { - sc.create_help_and_version(); - } - if sc.meta.bin_name != self.meta.bin_name { - sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name)); - } - Err(sc._help(false)) - } - - // allow wrong self convention due to self.valid_neg_num = true and it's a private method - #[cfg_attr(feature = "lints", allow(wrong_self_convention))] - fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult) -> bool { - debugln!("Parser::is_new_arg:{:?}:{:?}", arg_os, needs_val_of); - let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) { - true - } else if self.is_set(AS::AllowNegativeNumbers) { - let a = arg_os.to_string_lossy(); - if a.parse::().is_ok() || a.parse::().is_ok() { - self.set(AS::ValidNegNumFound); - true - } else { - false - } - } else { - false - }; - let arg_allows_tac = match needs_val_of { - ParseResult::Opt(name) => { - let o = self - .opts - .iter() - .find(|o| o.b.name == name) - .expect(INTERNAL_ERROR_MSG); - o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings - } - ParseResult::Pos(name) => { - let p = self - .positionals - .values() - .find(|p| p.b.name == name) - .expect(INTERNAL_ERROR_MSG); - p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings - } - ParseResult::ValuesDone => return true, - _ => false, - }; - debugln!("Parser::is_new_arg: arg_allows_tac={:?}", arg_allows_tac); - - // Is this a new argument, or values from a previous option? - let mut ret = if arg_os.starts_with(b"--") { - debugln!("Parser::is_new_arg: -- found"); - if arg_os.len() == 2 && !arg_allows_tac { - return true; // We have to return true so override everything else - } else if arg_allows_tac { - return false; - } - true - } else if arg_os.starts_with(b"-") { - debugln!("Parser::is_new_arg: - found"); - // a singe '-' by itself is a value and typically means "stdin" on unix systems - arg_os.len() != 1 - } else { - debugln!("Parser::is_new_arg: probably value"); - false - }; - - ret = ret && !arg_allows_tac; - - debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret); - ret - } - - // The actual parsing function - #[cfg_attr( - feature = "cargo-clippy", - allow(clippy::while_let_on_iterator, clippy::nonminimal_bool) - )] - pub fn get_matches_with( - &mut self, - matcher: &mut ArgMatcher<'a>, - it: &mut Peekable, - ) -> ClapResult<()> - where - I: Iterator, - T: Into + Clone, - { - debugln!("Parser::get_matches_with;"); - // Verify all positional assertions pass - debug_assert!(self.app_debug_asserts()); - if self.positionals.values().any(|a| { - a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) - }) && self - .positionals - .values() - .last() - .map_or(false, |p| !p.is_set(ArgSettings::Last)) - { - self.settings.set(AS::LowIndexMultiplePositional); - } - let has_args = self.has_args(); - - // Next we create the `--help` and `--version` arguments and add them if - // necessary - self.create_help_and_version(); - - let mut subcmd_name: Option = None; - let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound; - let mut pos_counter = 1; - let mut sc_is_external = false; - while let Some(arg) = it.next() { - let arg_os = arg.into(); - debugln!( - "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", - arg_os, - &*arg_os.as_bytes() - ); - - self.unset(AS::ValidNegNumFound); - // Is this a new argument, or values from a previous option? - let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of); - if !self.is_set(AS::TrailingValues) - && arg_os.starts_with(b"--") - && arg_os.len() == 2 - && starts_new_arg - { - debugln!("Parser::get_matches_with: setting TrailingVals=true"); - self.set(AS::TrailingValues); - continue; - } - - // Has the user already passed '--'? Meaning only positional args follow - if !self.is_set(AS::TrailingValues) { - // Does the arg match a subcommand name, or any of it's aliases (if defined) - { - match needs_val_of { - ParseResult::Opt(_) | ParseResult::Pos(_) => (), - _ => { - let (is_match, sc_name) = self.possible_subcommand(&arg_os); - debugln!( - "Parser::get_matches_with: possible_sc={:?}, sc={:?}", - is_match, - sc_name - ); - if is_match { - let sc_name = sc_name.expect(INTERNAL_ERROR_MSG); - if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) { - self.parse_help_subcommand(it)?; - } - subcmd_name = Some(sc_name.to_owned()); - break; - } - } - } - } - - if starts_new_arg { - let check_all = self.is_set(AS::AllArgsOverrideSelf); - { - let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); - matcher.process_arg_overrides( - any_arg, - &mut self.overrides, - &mut self.required, - check_all, - ); - } - - if arg_os.starts_with(b"--") { - needs_val_of = self.parse_long_arg(matcher, &arg_os, it)?; - debugln!( - "Parser:get_matches_with: After parse_long_arg {:?}", - needs_val_of - ); - match needs_val_of { - ParseResult::Flag | ParseResult::Opt(..) | ParseResult::ValuesDone => { - continue - } - _ => (), - } - } else if arg_os.starts_with(b"-") && arg_os.len() != 1 { - // Try to parse short args like normal, if AllowLeadingHyphen or - // AllowNegativeNumbers is set, parse_short_arg will *not* throw - // an error, and instead return Ok(None) - needs_val_of = self.parse_short_arg(matcher, &arg_os)?; - // If it's None, we then check if one of those two AppSettings was set - debugln!( - "Parser:get_matches_with: After parse_short_arg {:?}", - needs_val_of - ); - match needs_val_of { - ParseResult::MaybeNegNum => { - if !(arg_os.to_string_lossy().parse::().is_ok() - || arg_os.to_string_lossy().parse::().is_ok()) - { - return Err(Error::unknown_argument( - &*arg_os.to_string_lossy(), - "", - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - } - ParseResult::Opt(..) | ParseResult::Flag | ParseResult::ValuesDone => { - continue - } - _ => (), - } - } - } else if let ParseResult::Opt(name) = needs_val_of { - // Check to see if parsing a value from a previous arg - let arg = self - .opts - .iter() - .find(|o| o.b.name == name) - .expect(INTERNAL_ERROR_MSG); - // get the OptBuilder so we can check the settings - needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?; - // get the next value from the iterator - continue; - } - } - - if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound)) - && !self.is_set(AS::InferSubcommands) - && !self.is_set(AS::AllowExternalSubcommands) - { - if let Some(cdate) = - suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) - { - return Err(Error::invalid_subcommand( - arg_os.to_string_lossy().into_owned(), - cdate, - self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - } - - let low_index_mults = self.is_set(AS::LowIndexMultiplePositional) - && pos_counter == (self.positionals.len() - 1); - let missing_pos = self.is_set(AS::AllowMissingPositional) - && (pos_counter == (self.positionals.len() - 1) - && !self.is_set(AS::TrailingValues)); - debugln!( - "Parser::get_matches_with: Positional counter...{}", - pos_counter - ); - debugln!( - "Parser::get_matches_with: Low index multiples...{:?}", - low_index_mults - ); - if low_index_mults || missing_pos { - if let Some(na) = it.peek() { - let n = (*na).clone().into(); - needs_val_of = if needs_val_of != ParseResult::ValuesDone { - if let Some(p) = self.positionals.get(pos_counter) { - ParseResult::Pos(p.b.name) - } else { - ParseResult::ValuesDone - } - } else { - ParseResult::ValuesDone - }; - let sc_match = { self.possible_subcommand(&n).0 }; - if self.is_new_arg(&n, needs_val_of) - || sc_match - || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self)) - .is_some() - { - debugln!("Parser::get_matches_with: Bumping the positional counter..."); - pos_counter += 1; - } - } else { - debugln!("Parser::get_matches_with: Bumping the positional counter..."); - pos_counter += 1; - } - } else if (self.is_set(AS::AllowMissingPositional) && self.is_set(AS::TrailingValues)) - || (self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues)) - { - // Came to -- and one postional has .last(true) set, so we go immediately - // to the last (highest index) positional - debugln!("Parser::get_matches_with: .last(true) and --, setting last pos"); - pos_counter = self.positionals.len(); - } - if let Some(p) = self.positionals.get(pos_counter) { - if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) { - return Err(Error::unknown_argument( - &*arg_os.to_string_lossy(), - "", - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - if !self.is_set(AS::TrailingValues) - && (self.is_set(AS::TrailingVarArg) && pos_counter == self.positionals.len()) - { - self.settings.set(AS::TrailingValues); - } - if self.cache.map_or(true, |name| name != p.b.name) { - let check_all = self.is_set(AS::AllArgsOverrideSelf); - { - let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); - matcher.process_arg_overrides( - any_arg, - &mut self.overrides, - &mut self.required, - check_all, - ); - } - self.cache = Some(p.b.name); - } - let _ = self.add_val_to_arg(p, &arg_os, matcher)?; - - matcher.inc_occurrence_of(p.b.name); - let _ = self - .groups_for_arg(p.b.name) - .map(|vec| matcher.inc_occurrences_of(&*vec)); - - self.settings.set(AS::ValidArgFound); - // Only increment the positional counter if it doesn't allow multiples - if !p.b.settings.is_set(ArgSettings::Multiple) { - pos_counter += 1; - } - self.settings.set(AS::ValidArgFound); - } else if self.is_set(AS::AllowExternalSubcommands) { - // Get external subcommand name - let sc_name = match arg_os.to_str() { - Some(s) => s.to_string(), - None => { - if !self.is_set(AS::StrictUtf8) { - return Err(Error::invalid_utf8( - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - arg_os.to_string_lossy().into_owned() - } - }; - - // Collect the external subcommand args - let mut sc_m = ArgMatcher::new(); - // Due to borrow rules, this has to be a while let... - #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_let_on_iterator))] - while let Some(v) = it.next() { - let a = v.into(); - if a.to_str().is_none() && !self.is_set(AS::StrictUtf8) { - return Err(Error::invalid_utf8( - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - sc_m.add_val_to("", &a); - } - - matcher.subcommand(SubCommand { - name: sc_name, - matches: sc_m.into(), - }); - sc_is_external = true; - } else if !((self.is_set(AS::AllowLeadingHyphen) - || self.is_set(AS::AllowNegativeNumbers)) - && arg_os.starts_with(b"-")) - && !self.is_set(AS::InferSubcommands) - { - return Err(Error::unknown_argument( - &*arg_os.to_string_lossy(), - "", - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } else if !has_args || self.is_set(AS::InferSubcommands) && self.has_subcommands() { - if let Some(cdate) = - suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) - { - return Err(Error::invalid_subcommand( - arg_os.to_string_lossy().into_owned(), - cdate, - self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } else { - return Err(Error::unrecognized_subcommand( - arg_os.to_string_lossy().into_owned(), - self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), - self.color(), - )); - } - } else { - return Err(Error::unknown_argument( - &*arg_os.to_string_lossy(), - "", - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - } - - if !sc_is_external { - if let Some(ref pos_sc_name) = subcmd_name { - let sc_name = { - find_subcmd!(self, pos_sc_name) - .expect(INTERNAL_ERROR_MSG) - .p - .meta - .name - .clone() - }; - self.parse_subcommand(&*sc_name, matcher, it)?; - } else if self.is_set(AS::SubcommandRequired) { - let bn = self.meta.bin_name.as_ref().unwrap_or(&self.meta.name); - return Err(Error::missing_subcommand( - bn, - &usage::create_error_usage(self, matcher, None), - self.color(), - )); - } else if self.is_set(AS::SubcommandRequiredElseHelp) { - debugln!("Parser::get_matches_with: SubcommandRequiredElseHelp=true"); - let mut out = vec![]; - self.write_help_err(&mut out)?; - return Err(Error { - message: String::from_utf8_lossy(&*out).into_owned(), - kind: ErrorKind::MissingArgumentOrSubcommand, - info: None, - }); - } - } - - // In case the last arg was new, we need to process it's overrides - let check_all = self.is_set(AS::AllArgsOverrideSelf); - { - let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); - matcher.process_arg_overrides( - any_arg, - &mut self.overrides, - &mut self.required, - check_all, - ); - } - - self.remove_overrides(matcher); - - Validator::new(self).validate(needs_val_of, subcmd_name, matcher) - } - - fn remove_overrides(&mut self, matcher: &mut ArgMatcher) { - debugln!("Parser::remove_overrides:{:?};", self.overrides); - for &(overr, name) in &self.overrides { - debugln!("Parser::remove_overrides:iter:({},{});", overr, name); - if matcher.is_present(overr) { - debugln!( - "Parser::remove_overrides:iter:({},{}): removing {};", - overr, - name, - name - ); - matcher.remove(name); - for i in (0..self.required.len()).rev() { - debugln!( - "Parser::remove_overrides:iter:({},{}): removing required {};", - overr, - name, - name - ); - if self.required[i] == name { - self.required.swap_remove(i); - break; - } - } - } - } - } - - fn propagate_help_version(&mut self) { - debugln!("Parser::propagate_help_version;"); - self.create_help_and_version(); - for sc in &mut self.subcommands { - sc.p.propagate_help_version(); - } - } - - fn build_bin_names(&mut self) { - debugln!("Parser::build_bin_names;"); - for sc in &mut self.subcommands { - debug!("Parser::build_bin_names:iter: bin_name set..."); - if sc.p.meta.bin_name.is_none() { - sdebugln!("No"); - let bin_name = format!( - "{}{}{}", - self.meta - .bin_name - .as_ref() - .unwrap_or(&self.meta.name.clone()), - if self.meta.bin_name.is_some() { - " " - } else { - "" - }, - &*sc.p.meta.name - ); - debugln!( - "Parser::build_bin_names:iter: Setting bin_name of {} to {}", - self.meta.name, - bin_name - ); - sc.p.meta.bin_name = Some(bin_name); - } else { - sdebugln!("yes ({:?})", sc.p.meta.bin_name); - } - debugln!( - "Parser::build_bin_names:iter: Calling build_bin_names from...{}", - sc.p.meta.name - ); - sc.p.build_bin_names(); - } - } - - fn parse_subcommand( - &mut self, - sc_name: &str, - matcher: &mut ArgMatcher<'a>, - it: &mut Peekable, - ) -> ClapResult<()> - where - I: Iterator, - T: Into + Clone, - { - use std::fmt::Write; - debugln!("Parser::parse_subcommand;"); - let mut mid_string = String::new(); - if !self.is_set(AS::SubcommandsNegateReqs) { - let mut hs: Vec<&str> = self.required.iter().map(|n| &**n).collect(); - for k in matcher.arg_names() { - hs.push(k); - } - let reqs = usage::get_required_usage_from(self, &hs, Some(matcher), None, false); - - for s in &reqs { - write!(&mut mid_string, " {}", s).expect(INTERNAL_ERROR_MSG); - } - } - mid_string.push(' '); - if let Some(ref mut sc) = self - .subcommands - .iter_mut() - .find(|s| s.p.meta.name == sc_name) - { - let mut sc_matcher = ArgMatcher::new(); - // bin_name should be parent's bin_name + [] + the sc's name separated by - // a space - sc.p.meta.usage = Some(format!( - "{}{}{}", - self.meta.bin_name.as_ref().unwrap_or(&String::new()), - if self.meta.bin_name.is_some() { - &*mid_string - } else { - "" - }, - &*sc.p.meta.name - )); - sc.p.meta.bin_name = Some(format!( - "{}{}{}", - self.meta.bin_name.as_ref().unwrap_or(&String::new()), - if self.meta.bin_name.is_some() { - " " - } else { - "" - }, - &*sc.p.meta.name - )); - debugln!( - "Parser::parse_subcommand: About to parse sc={}", - sc.p.meta.name - ); - debugln!("Parser::parse_subcommand: sc settings={:#?}", sc.p.settings); - sc.p.get_matches_with(&mut sc_matcher, it)?; - matcher.subcommand(SubCommand { - name: sc.p.meta.name.clone(), - matches: sc_matcher.into(), - }); - } - Ok(()) - } - - pub fn groups_for_arg(&self, name: &str) -> Option> { - debugln!("Parser::groups_for_arg: name={}", name); - - if self.groups.is_empty() { - debugln!("Parser::groups_for_arg: No groups defined"); - return None; - } - let mut res = vec![]; - debugln!("Parser::groups_for_arg: Searching through groups..."); - for grp in &self.groups { - for a in &grp.args { - if a == &name { - sdebugln!("\tFound '{}'", grp.name); - res.push(&*grp.name); - } - } - } - if res.is_empty() { - return None; - } - - Some(res) - } - - pub fn args_in_group(&self, group: &str) -> Vec { - debug_assert!(self.app_debug_asserts()); - - let mut g_vec = vec![]; - let mut args = vec![]; - - for n in &self - .groups - .iter() - .find(|g| g.name == group) - .expect(INTERNAL_ERROR_MSG) - .args - { - if let Some(f) = self.flags.iter().find(|f| &f.b.name == n) { - args.push(f.to_string()); - } else if let Some(f) = self.opts.iter().find(|o| &o.b.name == n) { - args.push(f.to_string()); - } else if let Some(p) = self.positionals.values().find(|p| &p.b.name == n) { - args.push(p.b.name.to_owned()); - } else { - g_vec.push(*n); - } - } - - for av in g_vec.iter().map(|g| self.args_in_group(g)) { - args.extend(av); - } - args.dedup(); - args.iter().map(ToOwned::to_owned).collect() - } - - pub fn arg_names_in_group(&self, group: &str) -> Vec<&'a str> { - let mut g_vec = vec![]; - let mut args = vec![]; - - for n in &self - .groups - .iter() - .find(|g| g.name == group) - .expect(INTERNAL_ERROR_MSG) - .args - { - if self.groups.iter().any(|g| g.name == *n) { - args.extend(self.arg_names_in_group(n)); - g_vec.push(*n); - } else if !args.contains(n) { - args.push(*n); - } - } - - args.iter().copied().collect() - } - - pub fn create_help_and_version(&mut self) { - debugln!("Parser::create_help_and_version;"); - // name is "hclap_help" because flags are sorted by name - if !self.is_set(AS::DisableHelpFlags) && !self.contains_long("help") { - debugln!("Parser::create_help_and_version: Building --help"); - if self.help_short.is_none() && !self.contains_short('h') { - self.help_short = Some('h'); - } - let arg = FlagBuilder { - b: Base { - name: "hclap_help", - help: self.help_message.or(Some("Prints help information")), - ..Default::default() - }, - s: Switched { - short: self.help_short, - long: Some("help"), - ..Default::default() - }, - }; - self.flags.push(arg); - } - if !self.is_set(AS::DisableVersion) && !self.contains_long("version") { - debugln!("Parser::create_help_and_version: Building --version"); - if self.version_short.is_none() && !self.contains_short('V') { - self.version_short = Some('V'); - } - // name is "vclap_version" because flags are sorted by name - let arg = FlagBuilder { - b: Base { - name: "vclap_version", - help: self.version_message.or(Some("Prints version information")), - ..Default::default() - }, - s: Switched { - short: self.version_short, - long: Some("version"), - ..Default::default() - }, - }; - self.flags.push(arg); - } - if !self.subcommands.is_empty() - && !self.is_set(AS::DisableHelpSubcommand) - && self.is_set(AS::NeedsSubcommandHelp) - { - debugln!("Parser::create_help_and_version: Building help"); - self.subcommands.push( - App::new("help") - .about("Prints this message or the help of the given subcommand(s)"), - ); - } - } - - // Retrieves the names of all args the user has supplied thus far, except required ones - // because those will be listed in self.required - fn check_for_help_and_version_str(&self, arg: &OsStr) -> ClapResult<()> { - debugln!("Parser::check_for_help_and_version_str;"); - debug!( - "Parser::check_for_help_and_version_str: Checking if --{} is help or version...", - arg.to_str().unwrap() - ); - if arg == "help" && self.is_set(AS::NeedsLongHelp) { - sdebugln!("Help"); - return Err(self._help(true)); - } - if arg == "version" && self.is_set(AS::NeedsLongVersion) { - sdebugln!("Version"); - return Err(self._version(true)); - } - sdebugln!("Neither"); - - Ok(()) - } - - fn check_for_help_and_version_char(&self, arg: char) -> ClapResult<()> { - debugln!("Parser::check_for_help_and_version_char;"); - debug!( - "Parser::check_for_help_and_version_char: Checking if -{} is help or version...", - arg - ); - if let Some(h) = self.help_short { - if arg == h && self.is_set(AS::NeedsLongHelp) { - sdebugln!("Help"); - return Err(self._help(false)); - } - } - if let Some(v) = self.version_short { - if arg == v && self.is_set(AS::NeedsLongVersion) { - sdebugln!("Version"); - return Err(self._version(false)); - } - } - sdebugln!("Neither"); - Ok(()) - } - - fn use_long_help(&self) -> bool { - // 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 HiddenShortHelp is not included, - // then items specified with hidden_short_help will also be hidden. - let should_long = |v: &Base| { - v.long_help.is_some() - || v.is_set(ArgSettings::HiddenLongHelp) - || v.is_set(ArgSettings::HiddenShortHelp) - }; - - self.meta.long_about.is_some() - || self.flags.iter().any(|f| should_long(&f.b)) - || self.opts.iter().any(|o| should_long(&o.b)) - || self.positionals.values().any(|p| should_long(&p.b)) - || self - .subcommands - .iter() - .any(|s| s.p.meta.long_about.is_some()) - } - - fn _help(&self, mut use_long: bool) -> Error { - debugln!("Parser::_help: use_long={:?}", use_long); - use_long = use_long && self.use_long_help(); - let mut buf = vec![]; - match Help::write_parser_help(&mut buf, self, use_long) { - Err(e) => e, - _ => Error { - message: String::from_utf8(buf).unwrap_or_default(), - kind: ErrorKind::HelpDisplayed, - info: None, - }, - } - } - - fn _version(&self, use_long: bool) -> Error { - debugln!("Parser::_version: "); - let out = io::stdout(); - let mut buf_w = BufWriter::new(out.lock()); - match self.print_version(&mut buf_w, use_long) { - Err(e) => e, - _ => Error { - message: String::new(), - kind: ErrorKind::VersionDisplayed, - info: None, - }, - } - } - - fn parse_long_arg( - &mut self, - matcher: &mut ArgMatcher<'a>, - full_arg: &OsStr, - it: &mut Peekable, - ) -> ClapResult> - where - I: Iterator, - T: Into + Clone, - { - // maybe here lifetime should be 'a - debugln!("Parser::parse_long_arg;"); - - // Update the current index - self.cur_idx.set(self.cur_idx.get() + 1); - - let mut val = None; - debug!("Parser::parse_long_arg: Does it contain '='..."); - let arg = if full_arg.contains_byte(b'=') { - let (p0, p1) = full_arg.trim_left_matches(b'-').split_at_byte(b'='); - sdebugln!("Yes '{:?}'", p1); - val = Some(p1); - p0 - } else { - sdebugln!("No"); - full_arg.trim_left_matches(b'-') - }; - - if let Some(opt) = find_opt_by_long!(@os self, arg) { - debugln!( - "Parser::parse_long_arg: Found valid opt '{}'", - opt.to_string() - ); - self.settings.set(AS::ValidArgFound); - let ret = self.parse_opt(val, opt, val.is_some(), matcher)?; - if self.cache.map_or(true, |name| name != opt.b.name) { - self.cache = Some(opt.b.name); - } - - return Ok(ret); - } else if let Some(flag) = find_flag_by_long!(@os self, arg) { - debugln!( - "Parser::parse_long_arg: Found valid flag '{}'", - flag.to_string() - ); - self.settings.set(AS::ValidArgFound); - // Only flags could be help or version, and we need to check the raw long - // so this is the first point to check - self.check_for_help_and_version_str(arg)?; - - self.parse_flag(flag, matcher)?; - - // Handle conflicts, requirements, etc. - if self.cache.map_or(true, |name| name != flag.b.name) { - self.cache = Some(flag.b.name); - } - - return Ok(ParseResult::Flag); - } else if self.is_set(AS::AllowLeadingHyphen) { - return Ok(ParseResult::MaybeHyphenValue); - } else if self.is_set(AS::ValidNegNumFound) { - return Ok(ParseResult::MaybeNegNum); - } - - debugln!("Parser::parse_long_arg: Didn't match anything"); - - let args_rest: Vec<_> = it.map(|x| x.into()).collect(); - let args_rest2: Vec<_> = args_rest - .iter() - .map(|x| x.to_str().expect(INVALID_UTF8)) - .collect(); - self.did_you_mean_error(arg.to_str().expect(INVALID_UTF8), matcher, &args_rest2[..]) - .map(|_| ParseResult::NotFound) - } - - fn parse_short_arg( - &mut self, - matcher: &mut ArgMatcher<'a>, - full_arg: &OsStr, - ) -> ClapResult> { - debugln!("Parser::parse_short_arg: full_arg={:?}", full_arg); - let arg_os = full_arg.trim_left_matches(b'-'); - let arg = arg_os.to_string_lossy(); - - // If AllowLeadingHyphen is set, we want to ensure `-val` gets parsed as `-val` and not - // `-v` `-a` `-l` assuming `v` `a` and `l` are all, or mostly, valid shorts. - if self.is_set(AS::AllowLeadingHyphen) { - if arg.chars().any(|c| !self.contains_short(c)) { - debugln!( - "Parser::parse_short_arg: LeadingHyphenAllowed yet -{} isn't valid", - arg - ); - return Ok(ParseResult::MaybeHyphenValue); - } - } else if self.is_set(AS::ValidNegNumFound) { - // TODO: Add docs about having AllowNegativeNumbers and `-2` as a valid short - // May be better to move this to *after* not finding a valid flag/opt? - debugln!("Parser::parse_short_arg: Valid negative num..."); - return Ok(ParseResult::MaybeNegNum); - } - - let mut ret = ParseResult::NotFound; - for c in arg.chars() { - debugln!("Parser::parse_short_arg:iter:{}", c); - - // update each index because `-abcd` is four indices to clap - self.cur_idx.set(self.cur_idx.get() + 1); - - // Check for matching short options, and return the name if there is no trailing - // concatenated value: -oval - // Option: -o - // Value: val - if let Some(opt) = find_opt_by_short!(self, c) { - debugln!("Parser::parse_short_arg:iter:{}: Found valid opt", c); - self.settings.set(AS::ValidArgFound); - // Check for trailing concatenated value - let p: Vec<_> = arg.splitn(2, c).collect(); - debugln!( - "Parser::parse_short_arg:iter:{}: p[0]={:?}, p[1]={:?}", - c, - p[0].as_bytes(), - p[1].as_bytes() - ); - let i = p[0].as_bytes().len() + 1; - let val = if !p[1].as_bytes().is_empty() { - debugln!( - "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii)", - c, - arg_os.split_at(i).1.as_bytes(), - arg_os.split_at(i).1 - ); - Some(arg_os.split_at(i).1) - } else { - None - }; - - // Default to "we're expecting a value later" - let ret = self.parse_opt(val, opt, false, matcher)?; - - if self.cache.map_or(true, |name| name != opt.b.name) { - self.cache = Some(opt.b.name); - } - - return Ok(ret); - } else if let Some(flag) = find_flag_by_short!(self, c) { - debugln!("Parser::parse_short_arg:iter:{}: Found valid flag", c); - self.settings.set(AS::ValidArgFound); - // Only flags can be help or version - self.check_for_help_and_version_char(c)?; - ret = self.parse_flag(flag, matcher)?; - - // Handle conflicts, requirements, overrides, etc. - // Must be called here due to mutabililty - if self.cache.map_or(true, |name| name != flag.b.name) { - self.cache = Some(flag.b.name); - } - } else { - let arg = format!("-{}", c); - return Err(Error::unknown_argument( - &*arg, - "", - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - } - Ok(ret) - } - - fn parse_opt( - &self, - val: Option<&OsStr>, - opt: &OptBuilder<'a, 'b>, - had_eq: bool, - matcher: &mut ArgMatcher<'a>, - ) -> ClapResult> { - debugln!("Parser::parse_opt; opt={}, val={:?}", opt.b.name, val); - debugln!("Parser::parse_opt; opt.settings={:?}", opt.b.settings); - let mut has_eq = false; - let no_val = val.is_none(); - let empty_vals = opt.is_set(ArgSettings::EmptyValues); - let min_vals_zero = opt.v.min_vals.unwrap_or(1) == 0; - let needs_eq = opt.is_set(ArgSettings::RequireEquals); - - debug!("Parser::parse_opt; Checking for val..."); - if let Some(fv) = val { - has_eq = fv.starts_with(&[b'=']) || had_eq; - let v = fv.trim_left_matches(b'='); - if !empty_vals && (v.is_empty() || (needs_eq && !has_eq)) { - sdebugln!("Found Empty - Error"); - return Err(Error::empty_value( - opt, - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } - sdebugln!("Found - {:?}, len: {}", v, v.len()); - debugln!( - "Parser::parse_opt: {:?} contains '='...{:?}", - fv, - fv.starts_with(&[b'=']) - ); - self.add_val_to_arg(opt, v, matcher)?; - } else if needs_eq && !(empty_vals || min_vals_zero) { - sdebugln!("None, but requires equals...Error"); - return Err(Error::empty_value( - opt, - &*usage::create_error_usage(self, matcher, None), - self.color(), - )); - } else { - sdebugln!("None"); - } - - matcher.inc_occurrence_of(opt.b.name); - // Increment or create the group "args" - if let Some(vec) = self.groups_for_arg(opt.b.name) { - matcher.inc_occurrences_of(&*vec); - } - - let needs_delim = opt.is_set(ArgSettings::RequireDelimiter); - let mult = opt.is_set(ArgSettings::Multiple); - if no_val && min_vals_zero && !has_eq && needs_eq { - debugln!("Parser::parse_opt: More arg vals not required..."); - return Ok(ParseResult::ValuesDone); - } else if no_val || (mult && !needs_delim) && !has_eq && matcher.needs_more_vals(opt) { - debugln!("Parser::parse_opt: More arg vals required..."); - return Ok(ParseResult::Opt(opt.b.name)); - } - debugln!("Parser::parse_opt: More arg vals not required..."); - Ok(ParseResult::ValuesDone) - } - - fn add_val_to_arg( - &self, - arg: &A, - val: &OsStr, - matcher: &mut ArgMatcher<'a>, - ) -> ClapResult> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name(), val); - debugln!( - "Parser::add_val_to_arg; trailing_vals={:?}, DontDelimTrailingVals={:?}", - self.is_set(AS::TrailingValues), - self.is_set(AS::DontDelimitTrailingValues) - ); - if !(self.is_set(AS::TrailingValues) && self.is_set(AS::DontDelimitTrailingValues)) { - if let Some(delim) = arg.val_delim() { - if val.is_empty() { - Ok(self.add_single_val_to_arg(arg, val, matcher)?) - } else { - let mut iret = ParseResult::ValuesDone; - for v in val.split(delim as u32 as u8) { - iret = self.add_single_val_to_arg(arg, v, matcher)?; - } - // If there was a delimiter used, we're not looking for more values - if val.contains_byte(delim as u32 as u8) - || arg.is_set(ArgSettings::RequireDelimiter) - { - iret = ParseResult::ValuesDone; - } - Ok(iret) - } - } else { - self.add_single_val_to_arg(arg, val, matcher) - } - } else { - self.add_single_val_to_arg(arg, val, matcher) - } - } - - fn add_single_val_to_arg( - &self, - arg: &A, - v: &OsStr, - matcher: &mut ArgMatcher<'a>, - ) -> ClapResult> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Parser::add_single_val_to_arg;"); - debugln!("Parser::add_single_val_to_arg: adding val...{:?}", v); - - // update the current index because each value is a distinct index to clap - self.cur_idx.set(self.cur_idx.get() + 1); - - // @TODO @docs @p4: docs for indices should probably note that a terminator isn't a value - // and therefore not reported in indices - if let Some(t) = arg.val_terminator() { - if t == v { - return Ok(ParseResult::ValuesDone); - } - } - - matcher.add_val_to(arg.name(), v); - matcher.add_index_to(arg.name(), self.cur_idx.get()); - - // Increment or create the group "args" - if let Some(grps) = self.groups_for_arg(arg.name()) { - for grp in grps { - matcher.add_val_to(&*grp, v); - } - } - - if matcher.needs_more_vals(arg) { - return Ok(ParseResult::Opt(arg.name())); - } - Ok(ParseResult::ValuesDone) - } - - fn parse_flag( - &self, - flag: &FlagBuilder<'a, 'b>, - matcher: &mut ArgMatcher<'a>, - ) -> ClapResult> { - debugln!("Parser::parse_flag;"); - - matcher.inc_occurrence_of(flag.b.name); - matcher.add_index_to(flag.b.name, self.cur_idx.get()); - - // Increment or create the group "args" - if let Some(vec) = self.groups_for_arg(flag.b.name) { - matcher.inc_occurrences_of(&*vec); - } - - Ok(ParseResult::Flag) - } - - fn did_you_mean_error( - &self, - arg: &str, - matcher: &mut ArgMatcher<'a>, - args_rest: &[&str], - ) -> ClapResult<()> { - // Didn't match a flag or option - let suffix = - suggestions::did_you_mean_flag_suffix(arg, args_rest, longs!(self), &self.subcommands); - - // Add the arg to the matches to build a proper usage string - if let Some(name) = suffix.1 { - if let Some(opt) = find_opt_by_long!(self, name) { - if let Some(grps) = self.groups_for_arg(&*opt.b.name) { - matcher.inc_occurrences_of(&*grps); - } - matcher.insert(&*opt.b.name); - } else if let Some(flg) = find_flag_by_long!(self, name) { - if let Some(grps) = self.groups_for_arg(&*flg.b.name) { - matcher.inc_occurrences_of(&*grps); - } - matcher.insert(&*flg.b.name); - } - } - - let used_arg = format!("--{}", arg); - Err(Error::unknown_argument( - &*used_arg, - &*suffix.0, - &*usage::create_error_usage(self, matcher, None), - self.color(), - )) - } - - // Prints the version to the user and exits if quit=true - fn print_version(&self, w: &mut W, use_long: bool) -> ClapResult<()> { - self.write_version(w, use_long)?; - w.flush().map_err(Error::from) - } - - pub fn write_version(&self, w: &mut W, use_long: bool) -> io::Result<()> { - let ver = if use_long { - self.meta - .long_version - .unwrap_or_else(|| self.meta.version.unwrap_or("")) - } else { - self.meta - .version - .unwrap_or_else(|| self.meta.long_version.unwrap_or("")) - }; - if let Some(bn) = self.meta.bin_name.as_ref() { - if bn.contains(' ') { - // Incase we're dealing with subcommands i.e. git mv is translated to git-mv - write!(w, "{} {}", bn.replace(" ", "-"), ver) - } else { - write!(w, "{} {}", &self.meta.name[..], ver) - } - } else { - write!(w, "{} {}", &self.meta.name[..], ver) - } - } - - pub fn print_help(&self) -> ClapResult<()> { - let out = io::stdout(); - let mut buf_w = BufWriter::new(out.lock()); - self.write_help(&mut buf_w) - } - - pub fn write_help(&self, w: &mut W) -> ClapResult<()> { - Help::write_parser_help(w, self, false) - } - - pub fn write_long_help(&self, w: &mut W) -> ClapResult<()> { - Help::write_parser_help(w, self, true) - } - - pub fn write_help_err(&self, w: &mut W) -> ClapResult<()> { - Help::write_parser_help_to_stderr(w, self) - } - - pub fn add_defaults(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { - debugln!("Parser::add_defaults;"); - macro_rules! add_val { - (@default $_self:ident, $a:ident, $m:ident) => { - if let Some(ref val) = $a.v.default_val { - debugln!("Parser::add_defaults:iter:{}: has default vals", $a.b.name); - if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) { - debugln!("Parser::add_defaults:iter:{}: has no user defined vals", $a.b.name); - $_self.add_val_to_arg($a, OsStr::new(val), $m)?; - - if $_self.cache.map_or(true, |name| name != $a.name()) { - $_self.cache = Some($a.name()); - } - } else if $m.get($a.b.name).is_some() { - debugln!("Parser::add_defaults:iter:{}: has user defined vals", $a.b.name); - } else { - debugln!("Parser::add_defaults:iter:{}: wasn't used", $a.b.name); - - $_self.add_val_to_arg($a, OsStr::new(val), $m)?; - - if $_self.cache.map_or(true, |name| name != $a.name()) { - $_self.cache = Some($a.name()); - } - } - } else { - debugln!("Parser::add_defaults:iter:{}: doesn't have default vals", $a.b.name); - } - }; - ($_self:ident, $a:ident, $m:ident) => { - if let Some(ref vm) = $a.v.default_vals_ifs { - sdebugln!(" has conditional defaults"); - let mut done = false; - if $m.get($a.b.name).is_none() { - for &(arg, val, default) in vm.values() { - let add = if let Some(a) = $m.get(arg) { - if let Some(v) = val { - a.vals.iter().any(|value| v == value) - } else { - true - } - } else { - false - }; - if add { - $_self.add_val_to_arg($a, OsStr::new(default), $m)?; - if $_self.cache.map_or(true, |name| name != $a.name()) { - $_self.cache = Some($a.name()); - } - done = true; - break; - } - } - } - - if done { - continue; // outer loop (outside macro) - } - } else { - sdebugln!(" doesn't have conditional defaults"); - } - add_val!(@default $_self, $a, $m) - }; - } - - for o in &self.opts { - debug!("Parser::add_defaults:iter:{}:", o.b.name); - add_val!(self, o, matcher); - } - for p in self.positionals.values() { - debug!("Parser::add_defaults:iter:{}:", p.b.name); - add_val!(self, p, matcher); - } - Ok(()) - } - - pub fn add_env(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { - macro_rules! add_val { - ($_self:ident, $a:ident, $m:ident) => { - if let Some(ref val) = $a.v.env { - if $m - .get($a.b.name) - .map(|ma| ma.vals.len()) - .map(|len| len == 0) - .unwrap_or(false) - { - if let Some(ref val) = val.1 { - $_self.add_val_to_arg($a, OsStr::new(val), $m)?; - - if $_self.cache.map_or(true, |name| name != $a.name()) { - $_self.cache = Some($a.name()); - } - } - } else { - if let Some(ref val) = val.1 { - $_self.add_val_to_arg($a, OsStr::new(val), $m)?; - - if $_self.cache.map_or(true, |name| name != $a.name()) { - $_self.cache = Some($a.name()); - } - } - } - } - }; - } - - for o in &self.opts { - add_val!(self, o, matcher); - } - for p in self.positionals.values() { - add_val!(self, p, matcher); - } - Ok(()) - } - - pub fn flags(&self) -> Iter> { - self.flags.iter() - } - - pub fn opts(&self) -> Iter> { - self.opts.iter() - } - - pub fn positionals(&self) -> map::Values> { - self.positionals.values() - } - - pub fn subcommands(&self) -> Iter { - self.subcommands.iter() - } - - // Should we color the output? None=determined by output location, true=yes, false=no - #[doc(hidden)] - pub fn color(&self) -> ColorWhen { - debugln!("Parser::color;"); - debug!("Parser::color: Color setting..."); - if self.is_set(AS::ColorNever) { - sdebugln!("Never"); - ColorWhen::Never - } else if self.is_set(AS::ColorAlways) { - sdebugln!("Always"); - ColorWhen::Always - } else { - sdebugln!("Auto"); - ColorWhen::Auto - } - } - - pub fn find_any_arg(&self, name: &str) -> Option<&AnyArg<'a, 'b>> { - if let Some(f) = find_by_name!(self, name, flags, iter) { - return Some(f); - } - if let Some(o) = find_by_name!(self, name, opts, iter) { - return Some(o); - } - if let Some(p) = find_by_name!(self, name, positionals, values) { - return Some(p); - } - None - } - - /// Check is a given string matches the binary name for this parser - fn is_bin_name(&self, value: &str) -> bool { - self.meta - .bin_name - .as_ref() - .map(|name| value == name) - .unwrap_or(false) - } - - /// Check is a given string is an alias for this parser - fn is_alias(&self, value: &str) -> bool { - self.meta - .aliases - .as_ref() - .map(|aliases| { - for alias in aliases { - if alias.0 == value { - return true; - } - } - false - }) - .unwrap_or(false) - } - - // Only used for completion scripts due to bin_name messiness - #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))] - pub fn find_subcommand(&'b self, sc: &str) -> Option<&'b App<'a, 'b>> { - debugln!("Parser::find_subcommand: sc={}", sc); - debugln!( - "Parser::find_subcommand: Currently in Parser...{}", - self.meta.bin_name.as_ref().unwrap() - ); - for s in &self.subcommands { - if s.p.is_bin_name(sc) { - return Some(s); - } - // XXX: why do we split here? - // isn't `sc` supposed to be single word already? - let last = sc.split(' ').rev().next().expect(INTERNAL_ERROR_MSG); - if s.p.is_alias(last) { - return Some(s); - } - - if let Some(app) = s.p.find_subcommand(sc) { - return Some(app); - } - } - None - } - - #[inline] - fn contains_long(&self, l: &str) -> bool { - longs!(self).any(|al| al == &l) - } - - #[inline] - fn contains_short(&self, s: char) -> bool { - shorts!(self).any(|arg_s| arg_s == &s) - } -} diff --git a/third_party/rust/clap/src/app/settings.rs b/third_party/rust/clap/src/app/settings.rs deleted file mode 100644 index e387d9e90133..000000000000 --- a/third_party/rust/clap/src/app/settings.rs +++ /dev/null @@ -1,1192 +0,0 @@ -// Std -#[allow(deprecated, unused_imports)] -use std::ascii::AsciiExt; -use std::ops::BitOr; -use std::str::FromStr; - -bitflags! { - struct Flags: u64 { - const SC_NEGATE_REQS = 1; - const SC_REQUIRED = 1 << 1; - const A_REQUIRED_ELSE_HELP = 1 << 2; - const GLOBAL_VERSION = 1 << 3; - const VERSIONLESS_SC = 1 << 4; - const UNIFIED_HELP = 1 << 5; - const WAIT_ON_ERROR = 1 << 6; - const SC_REQUIRED_ELSE_HELP= 1 << 7; - const NEEDS_LONG_HELP = 1 << 8; - const NEEDS_LONG_VERSION = 1 << 9; - const NEEDS_SC_HELP = 1 << 10; - const DISABLE_VERSION = 1 << 11; - const HIDDEN = 1 << 12; - const TRAILING_VARARG = 1 << 13; - const NO_BIN_NAME = 1 << 14; - const ALLOW_UNK_SC = 1 << 15; - const UTF8_STRICT = 1 << 16; - const UTF8_NONE = 1 << 17; - const LEADING_HYPHEN = 1 << 18; - const NO_POS_VALUES = 1 << 19; - const NEXT_LINE_HELP = 1 << 20; - const DERIVE_DISP_ORDER = 1 << 21; - const COLORED_HELP = 1 << 22; - const COLOR_ALWAYS = 1 << 23; - const COLOR_AUTO = 1 << 24; - const COLOR_NEVER = 1 << 25; - const DONT_DELIM_TRAIL = 1 << 26; - const ALLOW_NEG_NUMS = 1 << 27; - const LOW_INDEX_MUL_POS = 1 << 28; - const DISABLE_HELP_SC = 1 << 29; - const DONT_COLLAPSE_ARGS = 1 << 30; - const ARGS_NEGATE_SCS = 1 << 31; - const PROPAGATE_VALS_DOWN = 1 << 32; - const ALLOW_MISSING_POS = 1 << 33; - const TRAILING_VALUES = 1 << 34; - const VALID_NEG_NUM_FOUND = 1 << 35; - const PROPAGATED = 1 << 36; - const VALID_ARG_FOUND = 1 << 37; - const INFER_SUBCOMMANDS = 1 << 38; - const CONTAINS_LAST = 1 << 39; - const ARGS_OVERRIDE_SELF = 1 << 40; - const DISABLE_HELP_FLAGS = 1 << 41; - } -} - -#[doc(hidden)] -#[derive(Debug, Copy, Clone, PartialEq)] -pub struct AppFlags(Flags); - -impl BitOr for AppFlags { - type Output = Self; - fn bitor(self, rhs: Self) -> Self { - AppFlags(self.0 | rhs.0) - } -} - -impl Default for AppFlags { - fn default() -> Self { - AppFlags( - Flags::NEEDS_LONG_VERSION - | Flags::NEEDS_LONG_HELP - | Flags::NEEDS_SC_HELP - | Flags::UTF8_NONE - | Flags::COLOR_AUTO, - ) - } -} - -#[allow(deprecated)] -impl AppFlags { - pub fn new() -> Self { - AppFlags::default() - } - pub fn zeroed() -> Self { - AppFlags(Flags::empty()) - } - - impl_settings! { AppSettings, - ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP, - ArgsNegateSubcommands => Flags::ARGS_NEGATE_SCS, - AllArgsOverrideSelf => Flags::ARGS_OVERRIDE_SELF, - AllowExternalSubcommands => Flags::ALLOW_UNK_SC, - AllowInvalidUtf8 => Flags::UTF8_NONE, - AllowLeadingHyphen => Flags::LEADING_HYPHEN, - AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS, - AllowMissingPositional => Flags::ALLOW_MISSING_POS, - ColoredHelp => Flags::COLORED_HELP, - 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, - DisableHelpFlags => Flags::DISABLE_HELP_FLAGS, - DisableHelpSubcommand => Flags::DISABLE_HELP_SC, - DisableVersion => Flags::DISABLE_VERSION, - GlobalVersion => Flags::GLOBAL_VERSION, - HidePossibleValuesInHelp => Flags::NO_POS_VALUES, - Hidden => Flags::HIDDEN, - LowIndexMultiplePositional => Flags::LOW_INDEX_MUL_POS, - NeedsLongHelp => Flags::NEEDS_LONG_HELP, - NeedsLongVersion => Flags::NEEDS_LONG_VERSION, - NeedsSubcommandHelp => Flags::NEEDS_SC_HELP, - NoBinaryName => Flags::NO_BIN_NAME, - PropagateGlobalValuesDown=> Flags::PROPAGATE_VALS_DOWN, - StrictUtf8 => Flags::UTF8_STRICT, - SubcommandsNegateReqs => Flags::SC_NEGATE_REQS, - SubcommandRequired => Flags::SC_REQUIRED, - SubcommandRequiredElseHelp => Flags::SC_REQUIRED_ELSE_HELP, - TrailingVarArg => Flags::TRAILING_VARARG, - UnifiedHelpMessage => Flags::UNIFIED_HELP, - NextLineHelp => Flags::NEXT_LINE_HELP, - VersionlessSubcommands => Flags::VERSIONLESS_SC, - WaitOnError => Flags::WAIT_ON_ERROR, - TrailingValues => Flags::TRAILING_VALUES, - ValidNegNumFound => Flags::VALID_NEG_NUM_FOUND, - Propagated => Flags::PROPAGATED, - ValidArgFound => Flags::VALID_ARG_FOUND, - InferSubcommands => Flags::INFER_SUBCOMMANDS, - ContainsLast => Flags::CONTAINS_LAST - } -} - -/// Application level settings, which affect how [`App`] 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 -/// -/// [`App`]: ./struct.App.html -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum AppSettings { - /// Specifies that any invalid UTF-8 code points should *not* be treated as an error. - /// This is the default behavior of `clap`. - /// - /// **NOTE:** Using argument values with invalid UTF-8 code points requires using - /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`], - /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid - /// UTF-8 values - /// - /// **NOTE:** This rule only applies to argument values, as flags, options, and - /// [`SubCommand`]s themselves only allow valid UTF-8 code points. - /// - /// # Platform Specific - /// - /// Non Windows systems only - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, AppSettings}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let r = App::new("myprog") - /// //.setting(AppSettings::AllowInvalidUtf8) - /// .arg_from_usage(" 'some positional arg'") - /// .get_matches_from_safe( - /// vec![ - /// OsString::from("myprog"), - /// OsString::from_vec(vec![0xe9])]); - /// - /// assert!(r.is_ok()); - /// let m = r.unwrap(); - /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]); - /// ``` - /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of - /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of - /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of - /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of - /// [`SubCommand`]: ./struct.SubCommand.html - AllowInvalidUtf8, - - /// Essentially sets [`Arg::overrides_with("itself")`] for all arguments. - /// - /// **WARNING:** Positional arguments cannot override themselves (or we would never be able - /// to advance to the next positional). This setting ignores positional arguments. - /// [`Arg::overrides_with("itself")`]: ./struct.Arg.html#method.overrides_with - AllArgsOverrideSelf, - - /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers - /// like `-10`. (which would otherwise be parsed as another flag or option) - /// - /// **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, App, AppSettings}; - /// // Imagine you needed to represent negative numbers as well, such as -10 - /// let m = App::new("nums") - /// .setting(AppSettings::AllowLeadingHyphen) - /// .arg(Arg::with_name("neg").index(1)) - /// .get_matches_from(vec![ - /// "nums", "-20" - /// ]); - /// - /// assert_eq!(m.value_of("neg"), Some("-20")); - /// # ; - /// ``` - /// [`Arg::allow_hyphen_values`]: ./struct.Arg.html#method.allow_hyphen_values - AllowLeadingHyphen, - - /// Allows negative numbers to pass as values. This is similar to - /// `AllowLeadingHyphen` except that it only allows numbers, all - /// other undefined leading hyphens will fail to parse. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// let res = App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::AllowNegativeNumbers) - /// .arg(Arg::with_name("num")) - /// .get_matches_from_safe(vec![ - /// "myprog", "-20" - /// ]); - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.value_of("num").unwrap(), "-20"); - /// ``` - /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen - AllowNegativeNumbers, - - /// 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 possible: - /// - /// * `$ prog foo bar baz1 baz2 baz3` - /// * `$ prog foo -- baz1 baz2 baz3` - /// * `$ prog -- baz1 baz2 baz3` - /// - /// # Examples - /// - /// Style number one from above: - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = App::new("myprog") - /// .setting(AppSettings::AllowMissingPositional) - /// .arg(Arg::with_name("arg1")) - /// .arg(Arg::with_name("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::{App, Arg, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = App::new("myprog") - /// .setting(AppSettings::AllowMissingPositional) - /// .arg(Arg::with_name("arg1") - /// .default_value("something")) - /// .arg(Arg::with_name("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::{App, Arg, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = App::new("myprog") - /// .setting(AppSettings::AllowMissingPositional) - /// .arg(Arg::with_name("foo")) - /// .arg(Arg::with_name("bar")) - /// .arg(Arg::with_name("baz").multiple(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 notice if we don't specify `foo` or `baz` but use the `--` operator. - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = App::new("myprog") - /// .setting(AppSettings::AllowMissingPositional) - /// .arg(Arg::with_name("foo")) - /// .arg(Arg::with_name("bar")) - /// .arg(Arg::with_name("baz").multiple(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]: ./struct.Arg.html#method.required - AllowMissingPositional, - - /// Specifies that an unexpected positional argument, - /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error, - /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct. - /// - /// **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. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = App::new("myprog") - /// .setting(AppSettings::AllowExternalSubcommands) - /// .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() { - /// (external, Some(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"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`ArgMatches`]: ./struct.ArgMatches.html - AllowExternalSubcommands, - - /// Specifies that use of a valid [argument] negates [subcommands] being used after. By default - /// `clap` allows arguments between subcommands such as - /// ` [cmd_args] [cmd2_args] [cmd3_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: - /// - /// * ` [cmd3_args]` - /// * ` [cmd2_args]` - /// * ` [cmd_args]` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ArgsNegateSubcommands) - /// # ; - /// ``` - /// [subcommands]: ./struct.SubCommand.html - /// [argument]: ./struct.Arg.html - ArgsNegateSubcommands, - - /// Specifies that the help text should be displayed (and then exit gracefully), - /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`. - /// - /// **NOTE:** [`SubCommand`]s count as arguments - /// - /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will - /// ensure that some argument is always present. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ArgRequiredElseHelp) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - ArgRequiredElseHelp, - - /// Uses colorized help messages. - /// - /// **NOTE:** Must be compiled with the `color` cargo feature - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ColoredHelp) - /// .get_matches(); - /// ``` - ColoredHelp, - - /// Enables colored output only when the output is going to a terminal or TTY. - /// - /// **NOTE:** This is the default behavior of `clap`. - /// - /// **NOTE:** Must be compiled with the `color` cargo feature. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ColorAuto) - /// .get_matches(); - /// ``` - ColorAuto, - - /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. - /// - /// **NOTE:** Must be compiled with the `color` cargo feature. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ColorAlways) - /// .get_matches(); - /// ``` - ColorAlways, - - /// Disables colored output no matter if the output is going to a terminal/TTY, or not. - /// - /// **NOTE:** Must be compiled with the `color` cargo feature - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::ColorNever) - /// .get_matches(); - /// ``` - ColorNever, - - /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::DontCollapseArgsInUsage) - /// .get_matches(); - /// ``` - DontCollapseArgsInUsage, - - /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`] - /// was used. - /// - /// **NOTE:** The same thing can be done manually by setting the final positional argument to - /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate - /// when making changes. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::DontDelimitTrailingValues) - /// .get_matches(); - /// ``` - /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg - /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter - DontDelimitTrailingValues, - - /// Disables `-h` and `--help` [`App`] without affecting any of the [`SubCommand`]s - /// (Defaults to `false`; application *does* have help flags) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings, ErrorKind}; - /// let res = App::new("myprog") - /// .setting(AppSettings::DisableHelpFlags) - /// .get_matches_from_safe(vec![ - /// "myprog", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// - /// ```rust - /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; - /// let res = App::new("myprog") - /// .setting(AppSettings::DisableHelpFlags) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", "test", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - DisableHelpFlags, - - /// Disables the `help` subcommand - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings, ErrorKind, SubCommand}; - /// let res = App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::DisableHelpSubcommand) - /// // Normally, creating a subcommand causes a `help` subcommand to automatically - /// // be generated as well - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", "help" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - DisableHelpSubcommand, - - /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s - /// (Defaults to `false`; application *does* have a version flag) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings, ErrorKind}; - /// let res = App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::DisableVersion) - /// .get_matches_from_safe(vec![ - /// "myprog", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// - /// ```rust - /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; - /// let res = App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::DisableVersion) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", "test", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - DisableVersion, - - /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were - /// declared in, and not alphabetically which is the default. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::DeriveDisplayOrder) - /// .get_matches(); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - DeriveDisplayOrder, - - /// Specifies to use the version of the current command for all child [`SubCommand`]s. - /// (Defaults to `false`; subcommands have independent version strings from their parents.) - /// - /// **NOTE:** The version for the current command **and** this setting must be set **prior** to - /// adding any child subcommands - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::GlobalVersion) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches(); - /// // running `$ myprog test --version` will display - /// // "myprog-test v1.1" - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - GlobalVersion, - - /// Specifies that this [`SubCommand`] should be hidden from help messages - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings, SubCommand}; - /// App::new("myprog") - /// .subcommand(SubCommand::with_name("test") - /// .setting(AppSettings::Hidden)) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - Hidden, - - /// 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. - HidePossibleValuesInHelp, - - /// Tries to match unknown args to partial [`subcommands`] or 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 [`AppSeettings::ArgsNegateSubcommands`] in - /// conjunction with this setting. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// let m = App::new("prog") - /// .setting(AppSettings::InferSubcommands) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from(vec![ - /// "prog", "te" - /// ]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`subcommands`]: ./struct.SubCommand.html - /// [positional/free arguments]: ./struct.Arg.html#method.index - /// [aliases]: ./struct.App.html#method.alias - /// [`AppSeettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands - InferSubcommands, - - /// 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, or an interactive CLI where one - /// one would not normally type the binary or program name for each command. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// let m = App::new("myprog") - /// .setting(AppSettings::NoBinaryName) - /// .arg(Arg::from_usage("... 'commands to run'")) - /// .get_matches_from(vec!["command", "set"]); - /// - /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); - /// assert_eq!(cmds, ["command", "set"]); - /// ``` - NoBinaryName, - - /// Places the help string for all arguments on the line after the argument. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::NextLineHelp) - /// .get_matches(); - /// ``` - NextLineHelp, - - /// **DEPRECATED**: This setting is no longer required in order to propagate values up or down - /// - /// Specifies that the parser should propagate global arg's values down or up through any *used* - /// child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to - /// said subcommand. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings, SubCommand}; - /// let m = App::new("myprog") - /// .arg(Arg::from_usage("[cmd] 'command to run'") - /// .global(true)) - /// .subcommand(SubCommand::with_name("foo")) - /// .get_matches_from(vec!["myprog", "set", "foo"]); - /// - /// assert_eq!(m.value_of("cmd"), Some("set")); - /// - /// let sub_m = m.subcommand_matches("foo").unwrap(); - /// assert_eq!(sub_m.value_of("cmd"), Some("set")); - /// ``` - /// Now doing the same thing, but *not* using any subcommands will result in the value not being - /// propagated down. - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings, SubCommand}; - /// let m = App::new("myprog") - /// .arg(Arg::from_usage("[cmd] 'command to run'") - /// .global(true)) - /// .subcommand(SubCommand::with_name("foo")) - /// .get_matches_from(vec!["myprog", "set"]); - /// - /// assert_eq!(m.value_of("cmd"), Some("set")); - /// - /// assert!(m.subcommand_matches("foo").is_none()); - /// ``` - #[deprecated(since = "2.27.0", note = "No longer required to propagate values")] - PropagateGlobalValuesDown, - - /// Allows [`SubCommand`]s 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::{App, Arg, AppSettings, SubCommand, ErrorKind}; - /// let err = App::new("myprog") - /// .setting(AppSettings::SubcommandsNegateReqs) - /// .arg(Arg::with_name("opt").required(true)) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(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::{App, Arg, AppSettings, SubCommand, ErrorKind}; - /// let noerr = App::new("myprog") - /// .setting(AppSettings::SubcommandsNegateReqs) - /// .arg(Arg::with_name("opt").required(true)) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", "test" - /// ]); - /// assert!(noerr.is_ok()); - /// # ; - /// ``` - /// [`Arg::required(true)`]: ./struct.Arg.html#method.required - /// [`SubCommand`]: ./struct.SubCommand.html - SubcommandsNegateReqs, - - /// Specifies that the help text should be displayed (before exiting gracefully) if no - /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`). - /// - /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do - /// nearly same thing; this prints the help text, and the other prints an error. - /// - /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will - /// still be displayed and exit. If this is *not* the desired result, consider using - /// [`AppSettings::ArgRequiredElseHelp`] instead. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::SubcommandRequiredElseHelp) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired - /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp - SubcommandRequiredElseHelp, - - /// Specifies that any invalid UTF-8 code points should be treated as an error and fail - /// with a [`ErrorKind::InvalidUtf8`] error. - /// - /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and - /// [`SubCommand`]s themselves only allow valid UTF-8 code points. - /// - /// # Platform Specific - /// - /// Non Windows systems only - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, AppSettings, ErrorKind}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::OsStringExt; - /// - /// let m = App::new("myprog") - /// .setting(AppSettings::StrictUtf8) - /// .arg_from_usage(" 'some positional arg'") - /// .get_matches_from_safe( - /// vec![ - /// OsString::from("myprog"), - /// OsString::from_vec(vec![0xe9])]); - /// - /// assert!(m.is_err()); - /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8 - StrictUtf8, - - /// Allows specifying that if no [`SubCommand`] is present at runtime, - /// error and exit gracefully. - /// - /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings, SubCommand, ErrorKind}; - /// let err = App::new("myprog") - /// .setting(AppSettings::SubcommandRequired) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - SubcommandRequired, - - /// 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(true)`] or the usage - /// string equivalent. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// let m = App::new("myprog") - /// .setting(AppSettings::TrailingVarArg) - /// .arg(Arg::from_usage("... '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(true)`]: ./struct.Arg.html#method.multiple - TrailingVarArg, - - /// Groups flags and options together, presenting a more unified help message - /// (a la `getopts` or `docopt` style). - /// - /// The default is that the auto-generated help message will group flags, and options - /// separately. - /// - /// **NOTE:** This setting is cosmetic only and does not affect any functionality. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::UnifiedHelpMessage) - /// .get_matches(); - /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message - /// ``` - UnifiedHelpMessage, - - /// Disables `-V` and `--version` for all [`SubCommand`]s - /// (Defaults to `false`; subcommands *do* have version flags.) - /// - /// **NOTE:** This setting must be set **prior** to adding any subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; - /// let res = App::new("myprog") - /// .version("v1.1") - /// .setting(AppSettings::VersionlessSubcommands) - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches_from_safe(vec![ - /// "myprog", "test", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - VersionlessSubcommands, - - /// Will display a message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before - /// exiting - /// - /// This is most useful when writing an application which is run from a GUI shortcut, or on - /// Windows where a user tries to open the binary by double-clicking instead of using the - /// command line. - /// - /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this - /// behavior for all subcommands, you must set this on each command (needing this is extremely - /// rare) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings}; - /// App::new("myprog") - /// .setting(AppSettings::WaitOnError) - /// # ; - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - WaitOnError, - - #[doc(hidden)] - NeedsLongVersion, - - #[doc(hidden)] - NeedsLongHelp, - - #[doc(hidden)] - NeedsSubcommandHelp, - - #[doc(hidden)] - LowIndexMultiplePositional, - - #[doc(hidden)] - TrailingValues, - - #[doc(hidden)] - ValidNegNumFound, - - #[doc(hidden)] - Propagated, - - #[doc(hidden)] - ValidArgFound, - - #[doc(hidden)] - ContainsLast, -} - -impl FromStr for AppSettings { - type Err = String; - fn from_str(s: &str) -> Result::Err> { - match &*s.to_ascii_lowercase() { - "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), - "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), - "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), - "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8), - "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), - "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), - "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), - "colorauto" => Ok(AppSettings::ColorAuto), - "coloralways" => Ok(AppSettings::ColorAlways), - "colornever" => Ok(AppSettings::ColorNever), - "coloredhelp" => Ok(AppSettings::ColoredHelp), - "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), - "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), - "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), - "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), - "disableversion" => Ok(AppSettings::DisableVersion), - "globalversion" => Ok(AppSettings::GlobalVersion), - "hidden" => Ok(AppSettings::Hidden), - "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), - "infersubcommands" => Ok(AppSettings::InferSubcommands), - "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional), - "nobinaryname" => Ok(AppSettings::NoBinaryName), - "nextlinehelp" => Ok(AppSettings::NextLineHelp), - "strictutf8" => Ok(AppSettings::StrictUtf8), - "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), - "subcommandrequired" => Ok(AppSettings::SubcommandRequired), - "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), - "trailingvararg" => Ok(AppSettings::TrailingVarArg), - "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), - "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands), - "waitonerror" => Ok(AppSettings::WaitOnError), - "validnegnumfound" => Ok(AppSettings::ValidNegNumFound), - "validargfound" => Ok(AppSettings::ValidArgFound), - "propagated" => Ok(AppSettings::Propagated), - "trailingvalues" => Ok(AppSettings::TrailingValues), - _ => Err("unknown AppSetting, cannot convert from str".to_owned()), - } - } -} - -#[cfg(test)] -mod test { - use super::AppSettings; - - #[test] - fn app_settings_fromstr() { - assert_eq!( - "disablehelpflags".parse::().unwrap(), - AppSettings::DisableHelpFlags - ); - assert_eq!( - "argsnegatesubcommands".parse::().unwrap(), - AppSettings::ArgsNegateSubcommands - ); - assert_eq!( - "argrequiredelsehelp".parse::().unwrap(), - AppSettings::ArgRequiredElseHelp - ); - assert_eq!( - "allowexternalsubcommands".parse::().unwrap(), - AppSettings::AllowExternalSubcommands - ); - assert_eq!( - "allowinvalidutf8".parse::().unwrap(), - AppSettings::AllowInvalidUtf8 - ); - assert_eq!( - "allowleadinghyphen".parse::().unwrap(), - AppSettings::AllowLeadingHyphen - ); - assert_eq!( - "allownegativenumbers".parse::().unwrap(), - AppSettings::AllowNegativeNumbers - ); - assert_eq!( - "coloredhelp".parse::().unwrap(), - AppSettings::ColoredHelp - ); - assert_eq!( - "colorauto".parse::().unwrap(), - AppSettings::ColorAuto - ); - assert_eq!( - "coloralways".parse::().unwrap(), - AppSettings::ColorAlways - ); - assert_eq!( - "colornever".parse::().unwrap(), - AppSettings::ColorNever - ); - assert_eq!( - "disablehelpsubcommand".parse::().unwrap(), - AppSettings::DisableHelpSubcommand - ); - assert_eq!( - "disableversion".parse::().unwrap(), - AppSettings::DisableVersion - ); - assert_eq!( - "dontcollapseargsinusage".parse::().unwrap(), - AppSettings::DontCollapseArgsInUsage - ); - assert_eq!( - "dontdelimittrailingvalues".parse::().unwrap(), - AppSettings::DontDelimitTrailingValues - ); - assert_eq!( - "derivedisplayorder".parse::().unwrap(), - AppSettings::DeriveDisplayOrder - ); - assert_eq!( - "globalversion".parse::().unwrap(), - AppSettings::GlobalVersion - ); - assert_eq!( - "hidden".parse::().unwrap(), - AppSettings::Hidden - ); - assert_eq!( - "hidepossiblevaluesinhelp".parse::().unwrap(), - AppSettings::HidePossibleValuesInHelp - ); - assert_eq!( - "lowindexmultiplePositional".parse::().unwrap(), - AppSettings::LowIndexMultiplePositional - ); - 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!( - "strictutf8".parse::().unwrap(), - AppSettings::StrictUtf8 - ); - assert_eq!( - "trailingvararg".parse::().unwrap(), - AppSettings::TrailingVarArg - ); - assert_eq!( - "unifiedhelpmessage".parse::().unwrap(), - AppSettings::UnifiedHelpMessage - ); - assert_eq!( - "versionlesssubcommands".parse::().unwrap(), - AppSettings::VersionlessSubcommands - ); - assert_eq!( - "waitonerror".parse::().unwrap(), - AppSettings::WaitOnError - ); - assert_eq!( - "validnegnumfound".parse::().unwrap(), - AppSettings::ValidNegNumFound - ); - assert_eq!( - "validargfound".parse::().unwrap(), - AppSettings::ValidArgFound - ); - assert_eq!( - "propagated".parse::().unwrap(), - AppSettings::Propagated - ); - assert_eq!( - "trailingvalues".parse::().unwrap(), - AppSettings::TrailingValues - ); - assert_eq!( - "infersubcommands".parse::().unwrap(), - AppSettings::InferSubcommands - ); - assert!("hahahaha".parse::().is_err()); - } -} diff --git a/third_party/rust/clap/src/app/usage.rs b/third_party/rust/clap/src/app/usage.rs deleted file mode 100644 index e68f2f4b1149..000000000000 --- a/third_party/rust/clap/src/app/usage.rs +++ /dev/null @@ -1,493 +0,0 @@ -// std -use std::collections::{BTreeMap, VecDeque}; - -// Internal -use crate::{ - app::{parser::Parser, settings::AppSettings as AS}, - args::{settings::ArgSettings, AnyArg, ArgMatcher, PosBuilder}, - INTERNAL_ERROR_MSG, -}; - -// 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 fn create_usage_with_title(p: &Parser, used: &[&str]) -> String { - debugln!("usage::create_usage_with_title;"); - let mut usage = String::with_capacity(75); - usage.push_str("USAGE:\n "); - usage.push_str(&*create_usage_no_title(p, used)); - usage -} - -// Creates a usage string to be used in error message (i.e. one with currently used args) -pub fn create_error_usage<'a, 'b>( - p: &Parser<'a, 'b>, - matcher: &'b ArgMatcher<'a>, - extra: Option<&str>, -) -> String { - let mut args: Vec<_> = matcher - .arg_names() - .iter() - .filter(|n| { - if let Some(o) = find_by_name!(p, **n, opts, iter) { - !o.b.is_set(ArgSettings::Required) && !o.b.is_set(ArgSettings::Hidden) - } else if let Some(p) = find_by_name!(p, **n, positionals, values) { - !p.b.is_set(ArgSettings::Required) && p.b.is_set(ArgSettings::Hidden) - } else { - true // flags can't be required, so they're always true - } - }) - .copied() - .collect(); - if let Some(r) = extra { - args.push(r); - } - create_usage_with_title(p, &*args) -} - -// Creates a usage string (*without title*) if one was not provided by the user manually. -pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String { - debugln!("usage::create_usage_no_title;"); - if let Some(u) = p.meta.usage_str { - String::from(&*u) - } else if used.is_empty() { - create_help_usage(p, true) - } else { - create_smart_usage(p, used) - } -} - -// Creates a usage string for display in help messages (i.e. not for errors) -pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { - let mut usage = String::with_capacity(75); - let name = p - .meta - .usage - .as_ref() - .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name)); - usage.push_str(&*name); - let req_string = if incl_reqs { - let mut reqs: Vec<&str> = p.required().map(|r| &**r).collect(); - reqs.sort_unstable(); - reqs.dedup(); - get_required_usage_from(p, &reqs, None, None, false) - .iter() - .fold(String::new(), |a, s| a + &format!(" {}", s)[..]) - } else { - String::new() - }; - - let flags = needs_flags_tag(p); - if flags && !p.is_set(AS::UnifiedHelpMessage) { - usage.push_str(" [FLAGS]"); - } else if flags { - usage.push_str(" [OPTIONS]"); - } - if !p.is_set(AS::UnifiedHelpMessage) - && p.opts - .iter() - .any(|o| !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden)) - { - usage.push_str(" [OPTIONS]"); - } - - usage.push_str(&req_string[..]); - - let has_last = p.positionals.values().any(|p| p.is_set(ArgSettings::Last)); - // places a '--' in the usage string if there are args and options - // supporting multiple values - if p.opts.iter().any(|o| o.is_set(ArgSettings::Multiple)) - && p.positionals - .values() - .any(|p| !p.is_set(ArgSettings::Required)) - && !(p.has_visible_subcommands() || p.is_set(AS::AllowExternalSubcommands)) - && !has_last - { - usage.push_str(" [--]"); - } - let not_req_or_hidden = |p: &PosBuilder| { - (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last)) - && !p.is_set(ArgSettings::Hidden) - }; - if p.has_positionals() && p.positionals.values().any(not_req_or_hidden) { - if let Some(args_tag) = get_args_tag(p, incl_reqs) { - usage.push_str(&*args_tag); - } else { - usage.push_str(" [ARGS]"); - } - if has_last && incl_reqs { - let pos = p - .positionals - .values() - .find(|p| p.b.is_set(ArgSettings::Last)) - .expect(INTERNAL_ERROR_MSG); - debugln!("usage::create_help_usage: '{}' has .last(true)", pos.name()); - let req = pos.is_set(ArgSettings::Required); - if req - && p.positionals - .values() - .any(|p| !p.is_set(ArgSettings::Required)) - { - 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(']'); - } - } - } - - // incl_reqs is only false when this function is called recursively - if p.has_visible_subcommands() && incl_reqs || p.is_set(AS::AllowExternalSubcommands) { - if p.is_set(AS::SubcommandsNegateReqs) || p.is_set(AS::ArgsNegateSubcommands) { - usage.push_str("\n "); - if !p.is_set(AS::ArgsNegateSubcommands) { - usage.push_str(&*create_help_usage(p, false)); - } else { - usage.push_str(&*name); - } - usage.push_str(" "); - } else if p.is_set(AS::SubcommandRequired) || p.is_set(AS::SubcommandRequiredElseHelp) { - usage.push_str(" "); - } else { - usage.push_str(" [SUBCOMMAND]"); - } - } - usage.shrink_to_fit(); - debugln!("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(p: &Parser, used: &[&str]) -> String { - debugln!("usage::smart_usage;"); - let mut usage = String::with_capacity(75); - let mut hs: Vec<&str> = p.required().map(|s| &**s).collect(); - hs.extend_from_slice(used); - - let r_string = get_required_usage_from(p, &hs, None, None, false) - .iter() - .fold(String::new(), |acc, s| acc + &format!(" {}", s)[..]); - - usage.push_str( - &p.meta - .usage - .as_ref() - .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name))[..], - ); - usage.push_str(&*r_string); - if p.is_set(AS::SubcommandRequired) { - usage.push_str(" "); - } - usage.shrink_to_fit(); - usage -} - -// Gets the `[ARGS]` tag for the usage string -fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { - debugln!("usage::get_args_tag;"); - let mut count = 0; - 'outer: for pos in p - .positionals - .values() - .filter(|pos| !pos.is_set(ArgSettings::Required)) - .filter(|pos| !pos.is_set(ArgSettings::Hidden)) - .filter(|pos| !pos.is_set(ArgSettings::Last)) - { - debugln!("usage::get_args_tag:iter:{}:", pos.b.name); - if let Some(g_vec) = p.groups_for_arg(pos.b.name) { - for grp_s in &g_vec { - debugln!("usage::get_args_tag:iter:{}:iter:{};", pos.b.name, grp_s); - // if it's part of a required group we don't want to count it - if p.groups.iter().any(|g| g.required && (&g.name == grp_s)) { - continue 'outer; - } - } - } - count += 1; - debugln!( - "usage::get_args_tag:iter: {} Args not required or hidden", - count - ); - } - if !p.is_set(AS::DontCollapseArgsInUsage) && count > 1 { - debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]"); - return None; // [ARGS] - } else if count == 1 && incl_reqs { - let pos = p - .positionals - .values() - .find(|pos| { - !pos.is_set(ArgSettings::Required) - && !pos.is_set(ArgSettings::Hidden) - && !pos.is_set(ArgSettings::Last) - }) - .expect(INTERNAL_ERROR_MSG); - debugln!( - "usage::get_args_tag:iter: Exactly one, returning '{}'", - pos.name() - ); - return Some(format!( - " [{}]{}", - pos.name_no_brackets(), - pos.multiple_str() - )); - } else if p.is_set(AS::DontCollapseArgsInUsage) && !p.positionals.is_empty() && incl_reqs { - debugln!("usage::get_args_tag:iter: Don't collapse returning all"); - return Some( - p.positionals - .values() - .filter(|pos| !pos.is_set(ArgSettings::Required)) - .filter(|pos| !pos.is_set(ArgSettings::Hidden)) - .filter(|pos| !pos.is_set(ArgSettings::Last)) - .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) - .collect::>() - .join(""), - ); - } else if !incl_reqs { - debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); - let highest_req_pos = p - .positionals - .iter() - .filter_map(|(idx, pos)| { - if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) { - Some(idx) - } else { - None - } - }) - .max() - .unwrap_or_else(|| p.positionals.len()); - return Some( - p.positionals - .iter() - .filter_map(|(idx, pos)| { - if idx <= highest_req_pos { - Some(pos) - } else { - None - } - }) - .filter(|pos| !pos.is_set(ArgSettings::Required)) - .filter(|pos| !pos.is_set(ArgSettings::Hidden)) - .filter(|pos| !pos.is_set(ArgSettings::Last)) - .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) - .collect::>() - .join(""), - ); - } - Some("".into()) -} - -// Determines if we need the `[FLAGS]` tag in the usage string -fn needs_flags_tag(p: &Parser) -> bool { - debugln!("usage::needs_flags_tag;"); - 'outer: for f in &p.flags { - debugln!("usage::needs_flags_tag:iter: f={};", f.b.name); - if let Some(l) = f.s.long { - if l == "help" || l == "version" { - // Don't print `[FLAGS]` just for help or version - continue; - } - } - if let Some(g_vec) = p.groups_for_arg(f.b.name) { - for grp_s in &g_vec { - debugln!("usage::needs_flags_tag:iter:iter: grp_s={};", grp_s); - if p.groups.iter().any(|g| &g.name == grp_s && g.required) { - debugln!("usage::needs_flags_tag:iter:iter: Group is required"); - continue 'outer; - } - } - } - if f.is_set(ArgSettings::Hidden) { - continue; - } - debugln!("usage::needs_flags_tag:iter: [FLAGS] required"); - return true; - } - - debugln!("usage::needs_flags_tag: [FLAGS] not required"); - false -} - -// Returns the required args in usage string form by fully unrolling all groups -pub fn get_required_usage_from<'a, 'b>( - p: &Parser<'a, 'b>, - reqs: &[&'a str], - matcher: Option<&ArgMatcher<'a>>, - extra: Option<&str>, - incl_last: bool, -) -> VecDeque { - debugln!( - "usage::get_required_usage_from: reqs={:?}, extra={:?}", - reqs, - extra - ); - let mut desc_reqs: Vec<&str> = vec![]; - desc_reqs.extend(extra); - let mut new_reqs: Vec<&str> = vec![]; - macro_rules! get_requires { - (@group $a: ident, $v:ident, $p:ident) => {{ - if let Some(rl) = p - .groups - .iter() - .filter(|g| g.requires.is_some()) - .find(|g| &g.name == $a) - .map(|g| g.requires.as_ref().unwrap()) - { - for r in rl { - if !$p.contains(&r) { - debugln!( - "usage::get_required_usage_from:iter:{}: adding group req={:?}", - $a, - r - ); - $v.push(r); - } - } - } - }}; - ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{ - if let Some(rl) = p - .$what - .$how() - .filter(|a| a.b.requires.is_some()) - .find(|arg| &arg.b.name == $a) - .map(|a| a.b.requires.as_ref().unwrap()) - { - for &(_, r) in rl.iter() { - if !$p.contains(&r) { - debugln!( - "usage::get_required_usage_from:iter:{}: adding arg req={:?}", - $a, - r - ); - $v.push(r); - } - } - } - }}; - } - // initialize new_reqs - for a in reqs { - get_requires!(a, flags, iter, new_reqs, reqs); - get_requires!(a, opts, iter, new_reqs, reqs); - get_requires!(a, positionals, values, new_reqs, reqs); - get_requires!(@group a, new_reqs, reqs); - } - desc_reqs.extend_from_slice(&*new_reqs); - debugln!( - "usage::get_required_usage_from: after init desc_reqs={:?}", - desc_reqs - ); - loop { - let mut tmp = vec![]; - for a in &new_reqs { - get_requires!(a, flags, iter, tmp, desc_reqs); - get_requires!(a, opts, iter, tmp, desc_reqs); - get_requires!(a, positionals, values, tmp, desc_reqs); - get_requires!(@group a, tmp, desc_reqs); - } - if tmp.is_empty() { - debugln!("usage::get_required_usage_from: no more children"); - break; - } else { - debugln!("usage::get_required_usage_from: after iter tmp={:?}", tmp); - debugln!( - "usage::get_required_usage_from: after iter new_reqs={:?}", - new_reqs - ); - desc_reqs.extend_from_slice(&*new_reqs); - new_reqs.clear(); - new_reqs.extend_from_slice(&*tmp); - debugln!( - "usage::get_required_usage_from: after iter desc_reqs={:?}", - desc_reqs - ); - } - } - desc_reqs.extend_from_slice(reqs); - desc_reqs.sort_unstable(); - desc_reqs.dedup(); - debugln!( - "usage::get_required_usage_from: final desc_reqs={:?}", - desc_reqs - ); - let mut ret_val = VecDeque::new(); - let args_in_groups = p - .groups - .iter() - .filter(|gn| desc_reqs.contains(&gn.name)) - .flat_map(|g| p.arg_names_in_group(g.name)) - .collect::>(); - - let pmap = if let Some(m) = matcher { - desc_reqs - .iter() - .filter(|a| p.positionals.values().any(|p| &&p.b.name == a)) - .filter(|&pos| !m.contains(pos)) - .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) - .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) - .filter(|pos| !args_in_groups.contains(&pos.b.name)) - .map(|pos| (pos.index, pos)) - .collect::>() // sort by index - } else { - desc_reqs - .iter() - .filter(|a| p.positionals.values().any(|pos| &&pos.b.name == a)) - .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) - .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) - .filter(|pos| !args_in_groups.contains(&pos.b.name)) - .map(|pos| (pos.index, pos)) - .collect::>() // sort by index - }; - debugln!( - "usage::get_required_usage_from: args_in_groups={:?}", - args_in_groups - ); - for &p in pmap.values() { - let s = p.to_string(); - if args_in_groups.is_empty() || !args_in_groups.contains(&&*s) { - ret_val.push_back(s); - } - } - for a in desc_reqs - .iter() - .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name)) - .filter(|name| !p.groups.iter().any(|g| &&g.name == name)) - .filter(|name| !args_in_groups.contains(name)) - .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name))) - { - debugln!("usage::get_required_usage_from:iter:{}:", a); - let arg = find_by_name!(p, *a, flags, iter) - .map(|f| f.to_string()) - .unwrap_or_else(|| { - find_by_name!(p, *a, opts, iter) - .map(|o| o.to_string()) - .expect(INTERNAL_ERROR_MSG) - }); - ret_val.push_back(arg); - } - let mut g_vec: Vec = vec![]; - for g in desc_reqs - .iter() - .filter(|n| p.groups.iter().any(|g| &&g.name == n)) - { - let g_string = p.args_in_group(g).join("|"); - let elem = format!("<{}>", &g_string[..g_string.len()]); - if !g_vec.contains(&elem) { - g_vec.push(elem); - } - } - for g in g_vec { - ret_val.push_back(g); - } - - ret_val -} diff --git a/third_party/rust/clap/src/app/validator.rs b/third_party/rust/clap/src/app/validator.rs deleted file mode 100644 index 1deb67d860b7..000000000000 --- a/third_party/rust/clap/src/app/validator.rs +++ /dev/null @@ -1,584 +0,0 @@ -// std -#[allow(deprecated, unused_imports)] -use std::{ascii::AsciiExt, fmt::Display}; - -// Internal -use crate::{ - app::{ - parser::{ParseResult, Parser}, - settings::AppSettings as AS, - usage, - }, - args::{settings::ArgSettings, AnyArg, ArgMatcher, MatchedArg}, - errors::{Error, ErrorKind, Result as ClapResult}, - fmt::{Colorizer, ColorizerOption}, - INTERNAL_ERROR_MSG, INVALID_UTF8, -}; - -pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>) -where - 'a: 'b, - 'b: 'z; - -impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { - pub fn new(p: &'z mut Parser<'a, 'b>) -> Self { - Validator(p) - } - - pub fn validate( - &mut self, - needs_val_of: ParseResult<'a>, - subcmd_name: Option, - matcher: &mut ArgMatcher<'a>, - ) -> ClapResult<()> { - debugln!("Validator::validate;"); - let mut reqs_validated = false; - self.0.add_env(matcher)?; - self.0.add_defaults(matcher)?; - if let ParseResult::Opt(a) = needs_val_of { - debugln!("Validator::validate: needs_val_of={:?}", a); - let o = { - self.0 - .opts - .iter() - .find(|o| o.b.name == a) - .expect(INTERNAL_ERROR_MSG) - .clone() - }; - self.validate_required(matcher)?; - reqs_validated = true; - let should_err = if let Some(v) = matcher.0.args.get(&*o.b.name) { - v.vals.is_empty() && !(o.v.min_vals.is_some() && o.v.min_vals.unwrap() == 0) - } else { - true - }; - if should_err { - return Err(Error::empty_value( - &o, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - } - - if matcher.is_empty() - && matcher.subcommand_name().is_none() - && self.0.is_set(AS::ArgRequiredElseHelp) - { - let mut out = vec![]; - self.0.write_help_err(&mut out)?; - return Err(Error { - message: String::from_utf8_lossy(&*out).into_owned(), - kind: ErrorKind::MissingArgumentOrSubcommand, - info: None, - }); - } - self.validate_blacklist(matcher)?; - if !(reqs_validated || self.0.is_set(AS::SubcommandsNegateReqs) && subcmd_name.is_some()) { - self.validate_required(matcher)?; - } - self.validate_matched_args(matcher)?; - matcher.usage(usage::create_usage_with_title(self.0, &[])); - - Ok(()) - } - - fn validate_arg_values( - &self, - arg: &A, - ma: &MatchedArg, - matcher: &ArgMatcher<'a>, - ) -> ClapResult<()> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Validator::validate_arg_values: arg={:?}", arg.name()); - for val in &ma.vals { - if self.0.is_set(AS::StrictUtf8) && val.to_str().is_none() { - debugln!( - "Validator::validate_arg_values: invalid UTF-8 found in val {:?}", - val - ); - return Err(Error::invalid_utf8( - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - if let Some(p_vals) = arg.possible_vals() { - debugln!("Validator::validate_arg_values: possible_vals={:?}", p_vals); - let val_str = val.to_string_lossy(); - let ok = if arg.is_set(ArgSettings::CaseInsensitive) { - p_vals.iter().any(|pv| pv.eq_ignore_ascii_case(&*val_str)) - } else { - p_vals.contains(&&*val_str) - }; - if !ok { - return Err(Error::invalid_value( - val_str, - p_vals, - arg, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - } - if !arg.is_set(ArgSettings::EmptyValues) - && val.is_empty() - && matcher.contains(&*arg.name()) - { - debugln!("Validator::validate_arg_values: illegal empty val found"); - return Err(Error::empty_value( - arg, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - if let Some(vtor) = arg.validator() { - debug!("Validator::validate_arg_values: checking validator..."); - if let Err(e) = vtor(val.to_string_lossy().into_owned()) { - sdebugln!("error"); - return Err(Error::value_validation(Some(arg), e, self.0.color())); - } else { - sdebugln!("good"); - } - } - if let Some(vtor) = arg.validator_os() { - debug!("Validator::validate_arg_values: checking validator_os..."); - if let Err(e) = vtor(val) { - sdebugln!("error"); - return Err(Error::value_validation( - Some(arg), - (*e).to_string_lossy().to_string(), - self.0.color(), - )); - } else { - sdebugln!("good"); - } - } - } - Ok(()) - } - - fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> { - debugln!("build_err!: name={}", name); - let mut c_with = find_from!(self.0, &name, blacklist, matcher); - c_with = c_with.or_else(|| { - self.0 - .find_any_arg(name) - .and_then(|aa| aa.blacklist()) - .and_then(|bl| bl.iter().find(|arg| matcher.contains(arg))) - .and_then(|an| self.0.find_any_arg(an)) - .map(|aa| format!("{}", aa)) - }); - debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name); - // matcher.remove(&name); - let usg = usage::create_error_usage(self.0, matcher, None); - if let Some(f) = find_by_name!(self.0, name, flags, iter) { - debugln!("build_err!: It was a flag..."); - Err(Error::argument_conflict(f, c_with, &*usg, self.0.color())) - } else if let Some(o) = find_by_name!(self.0, name, opts, iter) { - debugln!("build_err!: It was an option..."); - Err(Error::argument_conflict(o, c_with, &*usg, self.0.color())) - } else { - match find_by_name!(self.0, name, positionals, values) { - Some(p) => { - debugln!("build_err!: It was a positional..."); - Err(Error::argument_conflict(p, c_with, &*usg, self.0.color())) - } - None => panic!("{}", INTERNAL_ERROR_MSG), - } - } - } - - fn validate_blacklist(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { - debugln!("Validator::validate_blacklist;"); - let mut conflicts: Vec<&str> = vec![]; - for (&name, _) in matcher.iter() { - debugln!("Validator::validate_blacklist:iter:{};", name); - if let Some(grps) = self.0.groups_for_arg(name) { - for grp in &grps { - if let Some(g) = self.0.groups.iter().find(|g| &g.name == grp) { - if !g.multiple { - for arg in &g.args { - if arg == &name { - continue; - } - conflicts.push(arg); - } - } - if let Some(ref gc) = g.conflicts { - conflicts.extend(&*gc); - } - } - } - } - if let Some(arg) = find_any_by_name!(self.0, name) { - if let Some(bl) = arg.blacklist() { - for conf in bl { - if matcher.get(conf).is_some() { - conflicts.push(conf); - } - } - } - } else { - debugln!("Validator::validate_blacklist:iter:{}:group;", name); - let args = self.0.arg_names_in_group(name); - for arg in &args { - debugln!( - "Validator::validate_blacklist:iter:{}:group:iter:{};", - name, - arg - ); - if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() { - for conf in bl { - if matcher.get(conf).is_some() { - conflicts.push(conf); - } - } - } - } - } - } - - for name in &conflicts { - debugln!( - "Validator::validate_blacklist:iter:{}: Checking blacklisted arg", - name - ); - let mut should_err = false; - if self.0.groups.iter().any(|g| &g.name == name) { - debugln!( - "Validator::validate_blacklist:iter:{}: groups contains it...", - name - ); - for n in self.0.arg_names_in_group(name) { - debugln!( - "Validator::validate_blacklist:iter:{}:iter:{}: looking in group...", - name, - n - ); - if matcher.contains(n) { - debugln!( - "Validator::validate_blacklist:iter:{}:iter:{}: matcher contains it...", - name, - n - ); - return self.build_err(n, matcher); - } - } - } else if let Some(ma) = matcher.get(name) { - debugln!( - "Validator::validate_blacklist:iter:{}: matcher contains it...", - name - ); - should_err = ma.occurs > 0; - } - if should_err { - return self.build_err(*name, matcher); - } - } - Ok(()) - } - - fn validate_matched_args(&self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { - debugln!("Validator::validate_matched_args;"); - for (name, ma) in matcher.iter() { - debugln!( - "Validator::validate_matched_args:iter:{}: vals={:#?}", - name, - ma.vals - ); - if let Some(opt) = find_by_name!(self.0, *name, opts, iter) { - self.validate_arg_num_vals(opt, ma, matcher)?; - self.validate_arg_values(opt, ma, matcher)?; - self.validate_arg_requires(opt, ma, matcher)?; - self.validate_arg_num_occurs(opt, ma, matcher)?; - } else if let Some(flag) = find_by_name!(self.0, *name, flags, iter) { - self.validate_arg_requires(flag, ma, matcher)?; - self.validate_arg_num_occurs(flag, ma, matcher)?; - } else if let Some(pos) = find_by_name!(self.0, *name, positionals, values) { - self.validate_arg_num_vals(pos, ma, matcher)?; - self.validate_arg_num_occurs(pos, ma, matcher)?; - self.validate_arg_values(pos, ma, matcher)?; - self.validate_arg_requires(pos, ma, matcher)?; - } else { - let grp = self - .0 - .groups - .iter() - .find(|g| &g.name == name) - .expect(INTERNAL_ERROR_MSG); - if let Some(ref g_reqs) = grp.requires { - if g_reqs.iter().any(|&n| !matcher.contains(n)) { - return self.missing_required_error(matcher, None); - } - } - } - } - Ok(()) - } - - fn validate_arg_num_occurs( - &self, - a: &A, - ma: &MatchedArg, - matcher: &ArgMatcher, - ) -> ClapResult<()> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Validator::validate_arg_num_occurs: a={};", a.name()); - if ma.occurs > 1 && !a.is_set(ArgSettings::Multiple) { - // Not the first time, and we don't allow multiples - return Err(Error::unexpected_multiple_usage( - a, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - Ok(()) - } - - fn validate_arg_num_vals( - &self, - a: &A, - ma: &MatchedArg, - matcher: &ArgMatcher, - ) -> ClapResult<()> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Validator::validate_arg_num_vals:{}", a.name()); - if let Some(num) = a.num_vals() { - debugln!("Validator::validate_arg_num_vals: num_vals set...{}", num); - let should_err = if a.is_set(ArgSettings::Multiple) { - ((ma.vals.len() as u64) % num) != 0 - } else { - num != (ma.vals.len() as u64) - }; - if should_err { - debugln!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); - return Err(Error::wrong_number_of_values( - a, - num, - if a.is_set(ArgSettings::Multiple) { - ma.vals.len() % num as usize - } else { - ma.vals.len() - }, - if ma.vals.len() == 1 - || (a.is_set(ArgSettings::Multiple) && (ma.vals.len() % num as usize) == 1) - { - "as" - } else { - "ere" - }, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - } - if let Some(num) = a.max_vals() { - debugln!("Validator::validate_arg_num_vals: max_vals set...{}", num); - if (ma.vals.len() as u64) > num { - debugln!("Validator::validate_arg_num_vals: Sending error TooManyValues"); - return Err(Error::too_many_values( - ma.vals - .iter() - .last() - .expect(INTERNAL_ERROR_MSG) - .to_str() - .expect(INVALID_UTF8), - a, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - } - let min_vals_zero = if let Some(num) = a.min_vals() { - debugln!("Validator::validate_arg_num_vals: min_vals set: {}", num); - if (ma.vals.len() as u64) < num && num != 0 { - debugln!("Validator::validate_arg_num_vals: Sending error TooFewValues"); - return Err(Error::too_few_values( - a, - num, - ma.vals.len(), - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - 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.takes_value() && !min_vals_zero && ma.vals.is_empty() { - return Err(Error::empty_value( - a, - &*usage::create_error_usage(self.0, matcher, None), - self.0.color(), - )); - } - Ok(()) - } - - fn validate_arg_requires( - &self, - a: &A, - ma: &MatchedArg, - matcher: &ArgMatcher, - ) -> ClapResult<()> - where - A: AnyArg<'a, 'b> + Display, - { - debugln!("Validator::validate_arg_requires:{};", a.name()); - if let Some(a_reqs) = a.requires() { - for &(val, name) in a_reqs.iter().filter(|&&(val, _)| val.is_some()) { - let missing_req = - |v| v == val.expect(INTERNAL_ERROR_MSG) && !matcher.contains(name); - if ma.vals.iter().any(missing_req) { - return self.missing_required_error(matcher, None); - } - } - for &(_, name) in a_reqs.iter().filter(|&&(val, _)| val.is_none()) { - if !matcher.contains(name) { - return self.missing_required_error(matcher, Some(name)); - } - } - } - Ok(()) - } - - fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> { - debugln!( - "Validator::validate_required: required={:?};", - self.0.required - ); - - let mut should_err = false; - let mut to_rem = Vec::new(); - for name in &self.0.required { - debugln!("Validator::validate_required:iter:{}:", name); - if matcher.contains(name) { - continue; - } - if to_rem.contains(name) { - continue; - } else if let Some(a) = find_any_by_name!(self.0, *name) { - if self.is_missing_required_ok(a, matcher) { - to_rem.push(a.name()); - if let Some(reqs) = a.requires() { - for r in reqs - .iter() - .filter(|&&(val, _)| val.is_none()) - .map(|&(_, name)| name) - { - to_rem.push(r); - } - } - continue; - } - } - should_err = true; - break; - } - if should_err { - for r in &to_rem { - 'inner: for i in (0..self.0.required.len()).rev() { - if &self.0.required[i] == r { - self.0.required.swap_remove(i); - break 'inner; - } - } - } - return self.missing_required_error(matcher, None); - } - - // Validate the conditionally required args - for &(a, v, r) in &self.0.r_ifs { - if let Some(ma) = matcher.get(a) { - if matcher.get(r).is_none() && ma.vals.iter().any(|val| val == v) { - return self.missing_required_error(matcher, Some(r)); - } - } - } - Ok(()) - } - - fn validate_arg_conflicts(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option { - debugln!("Validator::validate_arg_conflicts: a={:?};", a.name()); - a.blacklist().map(|bl| { - bl.iter().any(|conf| { - matcher.contains(conf) - || self - .0 - .groups - .iter() - .find(|g| &g.name == conf) - .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg))) - }) - }) - } - - fn validate_required_unless(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option { - debugln!("Validator::validate_required_unless: a={:?};", a.name()); - macro_rules! check { - ($how:ident, $_self:expr, $a:ident, $m:ident) => {{ - $a.required_unless().map(|ru| { - ru.iter().$how(|n| { - $m.contains(n) || { - if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) { - grp.args.iter().any(|arg| $m.contains(arg)) - } else { - false - } - } - }) - }) - }}; - } - if a.is_set(ArgSettings::RequiredUnlessAll) { - check!(all, self.0, a, matcher) - } else { - check!(any, self.0, a, matcher) - } - } - - fn missing_required_error(&self, matcher: &ArgMatcher, extra: Option<&str>) -> ClapResult<()> { - debugln!("Validator::missing_required_error: extra={:?}", extra); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: self.0.color(), - }); - let mut reqs = self.0.required.iter().map(|&r| &*r).collect::>(); - if let Some(r) = extra { - reqs.push(r); - } - reqs.retain(|n| !matcher.contains(n)); - reqs.dedup(); - debugln!("Validator::missing_required_error: reqs={:#?}", reqs); - let req_args = - usage::get_required_usage_from(self.0, &reqs[..], Some(matcher), extra, true) - .iter() - .fold(String::new(), |acc, s| { - acc + &format!("\n {}", c.error(s))[..] - }); - debugln!( - "Validator::missing_required_error: req_args={:#?}", - req_args - ); - Err(Error::missing_required_argument( - &*req_args, - &*usage::create_error_usage(self.0, matcher, extra), - self.0.color(), - )) - } - - #[inline] - fn is_missing_required_ok(&self, a: &AnyArg, matcher: &ArgMatcher) -> bool { - debugln!("Validator::is_missing_required_ok: a={}", a.name()); - self.validate_arg_conflicts(a, matcher).unwrap_or(false) - || self.validate_required_unless(a, matcher).unwrap_or(false) - } -} diff --git a/third_party/rust/clap/src/args/any_arg.rs b/third_party/rust/clap/src/args/any_arg.rs deleted file mode 100644 index b1c3a6a42538..000000000000 --- a/third_party/rust/clap/src/args/any_arg.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Std -use std::{ - ffi::{OsStr, OsString}, - fmt as std_fmt, - rc::Rc, -}; - -// Internal -use crate::{ - args::settings::ArgSettings, - map::{self, VecMap}, - INTERNAL_ERROR_MSG, -}; - -#[doc(hidden)] -pub trait AnyArg<'n, 'e>: std_fmt::Display { - fn name(&self) -> &'n str; - fn overrides(&self) -> Option<&[&'e str]>; - fn aliases(&self) -> Option>; - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]>; - fn blacklist(&self) -> Option<&[&'e str]>; - fn required_unless(&self) -> Option<&[&'e str]>; - fn is_set(&self, setting: ArgSettings) -> bool; - fn set(&mut self, setting: ArgSettings); - fn has_switch(&self) -> bool; - fn max_vals(&self) -> Option; - fn min_vals(&self) -> Option; - fn num_vals(&self) -> Option; - fn possible_vals(&self) -> Option<&[&'e str]>; - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc Result<(), String>>>; - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc Result<(), OsString>>>; - fn short(&self) -> Option; - fn long(&self) -> Option<&'e str>; - fn val_delim(&self) -> Option; - fn takes_value(&self) -> bool; - fn val_names(&self) -> Option<&VecMap<&'e str>>; - fn help(&self) -> Option<&'e str>; - fn long_help(&self) -> Option<&'e str>; - fn default_val(&self) -> Option<&'e OsStr>; - fn default_vals_ifs(&self) -> Option, &'e OsStr)>>; - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)>; - fn longest_filter(&self) -> bool; - fn val_terminator(&self) -> Option<&'e str>; -} - -pub trait DispOrder { - fn disp_ord(&self) -> usize; -} - -impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T -where - T: AnyArg<'n, 'e> + 'z, -{ - fn name(&self) -> &'n str { - (*self).name() - } - fn overrides(&self) -> Option<&[&'e str]> { - (*self).overrides() - } - fn aliases(&self) -> Option> { - (*self).aliases() - } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - (*self).requires() - } - fn blacklist(&self) -> Option<&[&'e str]> { - (*self).blacklist() - } - fn required_unless(&self) -> Option<&[&'e str]> { - (*self).required_unless() - } - fn is_set(&self, a: ArgSettings) -> bool { - (*self).is_set(a) - } - fn set(&mut self, _: ArgSettings) { - panic!("{}", INTERNAL_ERROR_MSG) - } - fn has_switch(&self) -> bool { - (*self).has_switch() - } - fn max_vals(&self) -> Option { - (*self).max_vals() - } - fn min_vals(&self) -> Option { - (*self).min_vals() - } - fn num_vals(&self) -> Option { - (*self).num_vals() - } - fn possible_vals(&self) -> Option<&[&'e str]> { - (*self).possible_vals() - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc Result<(), String>>> { - (*self).validator() - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc Result<(), OsString>>> { - (*self).validator_os() - } - fn short(&self) -> Option { - (*self).short() - } - fn long(&self) -> Option<&'e str> { - (*self).long() - } - fn val_delim(&self) -> Option { - (*self).val_delim() - } - fn takes_value(&self) -> bool { - (*self).takes_value() - } - fn val_names(&self) -> Option<&VecMap<&'e str>> { - (*self).val_names() - } - fn help(&self) -> Option<&'e str> { - (*self).help() - } - fn long_help(&self) -> Option<&'e str> { - (*self).long_help() - } - fn default_val(&self) -> Option<&'e OsStr> { - (*self).default_val() - } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { - (*self).default_vals_ifs() - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - (*self).env() - } - fn longest_filter(&self) -> bool { - (*self).longest_filter() - } - fn val_terminator(&self) -> Option<&'e str> { - (*self).val_terminator() - } -} diff --git a/third_party/rust/clap/src/args/arg.rs b/third_party/rust/clap/src/args/arg.rs deleted file mode 100644 index 27db8ee11700..000000000000 --- a/third_party/rust/clap/src/args/arg.rs +++ /dev/null @@ -1,3961 +0,0 @@ -#[cfg(feature = "yaml")] -use std::collections::BTreeMap; -#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] -use std::os::unix::ffi::OsStrExt; -use std::{ - env, - ffi::{OsStr, OsString}, - rc::Rc, -}; - -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use crate::osstringext::OsStrExt3; -use crate::{ - args::{ - arg_builder::{Base, Switched, Valued}, - settings::ArgSettings, - }, - map::VecMap, - usage_parser::UsageParser, -}; - -/// 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. -/// -/// # Examples -/// -/// ```rust -/// # use clap::Arg; -/// // Using the traditional builder pattern and setting each option manually -/// let cfg = Arg::with_name("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::from_usage("-i, --input=[FILE] 'Provides an input file to the program'"); -/// ``` -/// [`Arg`]: ./struct.Arg.html -#[allow(missing_debug_implementations)] -#[derive(Default, Clone)] -pub struct Arg<'a, 'b> -where - 'a: 'b, -{ - #[doc(hidden)] - pub b: Base<'a, 'b>, - #[doc(hidden)] - pub s: Switched<'b>, - #[doc(hidden)] - pub v: Valued<'a, 'b>, - #[doc(hidden)] - pub index: Option, - #[doc(hidden)] - pub r_ifs: Option>, -} - -impl<'a, 'b> Arg<'a, 'b> { - /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get - /// information about 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::{App, Arg}; - /// Arg::with_name("config") - /// # ; - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg`]: ./struct.Arg.html - pub fn with_name(n: &'a str) -> Self { - Arg { - b: Base::new(n), - ..Default::default() - } - } - - /// Creates a new instance of [`Arg`] from a .yml (YAML) file. - /// - /// # Examples - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::Arg; - /// # fn main() { - /// let yml = load_yaml!("arg.yml"); - /// let arg = Arg::from_yaml(yml); - /// # } - /// ``` - /// [`Arg`]: ./struct.Arg.html - #[cfg(feature = "yaml")] - pub fn from_yaml(y: &BTreeMap) -> Arg { - // We WANT this to panic on error...so expect() is good. - let name_yml = y.keys().nth(0).unwrap(); - let name_str = name_yml.as_str().unwrap(); - let mut a = Arg::with_name(name_str); - let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap(); - - for (k, v) in arg_settings.iter() { - a = match k.as_str().unwrap() { - "short" => yaml_to_str!(a, v, short), - "long" => yaml_to_str!(a, v, long), - "aliases" => yaml_vec_or_str!(v, a, 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), - "required_ifs" => yaml_tuple2!(a, v, required_if), - "takes_value" => yaml_to_bool!(a, v, takes_value), - "index" => yaml_to_u64!(a, v, index), - "global" => yaml_to_bool!(a, v, global), - "multiple" => yaml_to_bool!(a, v, multiple), - "hidden" => yaml_to_bool!(a, v, hidden), - "next_line_help" => yaml_to_bool!(a, v, next_line_help), - "empty_values" => yaml_to_bool!(a, v, empty_values), - "group" => yaml_to_str!(a, v, group), - "number_of_values" => yaml_to_u64!(a, v, number_of_values), - "max_values" => yaml_to_u64!(a, v, max_values), - "min_values" => yaml_to_u64!(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_str!(a, v, value_delimiter), - "required_unless" => yaml_to_str!(a, v, required_unless), - "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), - "env" => yaml_to_str!(a, v, env), - "value_names" => yaml_vec_or_str!(v, a, value_name), - "groups" => yaml_vec_or_str!(v, a, group), - "requires" => yaml_vec_or_str!(v, a, requires), - "requires_if" => yaml_tuple2!(a, v, requires_if), - "requires_ifs" => yaml_tuple2!(a, v, requires_if), - "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), - "overrides_with" => yaml_vec_or_str!(v, a, overrides_with), - "possible_values" => yaml_vec_or_str!(v, a, possible_value), - "case_insensitive" => yaml_to_bool!(a, v, case_insensitive), - "required_unless_one" => yaml_vec_or_str!(v, a, required_unless), - "required_unless_all" => { - a = yaml_vec_or_str!(v, a, required_unless); - a.setb(ArgSettings::RequiredUnlessAll); - a - } - s => panic!( - "Unknown Arg setting '{}' in YAML file for arg '{}'", - s, name_str - ), - } - } - - a - } - - /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings - /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow. - /// - /// **NOTE**: Not all settings may be set using the usage string method. Some properties are - /// only available via the builder pattern. - /// - /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some - /// UTF-8 codepoints may work just fine, but this is not guaranteed. - /// - /// # Syntax - /// - /// Usage strings typically following the form: - /// - /// ```notrust - /// [explicit name] [short] [long] [value names] [help string] - /// ``` - /// - /// This is not a hard rule as the attributes can appear in other orders. There are also - /// several additional sigils which denote additional settings. Below are the details of each - /// portion of the string. - /// - /// ### Explicit Name - /// - /// 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: - /// - /// * Explicit Name (This always takes precedence when present) - /// * Long - /// * Short - /// * Value Name - /// - /// `clap` determines explicit names as the first string of characters between either `[]` or - /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning - /// the argument is required. - /// - /// Explicit names may be followed by: - /// * The multiple denotation `...` - /// - /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a - /// required argument): - /// - /// ```notrust - /// [ename] -s, --long 'some flag' - /// -r, --longer 'some other flag' - /// ``` - /// - /// ### Short - /// - /// This is set by placing a single character after a leading `-`. - /// - /// Shorts may be followed by - /// * The multiple denotation `...` - /// * An optional comma `,` which is cosmetic only - /// * Value notation - /// - /// Example shorts are as follows (`-s`, and `-r`): - /// - /// ```notrust - /// -s, --long 'some flag' - /// -r [val], --longer 'some option' - /// ``` - /// - /// ### Long - /// - /// This is set by placing a word (no spaces) after a leading `--`. - /// - /// Shorts may be followed by - /// * The multiple denotation `...` - /// * Value notation - /// - /// Example longs are as follows (`--some`, and `--rapid`): - /// - /// ```notrust - /// -s, --some 'some flag' - /// --rapid=[FILE] 'some option' - /// ``` - /// - /// ### Values (Value Notation) - /// - /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this - /// is cosmetic only and does not affect functionality). If an explicit name has **not** been - /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument - /// - /// Values may be followed by - /// * The multiple denotation `...` - /// * More Value notation - /// - /// More than one value will also implicitly set the arguments number of values, i.e. having - /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it - /// must receive exactly two values - /// - /// Example values are as follows (`FILE`, and `SPEED`): - /// - /// ```notrust - /// -s, --some [FILE] 'some option' - /// --rapid=... 'some required multiple option' - /// ``` - /// - /// ### Help String - /// - /// The help string is denoted between a pair of single quotes `''` and may contain any - /// characters. - /// - /// Example help strings are as follows: - /// - /// ```notrust - /// -s, --some [FILE] 'some option' - /// --rapid=... 'some required multiple option' - /// ``` - /// - /// ### Additional Sigils - /// - /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may - /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values. - /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is - /// multiple occurrences (and then you can obviously have instances of both as well) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// App::new("prog") - /// .args(&[ - /// Arg::from_usage("--config 'a required file for the configuration and no short'"), - /// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"), - /// Arg::from_usage("[input] 'an optional input file to use'") - /// ]) - /// # ; - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage - pub fn from_usage(u: &'a str) -> Self { - let parser = UsageParser::from_usage(u); - parser.parse() - } - - /// Sets the short version of the argument without the preceding `-`. - /// - /// By default `clap` automatically assigns `V` and `h` to 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. - /// - /// **NOTE:** Any leading `-` characters will be stripped, and only the first - /// non `-` character will be used as the [`short`] version - /// - /// # Examples - /// - /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as - /// `-c`, the `-` will be stripped. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .short("c") - /// # ; - /// ``` - /// - /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("config") - /// .short("c")) - /// .get_matches_from(vec![ - /// "prog", "-c" - /// ]); - /// - /// assert!(m.is_present("config")); - /// ``` - /// [`short`]: ./struct.Arg.html#method.short - pub fn short>(mut self, s: S) -> Self { - self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().next(); - self - } - - /// Sets the long version of the argument without the preceding `--`. - /// - /// By default `clap` automatically assigns `version` and `help` to 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 codepoints. 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) - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("cfg") - /// .long("config") - /// # ; - /// ``` - /// - /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config")) - /// .get_matches_from(vec![ - /// "prog", "--config" - /// ]); - /// - /// assert!(m.is_present("cfg")); - /// ``` - pub fn long(mut self, l: &'b str) -> Self { - self.s.long = Some(l.trim_left_matches(|c| c == '-')); - self - } - - /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that - /// automatically dispatch as if this argument was used. 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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .alias("alias") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--alias", "cool" - /// ]); - /// assert!(m.is_present("test")); - /// assert_eq!(m.value_of("test"), Some("cool")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - pub fn alias>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.s.aliases { - als.push((name.into(), false)); - } else { - self.s.aliases = Some(vec![(name.into(), false)]); - } - self - } - - /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that - /// automatically dispatch as if this argument 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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .aliases(&["do-stuff", "do-tests", "tests"]) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "--do-tests" - /// ]); - /// assert!(m.is_present("test")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - pub fn aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.s.aliases { - for n in names { - als.push((n, false)); - } - } else { - self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::>()); - } - self - } - - /// Allows adding a [`Arg`] alias that functions exactly like those defined with - /// [`Arg::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .visible_alias("something-awesome") - /// .long("test") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--something-awesome", "coffee" - /// ]); - /// assert!(m.is_present("test")); - /// assert_eq!(m.value_of("test"), Some("coffee")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`App::alias`]: ./struct.Arg.html#method.alias - pub fn visible_alias>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.s.aliases { - als.push((name.into(), true)); - } else { - self.s.aliases = Some(vec![(name.into(), true)]); - } - self - } - - /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined - /// with [`Arg::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .visible_aliases(&["something", "awesome", "cool"])) - /// .get_matches_from(vec![ - /// "prog", "--awesome" - /// ]); - /// assert!(m.is_present("test")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`App::aliases`]: ./struct.Arg.html#method.aliases - pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.s.aliases { - for n in names { - als.push((n, true)); - } - } else { - self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::>()); - } - self - } - - /// Sets the short help text of the argument that will be displayed to the user when they print - /// the help information with `-h`. Typically, this is a short (one line) description of the - /// arg. - /// - /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests - /// `--help` clap will still display the contents of `help` appropriately - /// - /// **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. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .help("The config file used by the myprog") - /// # ; - /// ``` - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("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 [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help - pub fn help(mut self, h: &'b str) -> Self { - self.b.help = Some(h); - self - } - - /// Sets the long help text of the argument that will be displayed to the user when they print - /// the help information with `--help`. Typically this a more detailed (multi-line) message - /// that describes the arg. - /// - /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h` - /// clap will still display the contents of `long_help` appropriately - /// - /// **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. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("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.") - /// # ; - /// ``` - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("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 - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --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 - /// Prints help information - /// - /// -V, --version - /// Prints version information - /// ``` - /// [`Arg::help`]: ./struct.Arg.html#method.help - pub fn long_help(mut self, h: &'b str) -> Self { - self.b.long_help = Some(h); - self - } - - /// Specifies that 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 [FLAGS] [-- ]` if - /// `ARG` is marked as `.last(true)`. - /// - /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing - /// to set this can make the usage string very confusing. - /// - /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS / - /// OPTIONS - /// - /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not - /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`] - /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also - /// marked [`.required(true)`]) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("args") - /// .last(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::last(true)`] 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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("first")) - /// .arg(Arg::with_name("second")) - /// .arg(Arg::with_name("third").last(true)) - /// .get_matches_from_safe(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(true)` is the only argument left to parse, - /// failing to use the `--` syntax results in an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("first")) - /// .arg(Arg::with_name("second")) - /// .arg(Arg::with_name("third").last(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "one", "two", "three" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::last(true)`]: ./struct.Arg.html#method.last - /// [index]: ./struct.Arg.html#method.index - /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage - /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands - /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs - /// [`.required(true)`]: ./struct.Arg.html#method.required - /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument - pub fn last(self, l: bool) -> Self { - if l { - self.set(ArgSettings::Last) - } else { - self.unset(ArgSettings::Last) - } - } - - /// Sets whether or not the argument is required by default. Required by default means it is - /// required, when no other conflicting rules have been evaluated. Conflicting rules take - /// precedence over being required. **Default:** `false` - /// - /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by - /// default. This is simply because if a flag should be required, it should simply be implied - /// as no additional information is required from user. Flags by their very nature are simply - /// yes/no, or true/false. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::required(true)`] requires that the argument be used at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required(true)`]: ./struct.Arg.html#method.required - pub fn required(self, r: bool) -> Self { - if r { - self.set(ArgSettings::Required) - } else { - self.unset(ArgSettings::Required) - } - } - - /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and - /// associated value) **Default:** `false` - /// - /// **NOTE:** This setting also removes the default of allowing empty values and implies - /// [`Arg::empty_values(false)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .long("config") - /// .takes_value(true) - /// .require_equals(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between - /// it and the associated value. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .require_equals(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config=file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error - /// unless [`Arg::empty_values(true)`] is set. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .require_equals(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); - /// ``` - /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals - /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values - /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values - pub fn require_equals(mut self, r: bool) -> Self { - if r { - self.unsetb(ArgSettings::EmptyValues); - self.set(ArgSettings::RequireEquals) - } else { - self.unset(ArgSettings::RequireEquals) - } - } - - /// Allows values which start with a leading hyphen (`-`) - /// - /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], 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::number_of_values(1)`] - /// - /// **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 - /// 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::Arg; - /// Arg::with_name("pattern") - /// .allow_hyphen_values(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("pat") - /// .allow_hyphen_values(true) - /// .takes_value(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("pat") - /// .takes_value(true) - /// .long("pattern")) - /// .get_matches_from_safe(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values - pub fn allow_hyphen_values(self, a: bool) -> Self { - if a { - self.set(ArgSettings::AllowLeadingHyphen) - } else { - self.unset(ArgSettings::AllowLeadingHyphen) - } - } - /// Sets an arg that override this arg's required setting. (i.e. this arg will be required - /// unless this other argument is present). - /// - /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not - /// mandatory to also set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless("debug") - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime - /// *unless* `name` is present. 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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless - /// [`Arg::required`]: ./struct.Arg.html#method.required - /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless - pub fn required_unless(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - vec.push(name); - } else { - self.b.r_unless = Some(vec![name]); - } - self.required(true) - } - - /// Sets args that override this arg's required setting. (i.e. this arg will be required unless - /// all these other arguments are present). - /// - /// **NOTE:** If you wish for this argument to only be required if *one of* these args are - /// present see [`Arg::required_unless_one`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless_all(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime - /// *unless* *all* the args in `names` are present. In the following example, the required - /// argument is *not* provided, but it's not an error because all the `unless` args have been - /// supplied. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug", "-i", "file" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this - /// arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one - /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all - pub fn required_unless_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - for s in names { - vec.push(s); - } - } else { - self.b.r_unless = Some(names.iter().copied().collect()); - } - self.setb(ArgSettings::RequiredUnlessAll); - self.required(true) - } - - /// Sets args that override this arg's [required] setting. (i.e. this arg will be required - /// unless *at least one of* these other arguments are present). - /// - /// **NOTE:** If you wish for this argument to only be required if *all of* these args are - /// present see [`Arg::required_unless_all`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless_all(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_one(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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_one(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names` - /// or this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_one(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: ./struct.Arg.html#method.required - /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one - /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all - pub fn required_unless_one(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - for s in names { - vec.push(s); - } - } else { - self.b.r_unless = Some(names.iter().copied().collect()); - } - self.required(true) - } - - /// Sets a conflicting argument by name. I.e. when using this argument, - /// the following argument can't be present and vice versa. - /// - /// **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)) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .conflicts_with("debug") - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having both arguments present at runtime is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .conflicts_with("debug") - /// .long("config")) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); - /// ``` - pub fn conflicts_with(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.blacklist { - vec.push(name); - } else { - self.b.blacklist = Some(vec![name]); - } - self - } - - /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per - /// 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 - /// need to also do B.conflicts_with(A)) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .conflicts_with_all(&["debug", "input"]) - /// .long("config")) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); - /// ``` - /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with - pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.blacklist { - for s in names { - vec.push(s); - } - } else { - self.b.blacklist = Some(names.iter().copied().collect()); - } - self - } - - /// Sets a overridable argument 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 - /// - /// **WARNING:** Positional arguments cannot override themselves (or we would never be able - /// to advance to the next positional). If a positional agument lists itself as an override, - /// it is simply ignored. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::from_usage("-f, --flag 'some flag'") - /// .conflicts_with("debug")) - /// .arg(Arg::from_usage("-d, --debug 'other flag'")) - /// .arg(Arg::from_usage("-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::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) - /// .get_matches_from(vec!["posix", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// assert_eq!(m.occurrences_of("flag"), 1); - /// ``` - /// Making a arg `multiple(true)` 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::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) - /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// assert_eq!(m.occurrences_of("flag"), 4); - /// ``` - /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last - /// occurrence happened. - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// assert_eq!(m.value_of("opt"), Some("other")); - /// ``` - /// - /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting. - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val]... 'some option'") - /// .overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 2); - /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "over", "other", "val"]); - /// ``` - /// - /// A safe thing to do if you'd like to support an option which supports multiple values, but - /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use - /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`) - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val] 'some option'") - /// .overrides_with("opt") - /// .use_delimiter(false)) - /// .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// assert_eq!(m.values_of("opt").unwrap().collect::>(), &["one,two"]); - /// ``` - pub fn overrides_with(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.overrides { - vec.push(name); - } else { - self.b.overrides = Some(vec![name]); - } - 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 - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::from_usage("-f, --flag 'some flag'") - /// .conflicts_with("color")) - /// .arg(Arg::from_usage("-d, --debug 'other flag'")) - /// .arg(Arg::from_usage("-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")); - /// ``` - pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.overrides { - for s in names { - vec.push(s); - } - } else { - self.b.overrides = Some(names.iter().copied().collect()); - } - self - } - - /// Sets an argument by name 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::with_name("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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.requires { - vec.push((None, name)); - } else { - self.b.requires = Some(vec![(None, name)]); - } - self - } - - /// Allows a conditional requirement. The requirement will only become valid if this arg's value - /// equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// requires_if: - /// - [val, arg] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "other") - /// .long("config")) - /// .arg(Arg::with_name("other")) - /// .get_matches_from_safe(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "input") - /// .long("config")) - /// .arg(Arg::with_name("input")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "my.cfg" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self { - if let Some(ref mut vec) = self.b.requires { - vec.push((Some(val), arg)); - } else { - self.b.requires = Some(vec![(Some(val), arg)]); - } - self - } - - /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value - /// equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// requires_if: - /// - [val, arg] - /// - [val2, arg2] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_ifs(&[ - /// ("special.conf", "opt"), - /// ("other.conf", "other"), - /// ]) - /// .long("config")) - /// .arg(Arg::with_name("opt") - /// .long("option") - /// .takes_value(true)) - /// .arg(Arg::with_name("other")) - /// .get_matches_from_safe(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)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self { - if let Some(ref mut vec) = self.b.requires { - for &(val, arg) in ifs { - vec.push((Some(val), arg)); - } - } else { - let mut vec = vec![]; - for &(val, arg) in ifs { - vec.push((Some(val), arg)); - } - self.b.requires = Some(vec); - } - self - } - - /// Allows specifying that an argument is [required] conditionally. The requirement will only - /// become valid if the specified `arg`'s value equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// required_if: - /// - [arg, val] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_if("other_arg", "value") - /// # ; - /// ``` - /// - /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at - /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`, - /// this argument isn't required. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .required_if("other", "special") - /// .long("config")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--other", "not-special" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required - /// ``` - /// - /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not* - /// using this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .required_if("other", "special") - /// .long("config")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--other", "special" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [required]: ./struct.Arg.html#method.required - pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self { - if let Some(ref mut vec) = self.r_ifs { - vec.push((arg, val)); - } else { - self.r_ifs = Some(vec![(arg, val)]); - } - self - } - - /// Allows specifying that an 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 it's corresponding `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// required_if: - /// - [arg, val] - /// - [arg2, val2] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_ifs(&[(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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::with_name("option") - /// .takes_value(true) - /// .long("option")) - /// .get_matches_from_safe(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_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::with_name("option") - /// .takes_value(true) - /// .long("option")) - /// .get_matches_from_safe(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [required]: ./struct.Arg.html#method.required - pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self { - if let Some(ref mut vec) = self.r_ifs { - for r_if in ifs { - vec.push((r_if.0, r_if.1)); - } - } else { - let mut vec = vec![]; - for r_if in ifs { - vec.push((r_if.0, r_if.1)); - } - self.r_ifs = Some(vec); - } - self - } - - /// Sets multiple arguments by names that are required when this one is present 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::with_name("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::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .arg(Arg::with_name("output") - /// .index(2)) - /// .get_matches_from_safe(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_all(&["input", "output"]) - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .arg(Arg::with_name("output") - /// .index(2)) - /// .get_matches_from_safe(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]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all - pub fn requires_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.requires { - for s in names { - vec.push((None, s)); - } - } else { - let mut vec = vec![]; - for s in names { - vec.push((None, *s)); - } - self.b.requires = Some(vec); - } - self - } - - /// 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_delimiter(false)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .takes_value(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter - /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter - /// [multiple values]: ./struct.Arg.html#method.multiple - pub fn takes_value(self, tv: bool) -> Self { - if tv { - self.set(ArgSettings::TakesValue) - } else { - self.unset(ArgSettings::TakesValue) - } - } - - /// Specifies if the possible values of an argument should be displayed in the help text or - /// not. Defaults to `false` (i.e. show possible values) - /// - /// This is useful for args with many values, or ones which are explained elsewhere in the - /// help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .hide_possible_values(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .possible_values(&["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. - pub fn hide_possible_values(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HidePossibleValues) - } else { - self.unset(ArgSettings::HidePossibleValues) - } - } - - /// Specifies if the default value of an argument should be displayed in the help text or - /// not. Defaults to `false` (i.e. show default value) - /// - /// This is useful when default behavior of an arg is explained elsewhere in the help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .hide_default_value(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("connect") - /// .arg(Arg::with_name("host") - /// .long("host") - /// .default_value("localhost") - /// .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. - pub fn hide_default_value(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HideDefaultValue) - } else { - self.unset(ArgSettings::HideDefaultValue) - } - } - - /// 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:** If no [`Arg::short`], or [`Arg::long`] have been defined, 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:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument - /// may be defined as multiple (i.e. with the highest index) - /// - /// # Panics - /// - /// Although not in this method directly, [`App`] 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::{App, Arg}; - /// Arg::with_name("config") - /// .index(1) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .index(1)) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .get_matches_from(vec![ - /// "prog", "--debug", "fast" - /// ]); - /// - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" - /// // *not* first argument - /// ``` - /// [`Arg::short`]: ./struct.Arg.html#method.short - /// [`Arg::long`]: ./struct.Arg.html#method.long - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`App`]: ./struct.App.html - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - pub fn index(mut self, idx: u64) -> Self { - self.index = Some(idx); - self - } - - /// Specifies that the argument may appear more than once. For flags, this results - /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d` - /// would count as three occurrences. For options there is a distinct difference in multiple - /// occurrences vs multiple values. - /// - /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas - /// `--opt val1 --opt val2` is two occurrences. - /// - /// **WARNING:** - /// - /// Setting `multiple(true)` for an [option] with no other details, allows multiple values - /// **and** multiple occurrences because it isn't possible to have more occurrences than values - /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly - /// valid, be careful when designing a CLI where positional arguments are expected after a - /// option which accepts multiple values, as `clap` will continue parsing *values* until it - /// reaches the max or specific number of values defined, or another flag or option. - /// - /// **Pro Tip**: - /// - /// It's possible to define an option which allows multiple occurrences, but only one value per - /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with - /// [`Arg::multiple(true)`]. - /// - /// **WARNING:** - /// - /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that - /// accept 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(true)` with no additional parameters and - /// a possible value that coincides with a subcommand name, the subcommand cannot be called - /// unless another argument is passed first. - /// - /// As an example, consider a CLI with an option `--ui-paths=...` and subcommand `signer` - /// - /// The following would be parsed as values to `--ui-paths`. - /// - /// ```notrust - /// $ 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. - /// - /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding - /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer` - /// is parsed as both a subcommand and a value in the second case. - /// - /// ```notrust - /// $ program --ui-paths path1 signer - /// $ program --ui-paths path1 --ui-paths signer signer - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .short("d") - /// .multiple(true) - /// # ; - /// ``` - /// An example with flags - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("verbose") - /// .multiple(true) - /// .short("v")) - /// .get_matches_from(vec![ - /// "prog", "-v", "-v", "-v" // note, -vvv would have same result - /// ]); - /// - /// assert!(m.is_present("verbose")); - /// assert_eq!(m.occurrences_of("verbose"), 3); - /// ``` - /// - /// An example with options - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(m.is_present("file")); - /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// This is functionally equivalent to the example above - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" - /// ]); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// - /// assert!(m.is_present("file")); - /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// - /// A common mistake is to define an option which allows multiples, and a positional argument - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(m.is_present("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! - /// assert!(!m.is_present("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 specify that `-F` only accepts one value, but is - /// allowed to appear multiple times - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .number_of_values(1) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" - /// ]); - /// - /// assert!(m.is_present("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert!(m.is_present("word")); - /// assert_eq!(m.value_of("word"), Some("word")); - /// ``` - /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the - /// problem example above, it would have been a runtime error with a pretty message to the - /// user :) - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .number_of_values(1) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [options]: ./struct.Arg.html#method.takes_value - /// [subcommands]: ./struct.SubCommand.html - /// [positionals]: ./struct.Arg.html#method.index - /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn multiple(self, multi: bool) -> Self { - if multi { - self.set(ArgSettings::Multiple) - } else { - self.unset(ArgSettings::Multiple) - } - } - - /// Specifies a value that *stops* parsing multiple values of a give argument. By default when - /// one sets [`multiple(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::{App, Arg}; - /// Arg::with_name("vals") - /// .takes_value(true) - /// .multiple(true) - /// .value_terminator(";") - /// # ; - /// ``` - /// The following example uses two arguments, a sequence of commands, and the location in which - /// to perform them - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cmds") - /// .multiple(true) - /// .allow_hyphen_values(true) - /// .value_terminator(";")) - /// .arg(Arg::with_name("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]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - /// [`multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`min_values`]: ./struct.Arg.html#method.min_values - /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values - /// [`max_values`]: ./struct.Arg.html#method.max_values - pub fn value_terminator(mut self, term: &'b str) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.terminator = Some(term); - self - } - - /// 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 - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .short("d") - /// .global(true) - /// # ; - /// ``` - /// - /// For example, 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::{App, Arg, SubCommand}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("verb") - /// .long("verbose") - /// .short("v") - /// .global(true)) - /// .subcommand(SubCommand::with_name("test")) - /// .subcommand(SubCommand::with_name("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!(sub_m.is_present("verb")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [required]: ./struct.Arg.html#method.required - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg`]: ./struct.Arg.html - pub fn global(self, g: bool) -> Self { - if g { - self.set(ArgSettings::Global) - } else { - self.unset(ArgSettings::Global) - } - } - - /// Allows an argument to accept explicitly empty values. An empty value must be specified at - /// the command line with an explicit `""`, or `''` - /// - /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed) - /// - /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .long("file") - /// .empty_values(false) - /// # ; - /// ``` - /// The default is to allow empty values, such as `--option ""` would be an empty value. But - /// we can change to make empty values become an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .short("v") - /// .empty_values(false)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config=" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn empty_values(mut self, ev: bool) -> Self { - if ev { - self.set(ArgSettings::EmptyValues) - } else { - self = self.set(ArgSettings::TakesValue); - self.unset(ArgSettings::EmptyValues) - } - } - - /// Hides an argument from help message output. - /// - /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`] - /// when set to true - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden(true) - /// # ; - /// ``` - /// Setting `hidden(true)` will hide the argument when displaying help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help - /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help - pub fn hidden(self, h: bool) -> Self { - if h { - self.set(ArgSettings::Hidden) - } else { - self.unset(ArgSettings::Hidden) - } - } - - /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that - /// only one of the specified values was used, or fails with an error message. - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"]) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"])) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// - /// The next example shows a failed parse from using a value which wasn't defined as one of the - /// possible values. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"])) - /// .get_matches_from_safe(vec![ - /// "prog", "--mode", "wrong" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); - /// ``` - /// [options]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - pub fn possible_values(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut vec) = self.v.possible_vals { - for s in names { - vec.push(s); - } - } else { - self.v.possible_vals = Some(names.iter().copied().collect()); - } - self - } - - /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies - /// that only one of the specified values was used, or fails with error message. - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium")) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// - /// The next example shows a failed parse from using a value which wasn't defined as one of the - /// possible values. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium")) - /// .get_matches_from_safe(vec![ - /// "prog", "--mode", "wrong" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); - /// ``` - /// [options]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - pub fn possible_value(mut self, name: &'b str) -> Self { - if let Some(ref mut vec) = self.v.possible_vals { - vec.push(name); - } else { - self.v.possible_vals = Some(vec![name]); - } - self - } - - /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if - /// the case differs from that of the specified `possible_value`. - /// - /// **Pro Tip:** Use this setting with [`arg_enum!`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// # use std::ascii::AsciiExt; - /// let m = App::new("pv") - /// .arg(Arg::with_name("option") - /// .long("--option") - /// .takes_value(true) - /// .possible_value("test123") - /// .case_insensitive(true)) - /// .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::{App, Arg}; - /// let m = App::new("pv") - /// .arg(Arg::with_name("option") - /// .short("-o") - /// .long("--option") - /// .takes_value(true) - /// .possible_value("test123") - /// .possible_value("test321") - /// .multiple(true) - /// .case_insensitive(true)) - /// .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"]); - /// ``` - /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values - /// [`arg_enum!`]: ./macro.arg_enum.html - pub fn case_insensitive(self, ci: bool) -> Self { - if ci { - self.set(ArgSettings::CaseInsensitive) - } else { - self.unset(ArgSettings::CaseInsensitive) - } - } - - /// Specifies the name of the [`ArgGroup`] the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .group("mode")) - /// .arg(Arg::with_name("verbose") - /// .long("verbose") - /// .group("mode")) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.is_present("mode")); - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - pub fn group(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.groups { - vec.push(name); - } else { - self.b.groups = Some(vec![name]); - } - self - } - - /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .groups(&["mode", "verbosity"])) - /// .arg(Arg::with_name("verbose") - /// .long("verbose") - /// .groups(&["mode", "verbosity"])) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.is_present("mode")); - /// assert!(m.is_present("verbosity")); - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - pub fn groups(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.groups { - for s in names { - vec.push(s); - } - } else { - self.b.groups = Some(names.iter().copied().collect()); - } - self - } - - /// Specifies how many values are required to satisfy 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(true)`] to be set. Setting - /// [`Arg::multiple(true)`] would allow `-f -f ` where - /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .number_of_values(3) - /// # ; - /// ``` - /// - /// Not supplying the correct number of values is an error - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .number_of_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn number_of_values(mut self, qty: u64) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.num_vals = Some(qty); - self - } - - /// Allows one to perform a custom validation on the argument value. You provide a closure - /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a - /// message displayed to the user. - /// - /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the - /// message as all errors will appear as - /// `error: Invalid value for '': ` where `` is replaced by the actual - /// arg, and `` is the `String` you return as the error. - /// - /// **NOTE:** There is a small performance hit for using validators, as they are implemented - /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order - /// to to be passed to the closure. This performance hit is extremely minimal in the grand - /// scheme of things. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// fn has_at(v: String) -> Result<(), String> { - /// if v.contains("@") { return Ok(()); } - /// Err(String::from("The value did not contain the required @ sigil")) - /// } - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .index(1) - /// .validator(has_at)) - /// .get_matches_from_safe(vec![ - /// "prog", "some@file" - /// ]); - /// assert!(res.is_ok()); - /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html - /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err - /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html - pub fn validator(mut self, f: F) -> Self - where - F: Fn(String) -> Result<(), String> + 'static, - { - self.v.validator = Some(Rc::new(f)); - self - } - - /// Works identically to Validator but is intended to be used with values that could - /// contain non UTF-8 formatted strings. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```rust")] - /// # use clap::{App, Arg}; - /// # use std::ffi::{OsStr, OsString}; - /// # use std::os::unix::ffi::OsStrExt; - /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> { - /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } - /// Err(OsString::from("The value did not contain the required & sigil")) - /// } - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .index(1) - /// .validator_os(has_ampersand)) - /// .get_matches_from_safe(vec![ - /// "prog", "Fish & chips" - /// ]); - /// assert!(res.is_ok()); - /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html - /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html - /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err - /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html - pub fn validator_os(mut self, f: F) -> Self - where - F: Fn(&OsStr) -> Result<(), OsString> + 'static, - { - self.v.validator_os = Some(Rc::new(f)); - self - } - - /// Specifies 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(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(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .max_values(3) - /// # ; - /// ``` - /// - /// Supplying less than the maximum number of values is allowed - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .max_values(3) - /// .short("F")) - /// .get_matches_from_safe(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .max_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn max_values(mut self, qty: u64) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.max_vals = Some(qty); - self - } - - /// Specifies 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(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(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .min_values(3) - /// # ; - /// ``` - /// - /// Supplying more than the minimum number of values is allowed - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .min_values(2) - /// .short("F")) - /// .get_matches_from_safe(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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .min_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn min_values(mut self, qty: u64) -> Self { - self.v.min_vals = Some(qty); - self.set(ArgSettings::TakesValue) - } - - /// Specifies whether or not 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:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`] - /// is the comma `,`. - /// - /// # Examples - /// - /// The following example shows the default behavior. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("option") - /// .long("option") - /// .use_delimiter(true) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(delims.is_present("option")); - /// assert_eq!(delims.occurrences_of("option"), 1); - /// 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::{App, Arg}; - /// let nodelims = App::new("prog") - /// .arg(Arg::with_name("option") - /// .long("option") - /// .use_delimiter(false) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(nodelims.is_present("option")); - /// assert_eq!(nodelims.occurrences_of("option"), 1); - /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); - /// ``` - /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter - pub fn use_delimiter(mut self, d: bool) -> Self { - if d { - if self.v.val_delim.is_none() { - self.v.val_delim = Some(','); - } - self.setb(ArgSettings::TakesValue); - self.setb(ArgSettings::UseValueDelimiter); - } else { - self.v.val_delim = None; - self.unsetb(ArgSettings::UseValueDelimiter); - } - self.unset(ArgSettings::ValueDelimiterNotSet) - } - - /// Specifies that *multiple values* may only be set using the delimiter. This means if an - /// if an option is encountered, and no delimiter is found, it automatically 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 to true implies [`Arg::use_delimiter(true)`] - /// - /// **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::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true) - /// .require_delimiter(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1,val2,val3", - /// ]); - /// - /// assert!(delims.is_present("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::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true) - /// .require_delimiter(true)) - /// .get_matches_from_safe(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::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1", "val2", "val3", - /// ]); - /// - /// assert!(delims.is_present("opt")); - /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); - /// ``` - /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - pub fn require_delimiter(mut self, d: bool) -> Self { - if d { - self = self.use_delimiter(true); - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::UseValueDelimiter); - self.set(ArgSettings::RequireDelimiter) - } else { - self = self.use_delimiter(false); - self.unsetb(ArgSettings::UseValueDelimiter); - self.unset(ArgSettings::RequireDelimiter) - } - } - - /// Specifies the separator to use when values are clumped together, defaults to `,` (comma). - /// - /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`] - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("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_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn value_delimiter(mut self, d: &str) -> Self { - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::TakesValue); - self.setb(ArgSettings::UseValueDelimiter); - self.v.val_delim = Some( - d.chars() - .next() - .expect("Failed to get value_delimiter from arg"), - ); - self - } - - /// Specify multiple names for values of option arguments. 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:** This implicitly sets [`Arg::number_of_values`] if the number of value names is - /// greater than one. I.e. be aware that the number of "names" you set for the values, will be - /// the *exact* number of values required to satisfy this argument - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("speed") - /// .short("s") - /// .value_names(&["fast", "slow"]) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("io") - /// .long("io-files") - /// .value_names(&["INFILE", "OUTFILE"])) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```notrust - /// valnames - /// - /// USAGE: - /// valnames [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// --io-files Some help text - /// ``` - /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help - /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn value_names(mut self, names: &[&'b str]) -> Self { - self.setb(ArgSettings::TakesValue); - if self.is_set(ArgSettings::ValueDelimiterNotSet) { - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::UseValueDelimiter); - } - if let Some(ref mut vals) = self.v.val_names { - let mut l = vals.len(); - for s in names { - vals.insert(l, s); - l += 1; - } - } else { - let mut vm = VecMap::new(); - for (i, n) in names.iter().enumerate() { - vm.insert(i, *n); - } - self.v.val_names = Some(vm); - } - self - } - - /// Specifies the name for value of [option] or [positional] arguments inside of help - /// documentation. 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::{App, Arg}; - /// Arg::with_name("cfg") - /// .long("config") - /// .value_name("FILE") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("config") - /// .long("config") - /// .value_name("FILE")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```notrust - /// valnames - /// - /// USAGE: - /// valnames [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// --config Some help text - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [positional]: ./struct.Arg.html#method.index - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn value_name(mut self, name: &'b str) -> Self { - self.setb(ArgSettings::TakesValue); - if let Some(ref mut vals) = self.v.val_names { - let l = vals.len(); - vals.insert(l, name); - } else { - let mut vm = VecMap::new(); - vm.insert(0, name); - self.v.val_names = Some(vm); - } - self - } - - /// Specifies the value of the argument when *not* specified at runtime. - /// - /// **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::is_present`] will - /// still return `true`. If you wish to determine whether the argument was used at runtime or - /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* - /// used at runtime. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly - /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg - /// at runtime. `Arg::default_value_if` however only takes affect 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 a this - /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the - /// `Arg::default_value` will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in - /// conjunction as it ensures that some argument will always be present. - /// - /// # Examples - /// - /// First we use the default value without providing any value at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("opt"), Some("myval")); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 0); - /// ``` - /// - /// Next we provide a value at runtime to override the default. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("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.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// ``` - /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of - /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if - pub fn default_value(self, val: &'a str) -> Self { - self.default_value_os(OsStr::from_bytes(val.as_bytes())) - } - - /// Provides a default value in the exact same manner as [`Arg::default_value`] - /// only using [`OsStr`]s instead. - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - pub fn default_value_os(mut self, val: &'a OsStr) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.default_val = Some(val); - 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`. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly - /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg - /// at runtime. This setting however only takes affect 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 a this arg at runtime, nor did - /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be - /// applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented - /// as `null` in YAML) - /// - /// ```yaml - /// default_value_if: - /// - [arg, val, default] - /// ``` - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("flag", None, "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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("flag", None, "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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), "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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), "default")) - /// .get_matches_from(vec![ - /// "prog", "--opt", "hahaha" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self { - self.default_value_if_os( - arg, - val.map(str::as_bytes).map(OsStr::from_bytes), - OsStr::from_bytes(default.as_bytes()), - ) - } - - /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] - /// only using [`OsStr`]s instead. - /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - pub fn default_value_if_os( - mut self, - arg: &'a str, - val: Option<&'b OsStr>, - default: &'b OsStr, - ) -> Self { - self.setb(ArgSettings::TakesValue); - if let Some(ref mut vm) = self.v.default_vals_ifs { - let l = vm.len(); - vm.insert(l, (arg, val, default)); - } else { - let mut vm = VecMap::new(); - vm.insert(0, (arg, val, default)); - self.v.default_vals_ifs = Some(vm); - } - self - } - - /// 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. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// default_value_if: - /// - [arg, val, default] - /// - [arg2, null, default2] - /// ``` - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "chan"), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self { - for &(arg, val, default) in ifs { - self = self.default_value_if_os( - arg, - val.map(str::as_bytes).map(OsStr::from_bytes), - OsStr::from_bytes(default.as_bytes()), - ); - } - 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`]: ./struct.Arg.html#method.default_value_ifs - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self { - for &(arg, val, default) in ifs { - self = self.default_value_if_os(arg, val, default); - } - self - } - - /// Specifies that if the value is not passed in as an argument, that it should be retrieved - /// from the environment, if available. If it is not present in the environment, then default - /// rules will apply. - /// - /// **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::is_present`] will - /// return `true` if the variable is present in the environment . If you wish to determine whether - /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will - /// return `0` if the argument was *not* used at runtime. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be - /// set. Otherwise, only a single argument will be returned from the environment variable. The - /// default delimiter is `,` and follows all the other delimiter rules. - /// - /// # Examples - /// - /// In this example, we show the variable coming from the environment: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("env")); - /// ``` - /// - /// In this example, we show the variable coming from an option on the CLI: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG")) - /// .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::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .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::{App, Arg}; - /// - /// env::set_var("MY_FLAG_MULTI", "env1,env2"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG_MULTI") - /// .multiple(true) - /// .use_delimiter(true)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.values_of("flag").unwrap().collect::>(), vec!["env1", "env2"]); - /// ``` - /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of - /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of - /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - pub fn env(self, name: &'a str) -> Self { - self.env_os(OsStr::new(name)) - } - - /// Specifies that if the value is not passed in as an argument, that it should be retrieved - /// from the environment if available in the exact same manner as [`Arg::env`] only using - /// [`OsStr`]s instead. - pub fn env_os(mut self, name: &'a OsStr) -> Self { - self.setb(ArgSettings::TakesValue); - - self.v.env = Some((name, env::var_os(name))); - self - } - - /// @TODO @p2 @docs @release: write docs - pub fn hide_env_values(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HideEnvValues) - } else { - self.unset(ArgSettings::HideEnvValues) - } - } - - /// When set to `true` the help string will be displayed on the line after the argument and - /// indented once. 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 consider using - /// [`AppSettings::NextLineHelp`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .long("long-option-flag") - /// .short("o") - /// .takes_value(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") - /// .next_line_help(true)) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```notrust - /// nlh - /// - /// USAGE: - /// nlh [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// -o, --long-option-flag - /// Some really long help and complex - /// help that makes more sense to be - /// on a line after the option - /// ``` - /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp - pub fn next_line_help(mut self, nlh: bool) -> Self { - if nlh { - self.setb(ArgSettings::NextLineHelp); - } else { - self.unsetb(ArgSettings::NextLineHelp); - } - 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. Duplicate values - /// **are** allowed. 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::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("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::with_name("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 - /// - /// ```notrust - /// cust-ord - /// - /// USAGE: - /// cust-ord [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// -O, --other-option I should be first! - /// -o, --long-option Some help and text - /// ``` - /// [positional arguments]: ./struct.Arg.html#method.index - /// [index]: ./struct.Arg.html#method.index - pub fn display_order(mut self, ord: usize) -> Self { - self.s.disp_ord = ord; - self - } - - /// Indicates that all parameters passed after this should not be parsed - /// individually, but rather passed in their entirety. It is worth noting - /// that setting this requires all values to come after a `--` to indicate they - /// should all be captured. For example: - /// - /// ```notrust - /// --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 [`AppSettings::TrailingVarArg`] - /// may be more appropriate. - /// - /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and - /// [`Arg::last(true)`] when set to `true` - /// - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values - /// [`Arg::last(true)`]: ./struct.Arg.html#method.last - /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg - pub fn raw(self, raw: bool) -> Self { - self.multiple(raw).allow_hyphen_values(raw).last(raw) - } - - /// Hides an argument from short help message output. - /// - /// **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::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden_short_help(true) - /// # ; - /// ``` - /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// - /// However, when --help is called - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - pub fn hidden_short_help(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HiddenShortHelp) - } else { - self.unset(ArgSettings::HiddenShortHelp) - } - } - - /// Hides an argument from long help message output. - /// - /// **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::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden_long_help(true) - /// # ; - /// ``` - /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// - /// However, when -h is called - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - pub fn hidden_long_help(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HiddenLongHelp) - } else { - self.unset(ArgSettings::HiddenLongHelp) - } - } - - /// Checks if one of the [`ArgSettings`] settings is set for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn is_set(&self, s: ArgSettings) -> bool { - self.b.is_set(s) - } - - /// Sets one of the [`ArgSettings`] settings for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn set(mut self, s: ArgSettings) -> Self { - self.setb(s); - self - } - - /// Unsets one of the [`ArgSettings`] settings for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn unset(mut self, s: ArgSettings) -> Self { - self.unsetb(s); - self - } - - #[doc(hidden)] - pub fn setb(&mut self, s: ArgSettings) { - self.b.set(s); - } - - #[doc(hidden)] - pub fn unsetb(&mut self, s: ArgSettings) { - self.b.unset(s); - } -} - -impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> { - fn from(a: &'z Arg<'a, 'b>) -> Self { - Arg { - b: a.b.clone(), - v: a.v.clone(), - s: a.s.clone(), - index: a.index, - r_ifs: a.r_ifs.clone(), - } - } -} - -impl<'n, 'e> PartialEq for Arg<'n, 'e> { - fn eq(&self, other: &Arg<'n, 'e>) -> bool { - self.b == other.b - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/base.rs b/third_party/rust/clap/src/args/arg_builder/base.rs deleted file mode 100644 index ae1a2f6ad1dc..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/base.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::args::{Arg, ArgFlags, ArgSettings}; - -#[derive(Debug, Clone, Default)] -pub struct Base<'a, 'b> -where - 'a: 'b, -{ - pub name: &'a str, - pub help: Option<&'b str>, - pub long_help: Option<&'b str>, - pub blacklist: Option>, - pub settings: ArgFlags, - pub r_unless: Option>, - pub overrides: Option>, - pub groups: Option>, - pub requires: Option, &'a str)>>, -} - -impl<'n, 'e> Base<'n, 'e> { - pub fn new(name: &'n str) -> Self { - Base { - name, - ..Default::default() - } - } - - pub fn set(&mut self, s: ArgSettings) { - self.settings.set(s); - } - pub fn unset(&mut self, s: ArgSettings) { - self.settings.unset(s); - } - pub fn is_set(&self, s: ArgSettings) -> bool { - self.settings.is_set(s) - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - a.b.clone() - } -} - -impl<'n, 'e> PartialEq for Base<'n, 'e> { - fn eq(&self, other: &Base<'n, 'e>) -> bool { - self.name == other.name - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/flag.rs b/third_party/rust/clap/src/args/arg_builder/flag.rs deleted file mode 100644 index e991a6c460d5..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/flag.rs +++ /dev/null @@ -1,216 +0,0 @@ -// Std -use std::{ - convert::From, - ffi::{OsStr, OsString}, - fmt::{Display, Formatter, Result}, - mem, - rc::Rc, - result::Result as StdResult, -}; - -// Internal -use crate::{ - args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched}, - map::{self, VecMap}, -}; - -#[derive(Default, Clone, Debug)] -#[doc(hidden)] -pub struct FlagBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub s: Switched<'e>, -} - -impl<'n, 'e> FlagBuilder<'n, 'e> { - pub fn new(name: &'n str) -> Self { - FlagBuilder { - b: Base::new(name), - ..Default::default() - } - } -} - -impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> { - fn from(a: &'z Arg<'a, 'b>) -> Self { - FlagBuilder { - b: Base::from(a), - s: Switched::from(a), - } - } -} - -impl<'a, 'b> From> for FlagBuilder<'a, 'b> { - fn from(mut a: Arg<'a, 'b>) -> Self { - FlagBuilder { - b: mem::take(&mut a.b), - s: mem::take(&mut a.s), - } - } -} - -impl<'n, 'e> Display for FlagBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - if let Some(l) = self.s.long { - write!(f, "--{}", l)?; - } else { - write!(f, "-{}", self.s.short.unwrap())?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { - fn name(&self) -> &'n str { - self.b.name - } - fn overrides(&self) -> Option<&[&'e str]> { - self.b.overrides.as_ref().map(|o| &o[..]) - } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { - self.b.blacklist.as_ref().map(|o| &o[..]) - } - fn required_unless(&self) -> Option<&[&'e str]> { - self.b.r_unless.as_ref().map(|o| &o[..]) - } - fn is_set(&self, s: ArgSettings) -> bool { - self.b.settings.is_set(s) - } - fn has_switch(&self) -> bool { - true - } - fn takes_value(&self) -> bool { - false - } - fn set(&mut self, s: ArgSettings) { - self.b.settings.set(s) - } - fn max_vals(&self) -> Option { - None - } - fn val_names(&self) -> Option<&VecMap<&'e str>> { - None - } - fn num_vals(&self) -> Option { - None - } - fn possible_vals(&self) -> Option<&[&'e str]> { - None - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { - None - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { - None - } - fn min_vals(&self) -> Option { - None - } - fn short(&self) -> Option { - self.s.short - } - fn long(&self) -> Option<&'e str> { - self.s.long - } - fn val_delim(&self) -> Option { - None - } - fn help(&self) -> Option<&'e str> { - self.b.help - } - fn long_help(&self) -> Option<&'e str> { - self.b.long_help - } - fn val_terminator(&self) -> Option<&'e str> { - None - } - fn default_val(&self) -> Option<&'e OsStr> { - None - } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { - None - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - None - } - fn longest_filter(&self) -> bool { - self.s.long.is_some() - } - fn aliases(&self) -> Option> { - if let Some(ref aliases) = self.s.aliases { - let vis_aliases: Vec<_> = aliases - .iter() - .filter_map(|&(n, v)| if v { Some(n) } else { None }) - .collect(); - if vis_aliases.is_empty() { - None - } else { - Some(vis_aliases) - } - } else { - None - } - } -} - -impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { - self.s.disp_ord - } -} - -impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> { - fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool { - self.b == other.b - } -} - -#[cfg(test)] -mod test { - use super::FlagBuilder; - use crate::args::settings::ArgSettings; - - #[test] - fn flagbuilder_display() { - let mut f = FlagBuilder::new("flg"); - f.b.settings.set(ArgSettings::Multiple); - f.s.long = Some("flag"); - - assert_eq!(&*format!("{}", f), "--flag"); - - let mut f2 = FlagBuilder::new("flg"); - f2.s.short = Some('f'); - - assert_eq!(&*format!("{}", f2), "-f"); - } - - #[test] - fn flagbuilder_display_single_alias() { - let mut f = FlagBuilder::new("flg"); - f.s.long = Some("flag"); - f.s.aliases = Some(vec![("als", true)]); - - assert_eq!(&*format!("{}", f), "--flag"); - } - - #[test] - fn flagbuilder_display_multiple_aliases() { - let mut f = FlagBuilder::new("flg"); - f.s.short = Some('f'); - f.s.aliases = Some(vec![ - ("alias_not_visible", false), - ("f2", true), - ("f3", true), - ("f4", true), - ]); - assert_eq!(&*format!("{}", f), "-f"); - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/mod.rs b/third_party/rust/clap/src/args/arg_builder/mod.rs deleted file mode 100644 index 2d7920819a5e..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub use self::base::Base; -pub use self::flag::FlagBuilder; -pub use self::option::OptBuilder; -pub use self::positional::PosBuilder; -pub use self::switched::Switched; -pub use self::valued::Valued; - -mod base; -mod flag; -mod option; -mod positional; -mod switched; -mod valued; diff --git a/third_party/rust/clap/src/args/arg_builder/option.rs b/third_party/rust/clap/src/args/arg_builder/option.rs deleted file mode 100644 index 3894914f61da..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/option.rs +++ /dev/null @@ -1,295 +0,0 @@ -// Std -use std::{ - ffi::{OsStr, OsString}, - fmt::{Display, Formatter, Result}, - mem, - rc::Rc, - result::Result as StdResult, -}; - -// Internal -use crate::{ - args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued}, - map::{self, VecMap}, - INTERNAL_ERROR_MSG, -}; - -#[allow(missing_debug_implementations)] -#[doc(hidden)] -#[derive(Default, Clone)] -pub struct OptBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub s: Switched<'e>, - pub v: Valued<'n, 'e>, -} - -impl<'n, 'e> OptBuilder<'n, 'e> { - pub fn new(name: &'n str) -> Self { - OptBuilder { - b: Base::new(name), - ..Default::default() - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for OptBuilder<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - OptBuilder { - b: Base::from(a), - s: Switched::from(a), - v: Valued::from(a), - } - } -} - -impl<'n, 'e> From> for OptBuilder<'n, 'e> { - fn from(mut a: Arg<'n, 'e>) -> Self { - a.v.fill_in(); - OptBuilder { - b: mem::take(&mut a.b), - s: mem::take(&mut a.s), - v: mem::take(&mut a.v), - } - } -} - -impl<'n, 'e> Display for OptBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - debugln!("OptBuilder::fmt:{}", self.b.name); - let sep = if self.b.is_set(ArgSettings::RequireEquals) { - "=" - } else { - " " - }; - // Write the name such --long or -l - if let Some(l) = self.s.long { - write!(f, "--{}{}", l, sep)?; - } else { - write!(f, "-{}{}", self.s.short.unwrap(), sep)?; - } - let delim = if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }; - - // Write the values such as - if let Some(ref vec) = self.v.val_names { - let mut it = vec.iter().peekable(); - while let Some((_, val)) = it.next() { - write!(f, "<{}>", val)?; - if it.peek().is_some() { - write!(f, "{}", delim)?; - } - } - let num = vec.len(); - if self.is_set(ArgSettings::Multiple) && num == 1 { - write!(f, "...")?; - } - } else if let Some(num) = self.v.num_vals { - let mut it = (0..num).peekable(); - while let Some(_) = it.next() { - write!(f, "<{}>", self.b.name)?; - if it.peek().is_some() { - write!(f, "{}", delim)?; - } - } - if self.is_set(ArgSettings::Multiple) && num == 1 { - write!(f, "...")?; - } - } else { - write!( - f, - "<{}>{}", - self.b.name, - if self.is_set(ArgSettings::Multiple) { - "..." - } else { - "" - } - )?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { - fn name(&self) -> &'n str { - self.b.name - } - fn overrides(&self) -> Option<&[&'e str]> { - self.b.overrides.as_ref().map(|o| &o[..]) - } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { - self.b.blacklist.as_ref().map(|o| &o[..]) - } - fn required_unless(&self) -> Option<&[&'e str]> { - self.b.r_unless.as_ref().map(|o| &o[..]) - } - fn val_names(&self) -> Option<&VecMap<&'e str>> { - self.v.val_names.as_ref() - } - fn is_set(&self, s: ArgSettings) -> bool { - self.b.settings.is_set(s) - } - fn has_switch(&self) -> bool { - true - } - fn set(&mut self, s: ArgSettings) { - self.b.settings.set(s) - } - fn max_vals(&self) -> Option { - self.v.max_vals - } - fn val_terminator(&self) -> Option<&'e str> { - self.v.terminator - } - fn num_vals(&self) -> Option { - self.v.num_vals - } - fn possible_vals(&self) -> Option<&[&'e str]> { - self.v.possible_vals.as_ref().map(|o| &o[..]) - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { - self.v.validator.as_ref() - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { - self.v.validator_os.as_ref() - } - fn min_vals(&self) -> Option { - self.v.min_vals - } - fn short(&self) -> Option { - self.s.short - } - fn long(&self) -> Option<&'e str> { - self.s.long - } - fn val_delim(&self) -> Option { - self.v.val_delim - } - fn takes_value(&self) -> bool { - true - } - fn help(&self) -> Option<&'e str> { - self.b.help - } - fn long_help(&self) -> Option<&'e str> { - self.b.long_help - } - fn default_val(&self) -> Option<&'e OsStr> { - self.v.default_val - } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { - self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - self.v - .env - .as_ref() - .map(|&(key, ref value)| (key, value.as_ref())) - } - fn longest_filter(&self) -> bool { - true - } - fn aliases(&self) -> Option> { - if let Some(ref aliases) = self.s.aliases { - let vis_aliases: Vec<_> = aliases - .iter() - .filter_map(|&(n, v)| if v { Some(n) } else { None }) - .collect(); - if vis_aliases.is_empty() { - None - } else { - Some(vis_aliases) - } - } else { - None - } - } -} - -impl<'n, 'e> DispOrder for OptBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { - self.s.disp_ord - } -} - -impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> { - fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool { - self.b == other.b - } -} - -#[cfg(test)] -mod test { - use super::OptBuilder; - use crate::{args::settings::ArgSettings, map::VecMap}; - - #[test] - fn optbuilder_display1() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", o), "--option ..."); - } - - #[test] - fn optbuilder_display2() { - let mut v_names = VecMap::new(); - v_names.insert(0, "file"); - v_names.insert(1, "name"); - - let mut o2 = OptBuilder::new("opt"); - o2.s.short = Some('o'); - o2.v.val_names = Some(v_names); - - assert_eq!(&*format!("{}", o2), "-o "); - } - - #[test] - fn optbuilder_display3() { - let mut v_names = VecMap::new(); - v_names.insert(0, "file"); - v_names.insert(1, "name"); - - let mut o2 = OptBuilder::new("opt"); - o2.s.short = Some('o'); - o2.v.val_names = Some(v_names); - o2.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", o2), "-o "); - } - - #[test] - fn optbuilder_display_single_alias() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.s.aliases = Some(vec![("als", true)]); - - assert_eq!(&*format!("{}", o), "--option "); - } - - #[test] - fn optbuilder_display_multiple_aliases() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.s.aliases = Some(vec![ - ("als_not_visible", false), - ("als2", true), - ("als3", true), - ("als4", true), - ]); - assert_eq!(&*format!("{}", o), "--option "); - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/positional.rs b/third_party/rust/clap/src/args/arg_builder/positional.rs deleted file mode 100644 index 9699fb6f50a5..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/positional.rs +++ /dev/null @@ -1,284 +0,0 @@ -// Std -use std::{ - borrow::Cow, - ffi::{OsStr, OsString}, - fmt::{Display, Formatter, Result}, - mem, - rc::Rc, - result::Result as StdResult, -}; - -// Internal -use crate::{ - args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Valued}, - map::{self, VecMap}, - INTERNAL_ERROR_MSG, -}; - -#[allow(missing_debug_implementations)] -#[doc(hidden)] -#[derive(Clone, Default)] -pub struct PosBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub v: Valued<'n, 'e>, - pub index: u64, -} - -impl<'n, 'e> PosBuilder<'n, 'e> { - pub fn new(name: &'n str, idx: u64) -> Self { - PosBuilder { - b: Base::new(name), - index: idx, - ..Default::default() - } - } - - pub fn from_arg_ref(a: &Arg<'n, 'e>, idx: u64) -> Self { - let mut pb = PosBuilder { - b: Base::from(a), - v: Valued::from(a), - index: idx, - }; - if a.v.max_vals.is_some() - || a.v.min_vals.is_some() - || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) - { - pb.b.settings.set(ArgSettings::Multiple); - } - pb - } - - pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self { - if a.v.max_vals.is_some() - || a.v.min_vals.is_some() - || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) - { - a.b.settings.set(ArgSettings::Multiple); - } - PosBuilder { - b: mem::take(&mut a.b), - v: mem::take(&mut a.v), - index: idx, - } - } - - pub fn multiple_str(&self) -> &str { - let mult_vals = self - .v - .val_names - .as_ref() - .map_or(true, |names| names.len() < 2); - if self.is_set(ArgSettings::Multiple) && mult_vals { - "..." - } else { - "" - } - } - - pub fn name_no_brackets(&self) -> Cow { - debugln!("PosBuilder::name_no_brackets;"); - let mut delim = String::new(); - delim.push(if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }); - if let Some(ref names) = self.v.val_names { - debugln!("PosBuilder:name_no_brackets: val_names={:#?}", names); - if names.len() > 1 { - Cow::Owned( - names - .values() - .map(|n| format!("<{}>", n)) - .collect::>() - .join(&*delim), - ) - } else { - Cow::Borrowed(names.values().next().expect(INTERNAL_ERROR_MSG)) - } - } else { - debugln!("PosBuilder:name_no_brackets: just name"); - Cow::Borrowed(self.b.name) - } - } -} - -impl<'n, 'e> Display for PosBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - let mut delim = String::new(); - delim.push(if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }); - if let Some(ref names) = self.v.val_names { - write!( - f, - "{}", - names - .values() - .map(|n| format!("<{}>", n)) - .collect::>() - .join(&*delim) - )?; - } else { - write!(f, "<{}>", self.b.name)?; - } - if self.b.settings.is_set(ArgSettings::Multiple) - && (self.v.val_names.is_none() || self.v.val_names.as_ref().unwrap().len() == 1) - { - write!(f, "...")?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> { - fn name(&self) -> &'n str { - self.b.name - } - fn overrides(&self) -> Option<&[&'e str]> { - self.b.overrides.as_ref().map(|o| &o[..]) - } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { - self.b.blacklist.as_ref().map(|o| &o[..]) - } - fn required_unless(&self) -> Option<&[&'e str]> { - self.b.r_unless.as_ref().map(|o| &o[..]) - } - fn val_names(&self) -> Option<&VecMap<&'e str>> { - self.v.val_names.as_ref() - } - fn is_set(&self, s: ArgSettings) -> bool { - self.b.settings.is_set(s) - } - fn set(&mut self, s: ArgSettings) { - self.b.settings.set(s) - } - fn has_switch(&self) -> bool { - false - } - fn max_vals(&self) -> Option { - self.v.max_vals - } - fn val_terminator(&self) -> Option<&'e str> { - self.v.terminator - } - fn num_vals(&self) -> Option { - self.v.num_vals - } - fn possible_vals(&self) -> Option<&[&'e str]> { - self.v.possible_vals.as_ref().map(|o| &o[..]) - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { - self.v.validator.as_ref() - } - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { - self.v.validator_os.as_ref() - } - fn min_vals(&self) -> Option { - self.v.min_vals - } - fn short(&self) -> Option { - None - } - fn long(&self) -> Option<&'e str> { - None - } - fn val_delim(&self) -> Option { - self.v.val_delim - } - fn takes_value(&self) -> bool { - true - } - fn help(&self) -> Option<&'e str> { - self.b.help - } - fn long_help(&self) -> Option<&'e str> { - self.b.long_help - } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { - self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) - } - fn default_val(&self) -> Option<&'e OsStr> { - self.v.default_val - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - self.v - .env - .as_ref() - .map(|&(key, ref value)| (key, value.as_ref())) - } - fn longest_filter(&self) -> bool { - true - } - fn aliases(&self) -> Option> { - None - } -} - -impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { - self.index as usize - } -} - -impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> { - fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool { - self.b == other.b - } -} - -#[cfg(test)] -mod test { - use super::PosBuilder; - use crate::{args::settings::ArgSettings, map::VecMap}; - - #[test] - fn display_mult() { - let mut p = PosBuilder::new("pos", 1); - p.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", p), "..."); - } - - #[test] - fn display_required() { - let mut p2 = PosBuilder::new("pos", 1); - p2.b.settings.set(ArgSettings::Required); - - assert_eq!(&*format!("{}", p2), ""); - } - - #[test] - fn display_val_names() { - let mut p2 = PosBuilder::new("pos", 1); - let mut vm = VecMap::new(); - vm.insert(0, "file1"); - vm.insert(1, "file2"); - p2.v.val_names = Some(vm); - - assert_eq!(&*format!("{}", p2), " "); - } - - #[test] - fn display_val_names_req() { - let mut p2 = PosBuilder::new("pos", 1); - p2.b.settings.set(ArgSettings::Required); - let mut vm = VecMap::new(); - vm.insert(0, "file1"); - vm.insert(1, "file2"); - p2.v.val_names = Some(vm); - - assert_eq!(&*format!("{}", p2), " "); - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/switched.rs b/third_party/rust/clap/src/args/arg_builder/switched.rs deleted file mode 100644 index 78af669aff7c..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/switched.rs +++ /dev/null @@ -1,40 +0,0 @@ -use crate::Arg; - -#[derive(Debug)] -pub struct Switched<'b> { - pub short: Option, - pub long: Option<&'b str>, - pub aliases: Option>, // (name, visible) - pub disp_ord: usize, - pub unified_ord: usize, -} - -impl<'e> Default for Switched<'e> { - fn default() -> Self { - Switched { - short: None, - long: None, - aliases: None, - disp_ord: 999, - unified_ord: 999, - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - a.s.clone() - } -} - -impl<'e> Clone for Switched<'e> { - fn clone(&self) -> Self { - Switched { - short: self.short, - long: self.long, - aliases: self.aliases.clone(), - disp_ord: self.disp_ord, - unified_ord: self.unified_ord, - } - } -} diff --git a/third_party/rust/clap/src/args/arg_builder/valued.rs b/third_party/rust/clap/src/args/arg_builder/valued.rs deleted file mode 100644 index ae659f7ed77c..000000000000 --- a/third_party/rust/clap/src/args/arg_builder/valued.rs +++ /dev/null @@ -1,70 +0,0 @@ -use std::{ - ffi::{OsStr, OsString}, - rc::Rc, -}; - -use crate::{map::VecMap, Arg}; - -#[allow(missing_debug_implementations)] -#[derive(Clone)] -pub struct Valued<'a, 'b> -where - 'a: 'b, -{ - pub possible_vals: Option>, - pub val_names: Option>, - pub num_vals: Option, - pub max_vals: Option, - pub min_vals: Option, - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - pub validator: Option Result<(), String>>>, - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - pub validator_os: Option Result<(), OsString>>>, - pub val_delim: Option, - pub default_val: Option<&'b OsStr>, - #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] - pub default_vals_ifs: Option, &'b OsStr)>>, - pub env: Option<(&'a OsStr, Option)>, - pub terminator: Option<&'b str>, -} - -impl<'n, 'e> Default for Valued<'n, 'e> { - fn default() -> Self { - Valued { - possible_vals: None, - num_vals: None, - min_vals: None, - max_vals: None, - val_names: None, - validator: None, - validator_os: None, - val_delim: None, - default_val: None, - default_vals_ifs: None, - env: None, - terminator: None, - } - } -} - -impl<'n, 'e> Valued<'n, 'e> { - pub fn fill_in(&mut self) { - if let Some(ref vec) = self.val_names { - if vec.len() > 1 { - self.num_vals = Some(vec.len() as u64); - } - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Valued<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - let mut v = a.v.clone(); - if let Some(ref vec) = a.v.val_names { - if vec.len() > 1 { - v.num_vals = Some(vec.len() as u64); - } - } - v - } -} diff --git a/third_party/rust/clap/src/args/arg_matcher.rs b/third_party/rust/clap/src/args/arg_matcher.rs deleted file mode 100644 index 5034dcc08207..000000000000 --- a/third_party/rust/clap/src/args/arg_matcher.rs +++ /dev/null @@ -1,274 +0,0 @@ -// Std -use std::{ - collections::{ - hash_map::{Entry, Iter}, - HashMap, - }, - ffi::OsStr, - mem, - ops::Deref, -}; - -// Internal -use crate::args::{settings::ArgSettings, AnyArg, ArgMatches, MatchedArg, SubCommand}; - -#[doc(hidden)] -#[allow(missing_debug_implementations)] -pub struct ArgMatcher<'a>(pub ArgMatches<'a>); - -impl<'a> Default for ArgMatcher<'a> { - fn default() -> Self { - ArgMatcher(ArgMatches::default()) - } -} - -impl<'a> ArgMatcher<'a> { - pub fn new() -> Self { - ArgMatcher::default() - } - - pub fn process_arg_overrides<'b>( - &mut self, - a: Option<&AnyArg<'a, 'b>>, - overrides: &mut Vec<(&'b str, &'a str)>, - required: &mut Vec<&'a str>, - check_all: bool, - ) { - debugln!( - "ArgMatcher::process_arg_overrides:{:?};", - a.map_or(None, |a| Some(a.name())) - ); - if let Some(aa) = a { - let mut self_done = false; - if let Some(a_overrides) = aa.overrides() { - for overr in a_overrides { - debugln!("ArgMatcher::process_arg_overrides:iter:{};", overr); - if overr == &aa.name() { - self_done = true; - self.handle_self_overrides(a); - } else if self.is_present(overr) { - debugln!( - "ArgMatcher::process_arg_overrides:iter:{}: removing from matches;", - overr - ); - self.remove(overr); - for i in (0..required.len()).rev() { - if &required[i] == overr { - debugln!( - "ArgMatcher::process_arg_overrides:iter:{}: removing required;", - overr - ); - required.swap_remove(i); - break; - } - } - overrides.push((overr, aa.name())); - } else { - overrides.push((overr, aa.name())); - } - } - } - if check_all && !self_done { - self.handle_self_overrides(a); - } - } - } - - pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) { - debugln!( - "ArgMatcher::handle_self_overrides:{:?};", - a.map_or(None, |a| Some(a.name())) - ); - if let Some(aa) = a { - if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) { - // positional args can't override self or else we would never advance to the next - - // Also flags with --multiple set are ignored otherwise we could never have more - // than one - return; - } - if let Some(ma) = self.get_mut(aa.name()) { - if ma.vals.len() > 1 { - // swap_remove(0) would be O(1) but does not preserve order, which - // we need - ma.vals.remove(0); - ma.occurs = 1; - } else if !aa.takes_value() && ma.occurs > 1 { - ma.occurs = 1; - } - } - } - } - - pub fn is_present(&self, name: &str) -> bool { - self.0.is_present(name) - } - - pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) { - debugln!( - "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: &[&'a str], - vals_map: &mut HashMap<&'a str, MatchedArg>, - ) { - 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`, however the occurs will be 0. - let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { - if parent_ma.occurs > 0 && ma.occurs == 0 { - parent_ma.clone() - } else { - ma.clone() - } - } else { - ma.clone() - }; - vals_map.insert(global_arg, to_update); - } - } - if let Some(ref mut sc) = self.0.subcommand { - let mut am = ArgMatcher(mem::replace(&mut sc.matches, ArgMatches::new())); - am.fill_in_global_values(global_arg_vec, vals_map); - mem::swap(&mut am.0, &mut sc.matches); - } - - for (name, matched_arg) in vals_map.iter_mut() { - self.0.args.insert(name, matched_arg.clone()); - } - } - - pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> { - self.0.args.get_mut(arg) - } - - pub fn get(&self, arg: &str) -> Option<&MatchedArg> { - self.0.args.get(arg) - } - - pub fn remove(&mut self, arg: &str) { - self.0.args.remove(arg); - } - - pub fn remove_all(&mut self, args: &[&str]) { - for &arg in args { - self.0.args.remove(arg); - } - } - - pub fn insert(&mut self, name: &'a str) { - self.0.args.insert(name, MatchedArg::new()); - } - - pub fn contains(&self, arg: &str) -> bool { - self.0.args.contains_key(arg) - } - - pub fn is_empty(&self) -> bool { - self.0.args.is_empty() - } - - pub fn usage(&mut self, usage: String) { - self.0.usage = Some(usage); - } - - pub fn arg_names(&'a self) -> Vec<&'a str> { - self.0.args.keys().map(Deref::deref).collect() - } - - pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> { - self.0.args.entry(arg) - } - - pub fn subcommand(&mut self, sc: SubCommand<'a>) { - self.0.subcommand = Some(Box::new(sc)); - } - - pub fn subcommand_name(&self) -> Option<&str> { - self.0.subcommand_name() - } - - pub fn iter(&self) -> Iter<&str, MatchedArg> { - self.0.args.iter() - } - - pub fn inc_occurrence_of(&mut self, arg: &'a str) { - debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg); - if let Some(a) = self.get_mut(arg) { - a.occurs += 1; - return; - } - debugln!("ArgMatcher::inc_occurrence_of: first instance"); - self.insert(arg); - } - - pub fn inc_occurrences_of(&mut self, args: &[&'a str]) { - debugln!("ArgMatcher::inc_occurrences_of: args={:?}", args); - for arg in args { - self.inc_occurrence_of(arg); - } - } - - pub fn add_val_to(&mut self, arg: &'a str, val: &OsStr) { - let ma = self.entry(arg).or_insert(MatchedArg { - occurs: 0, - indices: Vec::with_capacity(1), - vals: Vec::with_capacity(1), - }); - ma.vals.push(val.to_owned()); - } - - pub fn add_index_to(&mut self, arg: &'a str, idx: usize) { - let ma = self.entry(arg).or_insert(MatchedArg { - occurs: 0, - indices: Vec::with_capacity(1), - vals: Vec::new(), - }); - ma.indices.push(idx); - } - - pub fn needs_more_vals<'b, A>(&self, o: &A) -> bool - where - A: AnyArg<'a, 'b>, - { - debugln!("ArgMatcher::needs_more_vals: o={}", o.name()); - if let Some(ma) = self.get(o.name()) { - if let Some(num) = o.num_vals() { - debugln!("ArgMatcher::needs_more_vals: num_vals...{}", num); - return if o.is_set(ArgSettings::Multiple) { - ((ma.vals.len() as u64) % num) != 0 - } else { - num != (ma.vals.len() as u64) - }; - } else if let Some(num) = o.max_vals() { - debugln!("ArgMatcher::needs_more_vals: max_vals...{}", num); - return (ma.vals.len() as u64) <= num; - } else if o.min_vals().is_some() { - debugln!("ArgMatcher::needs_more_vals: min_vals...true"); - return true; - } - return o.is_set(ArgSettings::Multiple); - } - true - } -} - -// Not changing to From just to not deal with possible breaking changes on v2 since v3 is coming -// in the future anyways -#[cfg_attr(feature = "cargo-clippy", allow(clippy::from_over_into))] -impl<'a> Into> for ArgMatcher<'a> { - fn into(self) -> ArgMatches<'a> { - self.0 - } -} diff --git a/third_party/rust/clap/src/args/arg_matches.rs b/third_party/rust/clap/src/args/arg_matches.rs deleted file mode 100644 index a2c3231ae0d8..000000000000 --- a/third_party/rust/clap/src/args/arg_matches.rs +++ /dev/null @@ -1,1001 +0,0 @@ -// Std -use std::{ - borrow::Cow, - collections::HashMap, - ffi::{OsStr, OsString}, - iter::Map, - slice::Iter, -}; - -// Internal -use crate::{ - args::{MatchedArg, SubCommand}, - INVALID_UTF8, -}; - -/// 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 [`App::get_matches`] family of -/// methods. -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{App, Arg}; -/// let matches = App::new("MyApp") -/// .arg(Arg::with_name("out") -/// .long("output") -/// .required(true) -/// .takes_value(true)) -/// .arg(Arg::with_name("debug") -/// .short("d") -/// .multiple(true)) -/// .arg(Arg::with_name("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::value_of -/// if let Some(c) = matches.value_of("cfg") { -/// println!("Value for -c: {}", c); -/// } -/// -/// // The ArgMatches::value_of 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.value_of("out").unwrap()); -/// -/// // You can check the presence of an argument -/// if matches.is_present("out") { -/// // Another way to check if an argument was present, or if it occurred multiple times is to -/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the -/// // number of times that it occurred, if it was. To allow an argument to appear more than -/// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0. -/// if matches.occurrences_of("debug") > 2 { -/// println!("Debug mode is REALLY on, don't be crazy"); -/// } else { -/// println!("Debug mode kind of on"); -/// } -/// } -/// ``` -/// [`App::get_matches`]: ./struct.App.html#method.get_matches -#[derive(Debug, Clone)] -pub struct ArgMatches<'a> { - #[doc(hidden)] - pub args: HashMap<&'a str, MatchedArg>, - #[doc(hidden)] - pub subcommand: Option>>, - #[doc(hidden)] - pub usage: Option, -} - -impl<'a> Default for ArgMatches<'a> { - fn default() -> Self { - ArgMatches { - args: HashMap::new(), - subcommand: None, - usage: None, - } - } -} - -impl<'a> ArgMatches<'a> { - #[doc(hidden)] - pub fn new() -> Self { - ArgMatches { - ..Default::default() - } - } - - /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes - /// an additional value at runtime). If the option wasn't present at runtime - /// it returns `None`. - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first* - /// value. - /// - /// # Panics - /// - /// This method will [`panic!`] if the value contains invalid UTF-8 code points. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("output") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "something"]); - /// - /// assert_eq!(m.value_of("output"), Some("something")); - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [positional]: ./struct.Arg.html#method.index - /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - pub fn value_of>(&self, name: S) -> Option<&str> { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(v) = arg.vals.get(0) { - return Some(v.to_str().expect(INVALID_UTF8)); - } - } - None - } - - /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime - /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those - /// invalid points will be replaced with `\u{FFFD}` - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage(" 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi {0xe9}!" - /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); - /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!"); - /// ``` - /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy - pub fn value_of_lossy>(&'a self, name: S) -> Option> { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(v) = arg.vals.get(0) { - return Some(v.to_string_lossy()); - } - } - None - } - - /// Gets the OS version of a string value of a specific argument. If the option wasn't present - /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes, - /// regardless of whether or not they contain valid UTF-8 code points. 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 code points. - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first* - /// value. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage(" 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi {0xe9}!" - /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); - /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os - pub fn value_of_os>(&self, name: S) -> Option<&OsStr> { - self.args - .get(name.as_ref()) - .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str())) - } - - /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument - /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at - /// runtime it returns `None` - /// - /// # Panics - /// - /// This method will panic if any of the values contain invalid UTF-8 code points. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("output") - /// .multiple(true) - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "myprog", "-o", "val1", "val2", "val3" - /// ]); - /// let vals: Vec<&str> = m.values_of("output").unwrap().collect(); - /// assert_eq!(vals, ["val1", "val2", "val3"]); - /// ``` - /// [`Values`]: ./struct.Values.html - /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html - pub fn values_of>(&'a self, name: S) -> Option> { - if let Some(arg) = self.args.get(name.as_ref()) { - fn to_str_slice(o: &OsString) -> &str { - o.to_str().expect(INVALID_UTF8) - } - let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer - return Some(Values { - iter: arg.vals.iter().map(to_str_slice), - }); - } - None - } - - /// Gets the lossy values of a specific argument. If the option wasn't present at runtime - /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points, - /// those invalid points will be replaced with `\u{FFFD}` - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::OsStringExt; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("... 'some arg'")) - /// .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.values_of_lossy("arg").unwrap().into_iter(); - /// assert_eq!(&itr.next().unwrap()[..], "Hi"); - /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); - /// assert_eq!(itr.next(), None); - /// ``` - pub fn values_of_lossy>(&'a self, name: S) -> Option> { - if let Some(arg) = self.args.get(name.as_ref()) { - return Some( - arg.vals - .iter() - .map(|v| v.to_string_lossy().into_owned()) - .collect(), - ); - } - None - } - - /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a - /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value - /// on Unix-like systems is any series of bytes, regardless of whether or not they contain - /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid - /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::{OsStr,OsString}; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("... 'some arg'")) - /// .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.values_of_os("arg").unwrap().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); - /// ``` - /// [`OsValues`]: ./struct.OsValues.html - /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html - /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - pub fn values_of_os>(&'a self, name: S) -> Option> { - fn to_str_slice(o: &OsString) -> &OsStr { - &*o - } - let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer - if let Some(arg) = self.args.get(name.as_ref()) { - return Some(OsValues { - iter: arg.vals.iter().map(to_str_slice), - }); - } - None - } - - /// Returns `true` if an argument was present at runtime, otherwise `false`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert!(m.is_present("debug")); - /// ``` - pub fn is_present>(&self, name: S) -> bool { - if let Some(ref sc) = self.subcommand { - if sc.name == name.as_ref() { - return true; - } - } - self.args.contains_key(name.as_ref()) - } - - /// Returns the number of times an argument was used at runtime. If an argument isn't present - /// it will return `0`. - /// - /// **NOTE:** This returns the number of times the argument was used, *not* the number of - /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4 - /// values). - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d") - /// .multiple(true)) - /// .get_matches_from(vec![ - /// "myprog", "-d", "-d", "-d" - /// ]); - /// - /// assert_eq!(m.occurrences_of("debug"), 3); - /// ``` - /// - /// This next example shows that counts actual uses of the argument, not just `-`'s - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d") - /// .multiple(true)) - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .get_matches_from(vec![ - /// "myprog", "-ddfd" - /// ]); - /// - /// assert_eq!(m.occurrences_of("debug"), 3); - /// assert_eq!(m.occurrences_of("flag"), 1); - /// ``` - pub fn occurrences_of>(&self, name: S) -> u64 { - self.args.get(name.as_ref()).map_or(0, |a| a.occurs) - } - - /// Gets the starting index of the argument in respect to all other arguments. 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 descrepancy, the primary difference between an argv index and clap - /// index, is that clap continues counting once all arguments have properly seperated, 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. - /// - /// # 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 becuase it's not saved in - /// in an `ArgMatches` struct for querying. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); - /// // ARGV idices: ^0 ^1 ^2 ^3 - /// // clap idices: ^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::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); - /// // ARGV idices: ^0 ^1 ^2 - /// // clap idices: ^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::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("flag2") - /// .short("F")) - /// .arg(Arg::with_name("flag3") - /// .short("z")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); - /// // ARGV idices: ^0 ^1 ^2 - /// // clap idices: ^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::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("flag2") - /// .short("F")) - /// .arg(Arg::with_name("flag3") - /// .short("z")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-fzFoval"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^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::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^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)); - /// ``` - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [delimiter]: ./struct.Arg.html#method.value_delimiter - pub fn index_of>(&self, name: S) -> Option { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(i) = arg.indices.get(0) { - return Some(*i); - } - } - None - } - - /// Gets all indices of the argument in respect to all other arguments. 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 compare to argv indices, see - /// [`ArgMatches::index_of`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .use_delimiter(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^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::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .arg(Arg::with_name("flag") - /// .short("f") - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); - /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 - /// // clap idices: ^2 ^3 ^5 ^6 - /// - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 5]); - /// assert_eq!(m.indices_of("flag").unwrap().collect::>(), &[3, 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 case they'd only receive a - /// single index. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^2 - /// // - /// // clap sees the above as 'myapp -o "val1,val2,val3"' - /// // ^0 ^1 ^2 - /// assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2]); - /// ``` - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of - /// [delimiter]: ./struct.Arg.html#method.value_delimiter - pub fn indices_of>(&'a self, name: S) -> Option> { - if let Some(arg) = self.args.get(name.as_ref()) { - fn to_usize(i: &usize) -> usize { - *i - } - let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer - return Some(Indices { - iter: arg.indices.iter().map(to_usize), - }); - } - None - } - - /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] - /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if - /// the subcommand wasn't present at runtime. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .subcommand(SubCommand::with_name("test") - /// .arg(Arg::with_name("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.is_present("debug")); - /// - /// // 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.value_of("opt"), Some("val")); - /// } - /// ``` - /// [`Subcommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - /// [`ArgMatches`]: ./struct.ArgMatches.html - pub fn subcommand_matches>(&self, name: S) -> Option<&ArgMatches<'a>> { - if let Some(ref s) = self.subcommand { - if s.name == name.as_ref() { - return Some(&s.matches); - } - } - None - } - - /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] - /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know - /// which subcommand was actually used. This method returns the name of the subcommand that was - /// used at runtime, or `None` if one wasn't. - /// - /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime, - /// but only a single subcommand from any group of sibling commands may used at once. - /// - /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as - /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is - /// aware these aren't actually all subcommands in the real `git` interface, but it makes - /// explanation easier) - /// - /// ```notrust - /// Top Level App (git) TOP - /// | - /// ----------------------------------------- - /// / | \ \ - /// clone push add commit LEVEL 1 - /// | / \ / \ | - /// url origin remote ref name message LEVEL 2 - /// / /\ - /// path remote local LEVEL 3 - /// ``` - /// - /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all - /// inclusive list, and not including argument options per command for brevity and clarity): - /// - /// ```sh - /// $ git clone url - /// $ git push origin path - /// $ git add ref local - /// $ git commit message - /// ``` - /// - /// Notice only one command per "level" may be used. You could not, for example, do `$ git - /// clone url push origin path` - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("git") - /// .subcommand(SubCommand::with_name("clone")) - /// .subcommand(SubCommand::with_name("push")) - /// .subcommand(SubCommand::with_name("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`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - /// [`ArgMatches`]: ./struct.ArgMatches.html - pub fn subcommand_name(&self) -> Option<&str> { - self.subcommand.as_ref().map(|sc| &sc.name[..]) - } - - /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`] - /// by returning a tuple with both pieces of information. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("git") - /// .subcommand(SubCommand::with_name("clone")) - /// .subcommand(SubCommand::with_name("push")) - /// .subcommand(SubCommand::with_name("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand() { - /// ("clone", Some(sub_m)) => {}, // clone was used - /// ("push", Some(sub_m)) => {}, // push was used - /// ("commit", Some(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::{App, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let app_m = App::new("myprog") - /// .setting(AppSettings::AllowExternalSubcommands) - /// .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() { - /// (external, Some(sub_m)) => { - /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches - /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name - pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) { - self.subcommand - .as_ref() - .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches))) - } - - /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches(); - /// - /// println!("{}", app_m.usage()); - /// ``` - /// [`Subcommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - pub fn usage(&self) -> &str { - self.usage.as_ref().map_or("", |u| &u[..]) - } -} - -// The following were taken and adapated from vec_map source -// repo: https://github.com/contain-rs/vec-map -// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 -// license: MIT - Copyright (c) 2015 The Rust Project Developers - -/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`] -/// method. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg}; -/// let m = App::new("myapp") -/// .arg(Arg::with_name("output") -/// .short("o") -/// .multiple(true) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); -/// -/// let mut values = m.values_of("output").unwrap(); -/// -/// assert_eq!(values.next(), Some("val1")); -/// assert_eq!(values.next(), Some("val2")); -/// assert_eq!(values.next(), None); -/// ``` -/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of -#[derive(Debug, Clone)] -pub struct Values<'a> { - iter: Map, fn(&'a OsString) -> &'a str>, -} - -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.iter.size_hint() - } -} - -impl<'a> DoubleEndedIterator for Values<'a> { - fn next_back(&mut self) -> Option<&'a str> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for Values<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for Values<'a> { - fn default() -> Self { - static EMPTY: [OsString; 0] = []; - // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &str { - unreachable!() - } - Values { - iter: EMPTY[..].iter().map(to_str_slice), - } - } -} - -/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`] -/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike -/// [`Values`]. -/// -/// # Examples -/// -#[cfg_attr(not(unix), doc = " ```ignore")] -#[cfg_attr(unix, doc = " ```")] -/// # use clap::{App, Arg}; -/// use std::ffi::OsString; -/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; -/// -/// let m = App::new("utf8") -/// .arg(Arg::from_usage(" 'some arg'")) -/// .get_matches_from(vec![OsString::from("myprog"), -/// // "Hi {0xe9}!" -/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); -/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); -/// ``` -/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os -/// [`Values`]: ./struct.Values.html -#[derive(Debug, Clone)] -pub struct OsValues<'a> { - iter: Map, fn(&'a OsString) -> &'a OsStr>, -} - -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.iter.size_hint() - } -} - -impl<'a> DoubleEndedIterator for OsValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for OsValues<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for OsValues<'a> { - fn default() -> Self { - static EMPTY: [OsString; 0] = []; - // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &OsStr { - unreachable!() - } - OsValues { - iter: EMPTY[..].iter().map(to_str_slice), - } - } -} - -/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`] -/// method. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg}; -/// let m = App::new("myapp") -/// .arg(Arg::with_name("output") -/// .short("o") -/// .multiple(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`]: ./struct.ArgMatches.html#method.indices_of -#[derive(Debug, Clone)] -pub struct Indices<'a> { - // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469 - iter: Map, fn(&'a usize) -> 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.iter.size_hint() - } -} - -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: - fn to_usize(_: &usize) -> usize { - unreachable!() - } - Indices { - iter: EMPTY[..].iter().map(to_usize), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_default_values() { - let mut values: Values = Values::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_values_with_shorter_lifetime() { - let matches = ArgMatches::new(); - let mut values = matches.values_of("").unwrap_or_default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_osvalues() { - let mut values: OsValues = OsValues::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_osvalues_with_shorter_lifetime() { - let matches = ArgMatches::new(); - let mut values = matches.values_of_os("").unwrap_or_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::new(); - let mut indices = matches.indices_of("").unwrap_or_default(); - assert_eq!(indices.next(), None); - } -} diff --git a/third_party/rust/clap/src/args/matched_arg.rs b/third_party/rust/clap/src/args/matched_arg.rs deleted file mode 100644 index 681e5d2aa765..000000000000 --- a/third_party/rust/clap/src/args/matched_arg.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Std -use std::ffi::OsString; - -#[doc(hidden)] -#[derive(Debug, Clone)] -pub struct MatchedArg { - #[doc(hidden)] - pub occurs: u64, - #[doc(hidden)] - pub indices: Vec, - #[doc(hidden)] - pub vals: Vec, -} - -impl Default for MatchedArg { - fn default() -> Self { - MatchedArg { - occurs: 1, - indices: Vec::new(), - vals: Vec::new(), - } - } -} - -impl MatchedArg { - pub fn new() -> Self { - MatchedArg::default() - } -} diff --git a/third_party/rust/clap/src/args/mod.rs b/third_party/rust/clap/src/args/mod.rs deleted file mode 100644 index 8f076ea5c293..000000000000 --- a/third_party/rust/clap/src/args/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub use self::any_arg::{AnyArg, DispOrder}; -pub use self::arg::Arg; -pub use self::arg_builder::{Base, FlagBuilder, OptBuilder, PosBuilder, Switched, Valued}; -pub use self::arg_matcher::ArgMatcher; -pub use self::arg_matches::{ArgMatches, OsValues, Values}; -pub use self::group::ArgGroup; -pub use self::matched_arg::MatchedArg; -pub use self::settings::{ArgFlags, ArgSettings}; -pub use self::subcommand::SubCommand; - -#[macro_use] -mod macros; -pub mod any_arg; -mod arg; -mod arg_builder; -mod arg_matcher; -mod arg_matches; -mod group; -mod matched_arg; -pub mod settings; -mod subcommand; diff --git a/third_party/rust/clap/src/args/settings.rs b/third_party/rust/clap/src/args/settings.rs deleted file mode 100644 index 833a1eafefa3..000000000000 --- a/third_party/rust/clap/src/args/settings.rs +++ /dev/null @@ -1,237 +0,0 @@ -// Std -#[allow(deprecated, unused_imports)] -use std::ascii::AsciiExt; -use std::str::FromStr; - -bitflags! { - struct Flags: u32 { - const REQUIRED = 1; - const MULTIPLE = 1 << 1; - const 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 R_UNLESS_ALL = 1 << 8; - 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; - const HIDE_ENV_VALS = 1 << 17; - const HIDDEN_SHORT_H = 1 << 18; - const HIDDEN_LONG_H = 1 << 19; - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Copy)] -pub struct ArgFlags(Flags); - -impl ArgFlags { - pub fn new() -> Self { - ArgFlags::default() - } - - impl_settings! {ArgSettings, - Required => Flags::REQUIRED, - Multiple => Flags::MULTIPLE, - EmptyValues => Flags::EMPTY_VALS, - Global => Flags::GLOBAL, - Hidden => Flags::HIDDEN, - TakesValue => Flags::TAKES_VAL, - UseValueDelimiter => Flags::USE_DELIM, - NextLineHelp => Flags::NEXT_LINE_HELP, - RequiredUnlessAll => Flags::R_UNLESS_ALL, - RequireDelimiter => Flags::REQ_DELIM, - ValueDelimiterNotSet => Flags::DELIM_NOT_SET, - HidePossibleValues => Flags::HIDE_POS_VALS, - AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, - RequireEquals => Flags::REQUIRE_EQUALS, - Last => Flags::LAST, - CaseInsensitive => Flags::CASE_INSENSITIVE, - HideEnvValues => Flags::HIDE_ENV_VALS, - HideDefaultValue => Flags::HIDE_DEFAULT_VAL, - HiddenShortHelp => Flags::HIDDEN_SHORT_H, - HiddenLongHelp => Flags::HIDDEN_LONG_H - } -} - -impl Default for ArgFlags { - fn default() -> Self { - ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET) - } -} - -/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter -/// methods [`Arg::set`], [`Arg::unset`], and [`Arg::is_set`] -/// -/// [`Arg::set`]: ./struct.Arg.html#method.set -/// [`Arg::unset`]: ./struct.Arg.html#method.unset -/// [`Arg::is_set`]: ./struct.Arg.html#method.is_set -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum ArgSettings { - /// The argument must be used - Required, - /// The argument may be used multiple times such as `--flag --flag` - Multiple, - /// The argument allows empty values such as `--option ""` - EmptyValues, - /// The argument should be propagated down through all child [`SubCommand`]s - /// - /// [`SubCommand`]: ./struct.SubCommand.html - Global, - /// The argument should **not** be shown in help text - Hidden, - /// The argument accepts a value, such as `--option ` - TakesValue, - /// Determines if the argument allows values to be grouped via a delimiter - UseValueDelimiter, - /// Prints the help text on the line after the argument - NextLineHelp, - /// Requires the use of a value delimiter for all multiple values - RequireDelimiter, - /// Hides the possible values from the help string - HidePossibleValues, - /// Allows vals that start with a '-' - AllowLeadingHyphen, - /// Require options use `--option=val` syntax - RequireEquals, - /// Specifies that the arg is the last positional argument and may be accessed early via `--` - /// syntax - Last, - /// Hides the default value from the help string - HideDefaultValue, - /// Makes `Arg::possible_values` case insensitive - CaseInsensitive, - /// Hides ENV values in the help message - HideEnvValues, - /// The argument should **not** be shown in short help text - HiddenShortHelp, - /// The argument should **not** be shown in long help text - HiddenLongHelp, - #[doc(hidden)] - RequiredUnlessAll, - #[doc(hidden)] - ValueDelimiterNotSet, -} - -impl FromStr for ArgSettings { - type Err = String; - fn from_str(s: &str) -> Result::Err> { - match &*s.to_ascii_lowercase() { - "required" => Ok(ArgSettings::Required), - "multiple" => Ok(ArgSettings::Multiple), - "global" => Ok(ArgSettings::Global), - "emptyvalues" => Ok(ArgSettings::EmptyValues), - "hidden" => Ok(ArgSettings::Hidden), - "takesvalue" => Ok(ArgSettings::TakesValue), - "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), - "nextlinehelp" => Ok(ArgSettings::NextLineHelp), - "requiredunlessall" => Ok(ArgSettings::RequiredUnlessAll), - "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), - "valuedelimiternotset" => Ok(ArgSettings::ValueDelimiterNotSet), - "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), - "allowleadinghyphen" => Ok(ArgSettings::AllowLeadingHyphen), - "requireequals" => Ok(ArgSettings::RequireEquals), - "last" => Ok(ArgSettings::Last), - "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), - "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), - "hideenvvalues" => Ok(ArgSettings::HideEnvValues), - "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), - "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), - _ => Err("unknown ArgSetting, cannot convert from str".to_owned()), - } - } -} - -#[cfg(test)] -mod test { - use super::ArgSettings; - - #[test] - fn arg_settings_fromstr() { - assert_eq!( - "allowleadinghyphen".parse::().unwrap(), - ArgSettings::AllowLeadingHyphen - ); - assert_eq!( - "emptyvalues".parse::().unwrap(), - ArgSettings::EmptyValues - ); - assert_eq!( - "global".parse::().unwrap(), - ArgSettings::Global - ); - assert_eq!( - "hidepossiblevalues".parse::().unwrap(), - ArgSettings::HidePossibleValues - ); - assert_eq!( - "hidden".parse::().unwrap(), - ArgSettings::Hidden - ); - assert_eq!( - "multiple".parse::().unwrap(), - ArgSettings::Multiple - ); - assert_eq!( - "nextlinehelp".parse::().unwrap(), - ArgSettings::NextLineHelp - ); - assert_eq!( - "requiredunlessall".parse::().unwrap(), - ArgSettings::RequiredUnlessAll - ); - 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!( - "valuedelimiternotset".parse::().unwrap(), - ArgSettings::ValueDelimiterNotSet - ); - assert_eq!( - "requireequals".parse::().unwrap(), - ArgSettings::RequireEquals - ); - assert_eq!("last".parse::().unwrap(), ArgSettings::Last); - assert_eq!( - "hidedefaultvalue".parse::().unwrap(), - ArgSettings::HideDefaultValue - ); - assert_eq!( - "caseinsensitive".parse::().unwrap(), - ArgSettings::CaseInsensitive - ); - assert_eq!( - "hideenvvalues".parse::().unwrap(), - ArgSettings::HideEnvValues - ); - assert_eq!( - "hiddenshorthelp".parse::().unwrap(), - ArgSettings::HiddenShortHelp - ); - assert_eq!( - "hiddenlonghelp".parse::().unwrap(), - ArgSettings::HiddenLongHelp - ); - assert!("hahahaha".parse::().is_err()); - } -} diff --git a/third_party/rust/clap/src/args/subcommand.rs b/third_party/rust/clap/src/args/subcommand.rs deleted file mode 100644 index 8ad1c0ed96d9..000000000000 --- a/third_party/rust/clap/src/args/subcommand.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Third Party -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -// Internal -use crate::{App, ArgMatches}; - -/// The abstract representation of a command line subcommand. -/// -/// This struct describes all the valid options of the subcommand for the program. Subcommands are -/// essentially "sub-[`App`]s" and contain all the same possibilities (such as their own -/// [arguments], subcommands, and settings). -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg, SubCommand}; -/// App::new("myprog") -/// .subcommand( -/// SubCommand::with_name("config") -/// .about("Used for configuration") -/// .arg(Arg::with_name("config_file") -/// .help("The configuration file to use") -/// .index(1))) -/// # ; -/// ``` -/// [`App`]: ./struct.App.html -/// [arguments]: ./struct.Arg.html -#[derive(Debug, Clone)] -pub struct SubCommand<'a> { - #[doc(hidden)] - pub name: String, - #[doc(hidden)] - pub matches: ArgMatches<'a>, -} - -impl<'a> SubCommand<'a> { - /// Creates a new instance of a subcommand requiring a name. The name will be displayed - /// to the user when they print version or help and usage information. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// App::new("myprog") - /// .subcommand( - /// SubCommand::with_name("config")) - /// # ; - /// ``` - pub fn with_name<'b>(name: &str) -> App<'a, 'b> { - App::new(name) - } - - /// Creates a new instance of a subcommand from a YAML (.yml) document - /// - /// # Examples - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::Subcommand; - /// # fn main() { - /// let sc_yaml = load_yaml!("test_subcommand.yml"); - /// let sc = SubCommand::from_yaml(sc_yaml); - /// # } - /// ``` - #[cfg(feature = "yaml")] - pub fn from_yaml(yaml: &Yaml) -> App { - App::from_yaml(yaml) - } -} diff --git a/third_party/rust/clap/src/build/app/debug_asserts.rs b/third_party/rust/clap/src/build/app/debug_asserts.rs new file mode 100644 index 000000000000..f96c355490f0 --- /dev/null +++ b/third_party/rust/clap/src/build/app/debug_asserts.rs @@ -0,0 +1,582 @@ +use crate::{ + build::arg::{debug_asserts::assert_arg, ArgProvider}, + mkeymap::KeyType, + util::Id, + App, AppSettings, Arg, ArgSettings, ValueHint, +}; +use std::cmp::Ordering; + +pub(crate) fn assert_app(app: &App) { + debug!("App::_debug_asserts"); + + let mut short_flags = vec![]; + let mut long_flags = vec![]; + + // Invalid version flag settings + if app.version.is_none() && app.long_version.is_none() { + // PropagateVersion is meaningless if there is no version + assert!( + !app.settings.is_set(AppSettings::PropagateVersion), + "App {}: No version information via App::version or App::long_version to propagate", + app.get_name(), + ); + + // Used `App::mut_arg("version", ..) but did not provide any version information to display + let has_mutated_version = app + .args + .args() + .any(|x| x.id == Id::version_hash() && x.provider == ArgProvider::GeneratedMutated); + + if has_mutated_version { + assert!(app.settings.is_set(AppSettings::NoAutoVersion), + "App {}: Used App::mut_arg(\"version\", ..) without providing App::version, App::long_version or using AppSettings::NoAutoVersion" + ,app.get_name() + ); + } + } + + for sc in &app.subcommands { + if let Some(s) = sc.short_flag.as_ref() { + short_flags.push(Flag::App(format!("-{}", s), &sc.name)); + } + + for (short_alias, _) in &sc.short_flag_aliases { + short_flags.push(Flag::App(format!("-{}", short_alias), &sc.name)); + } + + if let Some(l) = sc.long_flag.as_ref() { + long_flags.push(Flag::App(format!("--{}", l), &sc.name)); + } + + for (long_alias, _) in &sc.long_flag_aliases { + long_flags.push(Flag::App(format!("--{}", long_alias), &sc.name)); + } + } + + for arg in app.args.args() { + assert_arg(arg); + + 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() { + 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!( + app.two_args_of(|x| x.id == arg.id).is_none(), + "App {}: Argument names must be unique, but '{}' is in use by more than one argument or group", + app.get_name(), + arg.name, + ); + + // Long conflicts + if let Some(l) = arg.long { + if let Some((first, second)) = app.two_args_of(|x| x.long == Some(l)) { + panic!( + "App {}: Long option names must be unique for each argument, \ + but '--{}' is in use by both '{}' and '{}'", + app.get_name(), + l, + first.name, + second.name + ) + } + } + + // Short conflicts + if let Some(s) = arg.short { + if let Some((first, second)) = app.two_args_of(|x| x.short == Some(s)) { + panic!( + "App {}: Short option names must be unique for each argument, \ + but '-{}' is in use by both '{}' and '{}'", + app.get_name(), + s, + first.name, + second.name + ) + } + } + + // Index conflicts + if let Some(idx) = arg.index { + if let Some((first, second)) = + app.two_args_of(|x| x.is_positional() && x.index == Some(idx)) + { + panic!( + "App {}: 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", + app.get_name(), + first.name, + second.name + ) + } + } + + // requires, r_if, r_unless + for req in &arg.requires { + assert!( + app.id_exists(&req.1), + "App {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist", + app.get_name(), + req.1, + arg.name, + ); + } + + for req in &arg.r_ifs { + assert!( + app.id_exists(&req.0), + "App {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist", + app.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_ifs_all { + assert!( + app.id_exists(&req.0), + "App {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist", + app.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_unless { + assert!( + app.id_exists(req), + "App {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", + app.get_name(), + req, + arg.name, + ); + } + + // blacklist + for req in &arg.blacklist { + assert!( + app.id_exists(req), + "App {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist", + app.get_name(), + req, + arg.name, + ); + } + + if arg.is_set(ArgSettings::Last) { + assert!( + arg.long.is_none(), + "App {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", + app.get_name(), + arg.name + ); + assert!( + arg.short.is_none(), + "App {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", + app.get_name(), + arg.name + ); + } + + assert!( + !(arg.is_set(ArgSettings::Required) && arg.get_global()), + "App {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", + app.get_name(), + arg.name + ); + + // validators + assert!( + arg.validator.is_none() || arg.validator_os.is_none(), + "App {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed", + app.get_name(), + arg.name + ); + + if arg.value_hint == ValueHint::CommandWithArguments { + assert!( + arg.is_positional(), + "App {}: Argument '{}' has hint CommandWithArguments and must be positional.", + app.get_name(), + arg.name + ); + + assert!( + app.is_set(AppSettings::TrailingVarArg), + "App {}: Positional argument '{}' has hint CommandWithArguments, so App must have TrailingVarArg set.", + app.get_name(), + arg.name + ); + } + } + + for group in &app.groups { + // Name conflicts + assert!( + app.groups.iter().filter(|x| x.id == group.id).count() < 2, + "App {}: Argument group name must be unique\n\n\t'{}' is already in use", + app.get_name(), + group.name, + ); + + // Groups should not have naming conflicts with Args + assert!( + !app.args.args().any(|x| x.id == group.id), + "App {}: Argument group name '{}' must not conflict with argument name", + app.get_name(), + group.name, + ); + + // Required groups should have at least one arg without default values + if group.required && !group.args.is_empty() { + assert!( + group.args.iter().any(|arg| { + app.args + .args() + .any(|x| x.id == *arg && x.default_vals.is_empty()) + }), + "App {}: Argument group '{}' is required but all of it's arguments have a default value.", + app.get_name(), + group.name + ) + } + + for arg in &group.args { + // Args listed inside groups should exist + assert!( + app.args.args().any(|x| x.id == *arg), + "App {}: Argument group '{}' contains non-existent argument '{:?}'", + app.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(app); + + if let Some(help_template) = app.template { + assert!( + !help_template.contains("{flags}"), + "App {}: {}", + app.get_name(), + "`{flags}` template variable was removed in clap3, they are now included in `{options}`", + ); + assert!( + !help_template.contains("{unified}"), + "App {}: {}", + app.get_name(), + "`{unified}` template variable was removed in clap3, use `{options}` instead" + ); + } + + app._panic_on_missing_help(app.g_settings.is_set(AppSettings::HelpExpected)); + assert_app_flags(app); +} + +#[derive(Eq)] +enum Flag<'a> { + App(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) { + (App(s1, _), App(s2, _)) + | (Arg(s1, _), Arg(s2, _)) + | (App(s1, _), Arg(s2, _)) + | (Arg(s1, _), App(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) { + (App(flag, one), App(_, 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), App(_, sub)) | (App(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(app: &App) { + use AppSettings::*; + + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if app.is_set($a) { + let mut s = String::new(); + + $( + if !app.is_set($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 app.is_set($a) { + let mut s = String::new(); + + $( + if app.is_set($b) { + s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("{}\n{}", app.get_name(), s) + } + } + }; + } + + checker!(AllowInvalidUtf8ForExternalSubcommands requires AllowExternalSubcommands); + #[cfg(feature = "unstable-multicall")] + checker!(Multicall conflicts NoBinaryName); +} + +#[cfg(debug_assertions)] +fn _verify_positionals(app: &App) -> bool { + debug!("App::_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 = app + .args + .keys() + .filter_map(|x| { + if let KeyType::Position(n) = x { + Some(*n) + } else { + None + } + }) + .max() + .unwrap_or(0); + + let num_p = app.args.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 app.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 = &app.args[&KeyType::Position(highest_idx)]; + let second_to_last = &app.args[&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_set(ArgSettings::Required) + || (second_to_last.terminator.is_some() || second_to_last.is_set(ArgSettings::Last)) + || last.is_set(ArgSettings::Last); + 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_set(ArgSettings::Last); + 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 = app + .get_positionals() + .filter(|p| { + p.settings.is_set(ArgSettings::MultipleOccurrences) + || (p.settings.is_set(ArgSettings::MultipleValues) && p.num_vals.is_none()) + }) + .count(); + let ok = count <= 1 + || (last.is_set(ArgSettings::Last) + && 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 app.is_set(AppSettings::AllowMissingPositional) { + // 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 app.get_positionals() { + if foundx2 && !p.is_set(ArgSettings::Required) { + assert!( + p.is_set(ArgSettings::Required), + "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_set(ArgSettings::Required) && !p.is_set(ArgSettings::Last) { + // 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| app.args.get(&n)) { + if found { + assert!( + p.is_set(ArgSettings::Required), + "Found non-required positional argument with a lower \ + index than a required positional argument: {:?} index {:?}", + p.name, + p.index + ); + } else if p.is_set(ArgSettings::Required) && !p.is_set(ArgSettings::Last) { + // 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!( + app.get_positionals() + .filter(|p| p.is_set(ArgSettings::Last)) + .count() + < 2, + "Only one positional argument may have last(true) set. Found two." + ); + if app + .get_positionals() + .any(|p| p.is_set(ArgSettings::Last) && p.is_set(ArgSettings::Required)) + && app.has_subcommands() + && !app.is_set(AppSettings::SubcommandsNegateReqs) + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true +} diff --git a/third_party/rust/clap/src/build/app/mod.rs b/third_party/rust/clap/src/build/app/mod.rs new file mode 100644 index 000000000000..366e18307a7d --- /dev/null +++ b/third_party/rust/clap/src/build/app/mod.rs @@ -0,0 +1,3279 @@ +#[cfg(debug_assertions)] +mod debug_asserts; +mod settings; +#[cfg(test)] +mod tests; + +pub use self::settings::{AppFlags, AppSettings}; + +// Std +use std::{ + collections::HashMap, + env, + ffi::OsString, + fmt, + io::{self, Write}, + ops::Index, + path::Path, +}; + +// Third Party +use os_str_bytes::RawOsStr; +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::{ + build::{arg::ArgProvider, Arg, ArgGroup, ArgSettings}, + mkeymap::MKeyMap, + output::{fmt::Colorizer, Help, HelpWriter, Usage}, + parse::{ArgMatcher, ArgMatches, Input, Parser}, + util::{color::ColorChoice, Id, Key}, + Error, ErrorKind, Result as ClapResult, INTERNAL_ERROR_MSG, +}; + +/// Build a command-line interface. +/// +/// This includes defining arguments, subcommands, parser behavior, and help output. +/// Once all configuration is complete, +/// the [`App::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 +/// [`IntoApp::into_app`][crate::IntoApp::into_app] to access the +/// `App`. +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{App, Arg}; +/// let m = App::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").index(1) +/// ) +/// .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`]: App::get_matches() +#[derive(Default, Debug, Clone, PartialEq, Eq)] +pub struct App<'help> { + pub(crate) id: Id, + pub(crate) name: String, + pub(crate) long_flag: Option<&'help str>, + pub(crate) short_flag: Option, + pub(crate) bin_name: Option, + pub(crate) author: Option<&'help str>, + pub(crate) version: Option<&'help str>, + pub(crate) long_version: Option<&'help str>, + pub(crate) about: Option<&'help str>, + pub(crate) long_about: Option<&'help str>, + pub(crate) before_help: Option<&'help str>, + pub(crate) before_long_help: Option<&'help str>, + pub(crate) after_help: Option<&'help str>, + pub(crate) after_long_help: Option<&'help str>, + pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible) + pub(crate) short_flag_aliases: Vec<(char, bool)>, // (name, visible) + pub(crate) long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible) + pub(crate) usage_str: Option<&'help str>, + pub(crate) usage: Option, + pub(crate) help_str: Option<&'help str>, + pub(crate) disp_ord: Option, + pub(crate) term_w: Option, + pub(crate) max_w: Option, + pub(crate) template: Option<&'help str>, + pub(crate) settings: AppFlags, + pub(crate) g_settings: AppFlags, + pub(crate) args: MKeyMap<'help>, + pub(crate) subcommands: Vec>, + pub(crate) replacers: HashMap<&'help str, &'help [&'help str]>, + pub(crate) groups: Vec>, + pub(crate) current_help_heading: Option<&'help str>, + pub(crate) subcommand_value_name: Option<&'help str>, + pub(crate) subcommand_heading: Option<&'help str>, +} + +impl<'help> App<'help> { + /// Creates a new instance of an `App`. + /// + /// 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 [`app_from_crate!!`](crate::app_from_crate!) and [`crate_name!`](crate::crate_name!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("My Program") + /// # ; + /// ``` + pub fn new>(name: S) -> Self { + let name = name.into(); + + 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(), + ) + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, arg, Arg}; + /// App::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(); + 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::{App, arg, Arg}; + /// App::new("myprog") + /// .args(&[ + /// arg!("[debug] -d 'turns on debugging info'"), + /// Arg::new("input").index(1).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 an [`App`]. + /// + /// This can be useful for modifying the auto-generated help or version arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// + /// let mut app = App::new("foo") + /// .arg(Arg::new("bar") + /// .short('b')) + /// .mut_arg("bar", |a| a.short('B')); + /// + /// let res = app.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 = app.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::{App, arg, ArgGroup}; + /// App::new("app") + /// .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 [`App`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, arg, ArgGroup}; + /// App::new("app") + /// .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-[`App`]s, because they can contain their own arguments, + /// subcommands, version, usage, etc. They also function just like [`App`]s, in that they get + /// their own auto generated help, version, and usage. + /// + /// A subcommand's [`App::name`] will be used for: + /// - The argument the user passes in + /// - Programmatically looking up the subcommand + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, arg}; + /// App::new("myprog") + /// .subcommand(App::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::{App, Arg, }; + /// # App::new("myprog") + /// .subcommands( vec![ + /// App::new("config").about("Controls configuration functionality") + /// .arg(Arg::new("config_file").index(1)), + /// App::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::{App, Arg}; + /// fn app() -> App<'static> { + /// App::new("foo") + /// .arg(Arg::new("bar").short('b') + /// ) + /// } + /// + /// #[test] + /// fn verify_app() { + /// app().debug_assert(); + /// } + /// + /// fn main() { + /// let m = app().get_matches_from(vec!["foo", "-b"]); + /// println!("{}", m.is_present("bar")); + /// } + /// ``` + pub fn debug_assert(mut self) { + self._build_all(); + } + + /// Custom error message for post-parsing validation + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, ErrorKind}; + /// let mut app = App::new("myprog"); + /// let err = app.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::{App, Arg}; + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::try_get_matches_from_mut`]: App::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 `App`. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let mut app = App::new("myprog") + /// // Args and options go here... + /// ; + /// let matches = app.get_matches_mut(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::get_matches`]: App::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::{App, Arg}; + /// let matches = App::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 + /// [`AppSettings::NoBinaryName`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`App::get_matches`]: App::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 + /// [`AppSettings::NoBinaryName`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .try_get_matches_from(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::get_matches_from`]: App::get_matches_from() + /// [`App::try_get_matches`]: App::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 `App`. + /// + /// **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 + /// [`AppSettings::NoBinaryName`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut app = App::new("myprog"); + /// // Args and options go here... + /// let matches = app.try_get_matches_from_mut(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::try_get_matches_from`]: App::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 it = Input::from(itr.into_iter()); + + #[cfg(feature = "unstable-multicall")] + if self.settings.is_set(AppSettings::Multicall) { + if let Some((argv0, _)) = it.next() { + 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!( + "App::try_get_matches_from_mut: Parsed command {} from argv", + command + ); + + debug!("App::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); + it.insert(&[&command]); + debug!("App::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 it); + } + } + }; + + // 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, _)) = it.next() { + 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 it) + } + + /// Prints the short help message (`-h`) to [`io::stdout()`]. + /// + /// See also [`App::print_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.print_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + pub fn print_help(&mut self) -> io::Result<()> { + self._build(); + let color = self.get_color(); + + let p = Parser::new(self); + let mut c = Colorizer::new(false, color); + Help::new(HelpWriter::Buffer(&mut c), &p, false).write_help()?; + c.print() + } + + /// Prints the long help message (`--help`) to [`io::stdout()`]. + /// + /// See also [`App::print_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.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(); + let color = self.get_color(); + + let p = Parser::new(self); + let mut c = Colorizer::new(false, color); + Help::new(HelpWriter::Buffer(&mut c), &p, true).write_help()?; + c.print() + } + + /// Writes the short help message (`-h`) to a [`io::Write`] object. + /// + /// See also [`App::write_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.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(); + + let p = Parser::new(self); + Help::new(HelpWriter::Normal(w), &p, false).write_help()?; + w.flush() + } + + /// Writes the long help message (`--help`) to a [`io::Write`] object. + /// + /// See also [`App::write_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.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(); + + let p = Parser::new(self); + Help::new(HelpWriter::Normal(w), &p, true).write_help()?; + w.flush() + } + + /// Version message rendered as if the user ran `-V`. + /// + /// See also [`App::render_long_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let app = App::new("myprog"); + /// println!("{}", app.render_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: App::version() + /// [`--version` (long)]: App::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 [`App::render_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let app = App::new("myprog"); + /// println!("{}", app.render_long_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: App::version() + /// [`--version` (long)]: App::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::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// println!("{}", app.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(); + + let mut parser = Parser::new(self); + parser._build(); + Usage::new(&parser).create_usage_with_title(&[]) + } +} + +/// App Settings +impl<'help> App<'help> { + /// (Re)Sets the program's name. + /// + /// See [`App::new`] for more details. + /// + /// # Examples + /// + /// ```ignore + /// # use clap::{App, load_yaml}; + /// let yaml = load_yaml!("app.yaml"); + /// let app = App::from(yaml) + /// .name(crate_name!()); + /// + /// // continued logic goes here, such as `app.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::App; + /// App::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 + } + + /// 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::App; + /// App::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 [`App::long_about`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `App::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::App; + /// App::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 [`App::about`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`App::about`] (short format) is used in completion + /// script generation in order to be concise. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::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`]: App::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 [`App::after_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::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 [`App::after_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::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 [`App::before_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::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 [`App::before_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::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 [`App::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::App; + /// App::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 [`App::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::App; + /// App::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::{App, Arg}; + /// App::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 [`App::override_help`] for + /// them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::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: + /// + /// * `{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 [`App::about`] or + /// [`App::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 [`App::after_long_help`]. + /// * `{before-help}` - Help from [`App::before_help`] or [`App::before_long_help`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .version("1.0") + /// .help_template("{bin} ({version}) - {usage}") + /// # ; + /// ``` + /// [`App::about`]: App::about() + /// [`App::long_about`]: App::long_about() + /// [`App::after_help`]: App::after_help() + /// [`App::after_long_help`]: App::after_long_help() + /// [`App::before_help`]: App::before_help() + /// [`App::before_long_help`]: App::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 [`App::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::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::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::{App, AppSettings}; + /// App::new("myprog") + /// .unset_setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::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 [`App::setting`] to apply a setting only to this command. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::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::{App, AppSettings}; + /// App::new("myprog") + /// .unset_global_setting(AppSettings::AllowNegativeNumbers) + /// # ; + /// ``` + /// [global]: App::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 + } + + /// 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::{App, ColorChoice}; + /// App::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)] + match color { + ColorChoice::Auto => self.global_setting(AppSettings::ColorAuto), + ColorChoice::Always => self.global_setting(AppSettings::ColorAlways), + ColorChoice::Never => self.global_setting(AppSettings::ColorNever), + } + } + + /// 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 [`App::subcommand_help_heading`] + /// + /// [`App::arg`]: App::arg() + /// [`Arg::help_heading`]: crate::Arg::help_heading() + #[inline] + #[must_use] + pub fn help_heading(mut self, heading: O) -> Self + where + O: Into>, + { + self.current_help_heading = heading.into(); + self + } + + /// 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::App; + /// App::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 [`App::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::App; + /// App::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 + } + + /// 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 `app module`. Now let's also assume `module` also has a subcommand + /// called `install` which can be invoked `app module install`. If for some + /// reason users needed to be able to reach `app module install` via the + /// short-hand `app 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 `app module install` handling code. This is error prone and + /// tedious. + /// + /// We could instead use [`App::replace`] so that, when the user types `app + /// 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::App; + /// let m = App::new("app") + /// .subcommand(App::new("module") + /// .subcommand(App::new("install"))) + /// .replace("install", &["module", "install"]) + /// .get_matches_from(vec!["app", "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 `app --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 [`App::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::{App, Arg}; + /// let m = App::new("app") + /// .arg(Arg::new("save-context") + /// .long("save-context")) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime")) + /// .replace("--save-all", &["--save-context", "--save-runtime"]) + /// .get_matches_from(vec!["app", "--save-all"]); + /// + /// assert!(m.is_present("save-context")); + /// assert!(m.is_present("save-runtime")); + /// ``` + /// + /// 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::{App, Arg}; + /// let m = App::new("app") + /// .arg(Arg::new("save-context") + /// .long("save-context")) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime")) + /// .arg(Arg::new("format") + /// .long("format") + /// .takes_value(true) + /// .possible_values(["txt", "json"])) + /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) + /// .get_matches_from(vec!["app", "--save-all"]); + /// + /// assert!(m.is_present("save-context")); + /// assert!(m.is_present("save-runtime")); + /// assert_eq!(m.value_of("format"), Some("json")); + /// ``` + /// + /// [`App::replace`]: App::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 + } +} + +/// 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::{App, Arg}; + /// let matches = App::new("pacman") + /// .subcommand( + /// App::new("sync").short_flag('S').arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .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.is_present("search")); + /// ``` + /// [`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::{App, Arg}; + /// let matches = App::new("pacman") + /// .subcommand( + /// App::new("sync").long_flag("sync").arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .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.is_present("search")); + /// ``` + /// + /// [`Arg::long`]: Arg::long() + #[must_use] + pub fn long_flag(mut self, long: &'help str) -> Self { + 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 [`App::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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::new("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_alias`]: App::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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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 [`App::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::{App, Arg}; + /// let m = App::new("myprog") + /// .subcommand(App::new("test") + /// .aliases(&["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .index(1) + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_aliases`]: App::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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::new("test").short_flag('t') + /// .short_flag_aliases(&['a', 'b', 'c'])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .index(1) + /// .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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::new("test").long_flag("test") + /// .long_flag_aliases(&["testing", "testall", "test_all"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .index(1) + /// .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 + /// [`App::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::{App, Arg}; + /// let m = App::new("myprog") + /// .subcommand(App::new("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: App::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 [`App::short_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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`]: App::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 [`App::long_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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`]: App::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 + /// [`App::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::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::new("test") + /// .visible_aliases(&["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: App::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 [`App::short_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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`]: App::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 [`App::long_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, }; + /// let m = App::new("myprog") + /// .subcommand(App::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`]: App::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::{App, }; + /// let m = App::new("cust-ord") + /// .subcommand(App::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(App::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 + } + + /// Sets the value name used for subcommands when printing usage and help. + /// + /// By default, this is "SUBCOMMAND". + /// + /// See also [`App::subcommand_help_heading`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .subcommand(App::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::{App, Arg}; + /// App::new("myprog") + /// .subcommand(App::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 [`App::subcommand_value_name`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .subcommand(App::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::{App, Arg}; + /// App::new("myprog") + /// .subcommand(App::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> { + /// 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 app. + #[inline] + pub fn get_name(&self) -> &str { + &self.name + } + + /// 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 [`App::about`]. + /// + /// [`App::about`]: App::about() + #[inline] + pub fn get_about(&self) -> Option<&'help str> { + self.about + } + + /// Get the help message specified via [`App::long_about`]. + /// + /// [`App::long_about`]: App::long_about() + #[inline] + pub fn get_long_about(&self) -> Option<&'help str> { + self.long_about + } + + /// Get the custom section heading specified via [`App::help_heading`]. + /// + /// [`App::help_heading`]: App::help_heading() + #[inline] + pub fn get_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 `App`. + /// + /// This checks both [local] and [global settings]. + /// + /// [local]: App::setting() + /// [global settings]: App::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] + pub fn get_color(&self) -> ColorChoice { + debug!("App::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 `App` has subcommands. + #[inline] + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } + + /// 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 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_set(ArgSettings::TakesValue) && !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 `App`. + pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator + { + if arg.get_global() { + self.get_global_arg_conflicts_with(arg) + } else { + arg.blacklist + .iter() + .map(|id| { + self.args.args().find(|arg| arg.id == *id).expect( + "App::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the app", + ) + }) + .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( + "App::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the app", + ) + }) + .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 + } +} + +/// 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")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + 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, "app".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 [`App::override_usage`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::override_usage`")] + #[must_use] + pub fn usage>(self, usage: S) -> Self { + self.override_usage(usage) + } + + /// Deprecated, replaced with [`App::override_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::override_help`")] + #[must_use] + pub fn help>(self, help: S) -> Self { + self.override_help(help) + } + + /// Deprecated, replaced with [`App::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[must_use] + pub fn help_short(self, c: char) -> Self { + self.mut_arg("help", |a| a.short(c)) + } + + /// Deprecated, replaced with [`App::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[must_use] + pub fn version_short(self, c: char) -> Self { + self.mut_arg("version", |a| a.short(c)) + } + + /// Deprecated, replaced with [`App::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[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 [`App::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[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 [`App::help_template`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::help_template`")] + #[must_use] + pub fn template>(self, s: S) -> Self { + self.help_template(s) + } + + /// Deprecated, replaced with [`App::setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::setting(a | b)`")] + #[must_use] + pub fn settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.insert((*s).into()); + } + self + } + + /// Deprecated, replaced with [`App::unset_setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::unset_setting(a | b)`")] + #[must_use] + pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.remove((*s).into()); + } + self + } + + /// Deprecated, replaced with [`App::global_setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::global_setting(a | b)`")] + #[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 [`App::term_width`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::term_width`")] + #[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!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + #[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!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + #[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 [`App::render_version`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::render_version`")] + pub fn write_version(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`App::render_long_version`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::render_long_version`")] + pub fn write_long_version(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_long_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`App::try_get_matches`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches`")] + pub fn get_matches_safe(self) -> ClapResult { + self.try_get_matches() + } + + /// Deprecated, replaced with [`App::try_get_matches_from`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches_from`")] + 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 [`App::try_get_matches_from_mut`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `App::try_get_matches_from_mut`" + )] + 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> { + fn get_used_global_args(&self, matcher: &ArgMatcher) -> Vec { + let global_args: Vec<_> = self + .args + .args() + .filter(|a| a.get_global()) + .map(|ga| ga.id.clone()) + .collect(); + if let Some(used_subcommand) = matcher.0.subcommand.as_ref() { + if let Some(used_subcommand) = self + .subcommands + .iter() + .find(|subcommand| subcommand.id == used_subcommand.id) + { + return [global_args, used_subcommand.get_used_global_args(matcher)].concat(); + } + } + global_args + } + + fn _do_parse(&mut self, it: &mut Input) -> ClapResult { + debug!("App::_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(); + + 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, it) { + if self.is_set(AppSettings::IgnoreErrors) { + debug!("App::_do_parse: ignoring error: {}", error); + } else { + return Err(error); + } + } + + let global_arg_vec: Vec = self.get_used_global_args(&matcher); + + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into_inner()) + } + + // used in clap_complete (https://github.com/clap-rs/clap_complete) + #[doc(hidden)] + pub fn _build_all(&mut self) { + self._build(); + for subcmd in self.get_subcommands_mut() { + subcmd._build(); + } + self._build_bin_names(); + } + + // used in clap_complete (https://github.com/clap-rs/clap_complete) + #[doc(hidden)] + pub fn _build(&mut self) { + debug!("App::_build"); + 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; + + 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); + 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_set(ArgSettings::Last) { + // 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 self_override { + let self_id = a.id.clone(); + a.overrides.push(self_id); + } + a._build(); + if a.is_positional() && a.index.is_none() { + a.index = Some(pos_counter); + pos_counter += 1; + } + } + + self.args._build(); + + #[cfg(debug_assertions)] + self::debug_asserts::assert_app(self); + self.settings.set(AppSettings::Built); + } else { + debug!("App::_build: already built"); + } + } + + 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(), + "AppSettings::HelpExpected is enabled for the App {}, 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)] + 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!("App::_propagate_global_args:{}", self.name); + + for sc in &mut self.subcommands { + for a in self.args.args().filter(|a| a.get_global()) { + 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 { + sc.args.remove(index); + propagate = true; + } + } + + if propagate || sc.find(&a.id).is_none() { + sc.args.push(a.clone()); + } + } + } + } + + /// Propagate settings + pub(crate) fn _propagate(&mut self) { + debug!("App::_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!("App::_check_help_and_version"); + + 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!("App::_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 other_arg_has_short = self.args.args().any(|x| x.short == Some('h')); + let help = self + .args + .args_mut() + .find(|x| x.id == Id::help_hash()) + .expect(INTERNAL_ERROR_MSG); + + if !(help.short.is_some() + || other_arg_has_short + || self.subcommands.iter().any(|sc| sc.short_flag == Some('h'))) + { + help.short = Some('h'); + } + } + + // 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!("App::_check_help_and_version: Removing generated version"); + + // This is the check mentioned above that only checks for Generated, not + // GeneratedMuated 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!("App::_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!("App::_derive_display_order:{}", self.name); + + if self.settings.is_set(AppSettings::DeriveDisplayOrder) { + for (i, a) in self + .args + .args_mut() + .filter(|a| !a.is_positional()) + .filter(|a| a.provider != ArgProvider::Generated) + .enumerate() + { + a.disp_ord.get_or_insert(i); + } + 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(); + } + } + + // used in clap_complete (https://github.com/clap-rs/clap_complete) + #[doc(hidden)] + pub fn _build_bin_names(&mut self) { + debug!("App::_build_bin_names"); + + if !self.is_set(AppSettings::BinNameBuilt) { + for mut sc in &mut self.subcommands { + debug!("App::_build_bin_names:iter: bin_name set..."); + + if sc.bin_name.is_none() { + debug!("No"); + let bin_name = format!( + "{}{}{}", + self.bin_name.as_ref().unwrap_or(&self.name.clone()), + if self.bin_name.is_some() { " " } else { "" }, + &*sc.name + ); + debug!( + "App::_build_bin_names:iter: Setting bin_name of {} to {}", + self.name, bin_name + ); + sc.bin_name = Some(bin_name); + } else { + debug!("yes ({:?})", sc.bin_name); + } + debug!( + "App::_build_bin_names:iter: Calling build_bin_names from...{}", + sc.name + ); + sc._build_bin_names(); + } + self.set(AppSettings::BinNameBuilt); + } else { + debug!("App::_build_bin_names: already built"); + } + } + + pub(crate) fn _render_version(&self, use_long: bool) -> String { + debug!("App::_render_version"); + + let ver = if use_long { + self.long_version + .unwrap_or_else(|| self.version.unwrap_or("")) + } else { + self.version + .unwrap_or_else(|| 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!("App::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 unroll_args_in_group(&self, group: &Id) -> Vec { + debug!("App::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!("App::unroll_args_in_group:iter: entity={:?}", n); + if !args.contains(n) { + if self.find(n).is_some() { + debug!("App::unroll_args_in_group:iter: this is an arg"); + args.push(n.clone()) + } else { + debug!("App::unroll_args_in_group:iter: this is a group"); + g_vec.push(n); + } + } + } + } + + args + } + + pub(crate) fn unroll_requirements_for_arg(&self, arg: &Id, matcher: &ArgMatcher) -> Vec { + let requires_if_or_not = |(val, req_arg): &(Option<&str>, Id)| -> Option { + if let Some(v) = val { + if matcher + .get(arg) + .map(|ma| ma.contains_val(v)) + .unwrap_or(false) + { + Some(req_arg.clone()) + } else { + None + } + } else { + Some(req_arg.clone()) + } + }; + + 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(requires_if_or_not) { + 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: &RawOsStr) -> 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) + } +} + +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/third_party/rust/clap/src/build/app/settings.rs b/third_party/rust/clap/src/build/app/settings.rs new file mode 100644 index 000000000000..f166795ea082 --- /dev/null +++ b/third_party/rust/clap/src/build/app/settings.rs @@ -0,0 +1,1366 @@ +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +// 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 [`App`] 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 +/// +/// [`App`]: crate::App +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum AppSettings { + /// 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! + /// + /// ```rust + /// # use clap::{App, arg, AppSettings}; + /// let app = App::new("app") + /// .global_setting(AppSettings::IgnoreErrors) + /// .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 = app.try_get_matches_from(vec!["app", "-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); + /// ``` + IgnoreErrors, + + /// Display the message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before + /// exiting + /// + /// This is most useful when writing an application which is run from a GUI shortcut, or on + /// Windows where a user tries to open the binary by double-clicking instead of using the + /// command line. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::WaitOnError); + /// ``` + WaitOnError, + + /// 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 + /// [`AppSettings::AllowNegativeNumbers`]. + /// + /// **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, App, AppSettings}; + /// // Imagine you needed to represent negative numbers as well, such as -10 + /// let m = App::new("nums") + /// .setting(AppSettings::AllowHyphenValues) + /// .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() + AllowHyphenValues, + + /// Allows negative numbers to pass as values. + /// + /// This is similar to [`AppSettings::AllowHyphenValues`] except that it only allows numbers, + /// all other undefined leading hyphens will fail to parse. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let res = App::new("myprog") + /// .global_setting(AppSettings::AllowNegativeNumbers) + /// .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"); + /// ``` + AllowNegativeNumbers, + + /// Specifies that all arguments override themselves. + /// + /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all + /// defined arguments. + /// + /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() + AllArgsOverrideSelf, + + /// 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::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .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::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .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::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .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::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .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() + AllowMissingPositional, + + /// 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::{App, arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::TrailingVarArg) + /// .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() + TrailingVarArg, + + /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`] + /// was used. + /// + /// **NOTE:** The same thing can be done manually by setting the final positional argument to + /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DontDelimitTrailingValues) + /// .get_matches(); + /// ``` + /// + /// [`Arg::use_delimiter(false)`]: crate::Arg::use_delimiter() + DontDelimitTrailingValues, + + /// 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` + /// + /// [aliases]: crate::App::aliases() + 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 [`AppSettings::ArgsNegateSubcommands`] in + /// conjunction with this setting. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// let m = App::new("prog") + /// .global_setting(AppSettings::InferSubcommands) + /// .subcommand(App::new("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// + /// [subcommand]: crate::App::subcommand() + /// [positional/free arguments]: crate::Arg::index() + /// [aliases]: crate::App::aliases() + InferSubcommands, + + /// If no [`subcommand`] is present at runtime, error and exit gracefully. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .subcommand(App::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::App::subcommand() + SubcommandRequired, + + /// Display help if no [`subcommands`] are present at runtime and exit gracefully (i.e. an + /// empty run such as `$ myprog`). + /// + /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do + /// nearly same thing; this prints the help text, and the other prints an error. + /// + /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will + /// still be displayed and exit. If this is *not* the desired result, consider using + /// [`AppSettings::ArgRequiredElseHelp`] instead. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequiredElseHelp); + /// ``` + /// + /// [`subcommands`]: crate::App::subcommand() + SubcommandRequiredElseHelp, + + /// Assume unexpected positional arguments are a [`subcommand`]. + /// + /// **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. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowExternalSubcommands) + /// .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::App::subcommand() + /// [`ArgMatches`]: crate::ArgMatches + /// [`ErrorKind::UnknownArgument`]: crate::ErrorKind::UnknownArgument + AllowExternalSubcommands, + + /// Strip directory path from argv\[0\] and use as an argument. + /// + /// 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 when it is convenient to store code + /// for many programs in the same file, + /// such as deduplicating code across multiple programs + /// without loading a shared library at runtime. + /// + /// Multicall can't be used with [`NoBinaryName`] since they interpret + /// the command name in incompatible ways. + /// + /// # 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 other related functionality that would be convenient to provide + /// and it is convenient for the code to implement it to be in the same executable. + /// + /// The name of the app is essentially unused + /// and may be the same as the name of a subcommand. + /// + /// The names of the immediate subcommands of the App + /// 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::{App, AppSettings, ErrorKind}; + /// let mut app = App::new("hostname") + /// .setting(AppSettings::Multicall) + /// .subcommand(App::new("hostname")) + /// .subcommand(App::new("dnsdomainname")); + /// let m = app.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind, ErrorKind::UnknownArgument); + /// let m = app.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 App + /// and as subcommands of the "main" applet. + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// fn applet_commands() -> [App<'static>; 2] { + /// [App::new("true"), App::new("false")] + /// } + /// let mut app = App::new("busybox") + /// .setting(AppSettings::Multicall) + /// .subcommand( + /// App::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 = app.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 = app.get_matches_from(&["/usr/bin/true"]); + /// assert_eq!(m.subcommand_name(), Some("true")); + /// ``` + /// + /// **NOTE:** Applets are slightly semantically different from subcommands, + /// so it's recommended to use [`App::subcommand_help_heading`] and + /// [`App::subcommand_value_name`] to change the descriptive text as above. + /// + /// [`NoBinaryName`]: crate::AppSettings::NoBinaryName + /// [`App::subcommand_value_name`]: crate::App::subcommand_value_name + /// [`App::subcommand_help_heading`]: crate::App::subcommand_help_heading + #[cfg(feature = "unstable-multicall")] + Multicall, + + /// 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 [`AppSettings::AllowExternalSubcommands`] + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + /// .setting(AppSettings::AllowExternalSubcommands) + /// .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::App::subcommand() + AllowInvalidUtf8ForExternalSubcommands, + + /// Specifies that the help subcommand should print the long help message (`--help`). + /// + /// **NOTE:** This setting is useless if [`AppSettings::DisableHelpSubcommand`] or [`AppSettings::NoAutoHelp`] is set, + /// or if the app contains no subcommands at all. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::UseLongFormatForHelpSubcommand) + /// .subcommand(App::new("test") + /// .arg(Arg::new("foo") + /// .help("short form about message") + /// .long_help("long form about message") + /// ) + /// ) + /// .get_matches(); + /// ``` + /// [long format]: crate::App::long_about + UseLongFormatForHelpSubcommand, + + /// 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::{App, Arg, AppSettings, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(App::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::{App, Arg, AppSettings, ErrorKind}; + /// let noerr = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(App::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// + /// [`Arg::required(true)`]: crate::Arg::required() + /// [`subcommands`]: crate::App::subcommand() + SubcommandsNegateReqs, + + /// 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::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgsNegateSubcommands); + /// ``` + /// + /// [`subcommands`]: crate::App::subcommand() + 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 + /// app --foo val1 val2 subcommand + /// --------- ---------- + /// values another value + /// ``` + /// + /// This setting instructs the parser to stop when encountering a subcommand instead of + /// greedily consuming arguments. + /// + /// ```text + /// app --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::{App, AppSettings, Arg}; + /// let app = App::new("app").subcommand(App::new("sub")).arg( + /// Arg::new("arg") + /// .long("arg") + /// .multiple_values(true) + /// .takes_value(true), + /// ); + /// + /// let matches = app + /// .clone() + /// .try_get_matches_from(&["app", "--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 = app + /// .setting(AppSettings::SubcommandPrecedenceOverArg) + /// .try_get_matches_from(&["app", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// + /// assert_eq!( + /// matches.values_of("arg").unwrap().collect::>(), + /// &["1", "2", "3"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_some()); + /// ``` + SubcommandPrecedenceOverArg, + + /// Exit gracefully if no arguments are present (e.g. `$ myprog`). + /// + /// **NOTE:** [`subcommands`] count as arguments + /// + /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will + /// ensure that some argument is always present. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgRequiredElseHelp); + /// ``` + /// + /// [`subcommands`]: crate::App::subcommand() + /// [`Arg::default_value`]: crate::Arg::default_value() + 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 [`App::display_order`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::DeriveDisplayOrder) + /// .get_matches(); + /// ``` + /// + /// [`subcommands`]: crate::App::subcommand() + /// [`Arg::display_order`]: crate::Arg::display_order + /// [`App::display_order`]: crate::App::display_order + DeriveDisplayOrder, + + /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::DontCollapseArgsInUsage) + /// .get_matches(); + /// ``` + DontCollapseArgsInUsage, + + /// Places the help string for all arguments on the line after the argument. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::NextLineHelp) + /// .get_matches(); + /// ``` + NextLineHelp, + + /// Disables colorized help messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DisableColoredHelp) + /// .get_matches(); + /// ``` + DisableColoredHelp, + + /// Disables `-h` and `--help` flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpFlag) + /// .try_get_matches_from(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + DisableHelpFlag, + + /// Disables the `help` [`subcommand`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind, }; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpSubcommand) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(App::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// + /// [`subcommand`]: crate::App::subcommand() + DisableHelpSubcommand, + + /// Disables `-V` and `--version` flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableVersionFlag) + /// .try_get_matches_from(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + 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! + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .version("v1.1") + /// .global_setting(AppSettings::PropagateVersion) + /// .subcommand(App::new("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// + /// [`subcommands`]: crate::App::subcommand() + PropagateVersion, + + /// Specifies that this [`subcommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, }; + /// App::new("myprog") + /// .subcommand(App::new("test") + /// .setting(AppSettings::Hidden)) + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::App::subcommand() + Hidden, + + /// 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]. + HidePossibleValues, + + /// Panic if help descriptions are omitted. + /// + /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at + /// compile-time with `#![deny(missing_docs)]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::HelpExpected) + /// .arg( + /// Arg::new("foo").help("It does foo stuff") + /// // As required via AppSettings::HelpExpected, a help message was supplied + /// ) + /// # .get_matches(); + /// ``` + /// + /// # Panics + /// + /// ```rust,no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myapp") + /// .global_setting(AppSettings::HelpExpected) + /// .arg( + /// Arg::new("foo") + /// // Someone forgot to put .about("...") here + /// // Since the setting AppSettings::HelpExpected is activated, this will lead to + /// // a panic (if you are in debug mode) + /// ) + /// # .get_matches(); + ///``` + HelpExpected, + + /// 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, or an interactive CLI where + /// one would not normally type the binary or program name for each command. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::NoBinaryName) + /// .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::App::try_get_matches_from_mut() + NoBinaryName, + + /// Treat the auto-generated `-h, --help` flags like any other flag, and *not* print the help + /// message. + /// + /// This allows one to handle printing of the help message manually. + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// let result = App::new("myprog") + /// .setting(AppSettings::NoAutoHelp) + /// .try_get_matches_from("myprog --help".split(" ")); + /// + /// // Normally, if `--help` is used clap prints the help message and returns an + /// // ErrorKind::DisplayHelp + /// // + /// // However, `--help` was treated like a normal flag + /// + /// assert!(result.is_ok()); + /// assert!(result.unwrap().is_present("help")); + /// ``` + NoAutoHelp, + + /// Treat the auto-generated `-V, --version` flags like any other flag, and + /// *not* print the version message. + /// + /// This allows one to handle printing of the version message manually. + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// let result = App::new("myprog") + /// .version("3.0") + /// .setting(AppSettings::NoAutoVersion) + /// .try_get_matches_from("myprog --version".split(" ")); + /// + /// // Normally, if `--version` is used clap prints the version message and returns an + /// // ErrorKind::DisplayVersion + /// // + /// // However, `--version` was treated like a normal flag + /// + /// assert!(result.is_ok()); + /// assert!(result.unwrap().is_present("version")); + /// ``` + NoAutoVersion, + + /// Deprecated, replaced with [`AppSettings::AllowHyphenValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::AllowHyphenValues`" + )] + AllowLeadingHyphen, + + /// Deprecated, this is now the default, see [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`] and [`ArgSettings::AllowInvalidUtf8`][crate::ArgSettings::AllowInvalidUtf8] for the opposite. + #[deprecated( + since = "3.0.0", + note = "This is now the default see `AppSettings::AllowInvalidUtf8ForExternalSubcommands` and `ArgSettings::AllowInvalidUtf8` for the opposite." + )] + StrictUtf8, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + UnifiedHelpMessage, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + ColoredHelp, + + /// Deprecated, see [`App::color`][crate::App::color] + #[deprecated(since = "3.0.0", note = "Replaced with `App::color`")] + ColorAuto, + + /// Deprecated, replaced with [`App::color`][crate::App::color] + #[deprecated(since = "3.0.0", note = "Replaced with `App::color`")] + ColorAlways, + + /// Deprecated, replaced with [`App::color`][crate::App::color] + #[deprecated(since = "3.0.0", note = "Replaced with `App::color`")] + ColorNever, + + /// Deprecated, replaced with [`AppSettings::DisableHelpFlag`] + #[deprecated(since = "3.0.0", note = "Replaced with `AppSettings::DisableHelpFlag`")] + DisableHelpFlags, + + /// Deprecated, replaced with [`AppSettings::DisableVersionFlag`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::DisableVersionFlag`" + )] + DisableVersion, + + /// Deprecated, replaced with [`AppSettings::PropagateVersion`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::PropagateVersion`" + )] + GlobalVersion, + + /// Deprecated, replaced with [`AppSettings::HidePossibleValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with AppSettings::HidePossibleValues" + )] + HidePossibleValuesInHelp, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + UnifiedHelp, + + /// If the app is already built, used for caching. + #[doc(hidden)] + Built, + + /// If the app'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; + #[cfg(feature = "unstable-multicall")] + 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, + #[cfg(feature = "unstable-multicall")] + 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/third_party/rust/clap/src/build/app/tests.rs b/third_party/rust/clap/src/build/app/tests.rs new file mode 100644 index 000000000000..579243baadb7 --- /dev/null +++ b/third_party/rust/clap/src/build/app/tests.rs @@ -0,0 +1,63 @@ +use crate::{App, AppSettings}; + +#[test] +fn propagate_version() { + let mut app = App::new("test") + .setting(AppSettings::PropagateVersion) + .version("1.1") + .subcommand(App::new("sub1")); + app._propagate(); + assert_eq!(app.subcommands[0].version, Some("1.1")); +} + +#[test] +fn global_setting() { + let mut app = App::new("test") + .global_setting(AppSettings::AllowHyphenValues) + .subcommand(App::new("subcmd")); + app._propagate(); + assert!(app + .subcommands + .iter() + .find(|s| s.name == "subcmd") + .unwrap() + .is_set(AppSettings::AllowHyphenValues)); +} + +#[test] +fn global_settings() { + let mut app = App::new("test") + .global_setting(AppSettings::AllowHyphenValues) + .global_setting(AppSettings::TrailingVarArg) + .subcommand(App::new("subcmd")); + app._propagate(); + assert!(app + .subcommands + .iter() + .find(|s| s.name == "subcmd") + .unwrap() + .is_set(AppSettings::AllowHyphenValues)); + assert!(app + .subcommands + .iter() + .find(|s| s.name == "subcmd") + .unwrap() + .is_set(AppSettings::TrailingVarArg)); +} + +// This test will *fail to compile* if App is not Send + Sync +#[test] +fn app_send_sync() { + fn foo(_: T) {} + foo(App::new("test")) +} + +#[test] +fn issue_2090() { + let mut app = App::new("app") + .global_setting(AppSettings::DisableVersionFlag) + .subcommand(App::new("sub")); + app._build(); + + assert!(app.subcommands[0].is_set(AppSettings::DisableVersionFlag)); +} diff --git a/third_party/rust/clap/src/build/arg/debug_asserts.rs b/third_party/rust/clap/src/build/arg/debug_asserts.rs new file mode 100644 index 000000000000..8fe77c281994 --- /dev/null +++ b/third_party/rust/clap/src/build/arg/debug_asserts.rs @@ -0,0 +1,80 @@ +use crate::{Arg, ArgSettings, ValueHint}; + +pub(crate) 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, + ); + + if arg.value_hint != ValueHint::Unknown { + assert!( + arg.is_set(ArgSettings::TakesValue), + "Argument '{}' has value hint but takes no value", + arg.name + ); + + if arg.value_hint == ValueHint::CommandWithArguments { + assert!( + arg.is_set(ArgSettings::MultipleValues), + "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 + ); + } + + if arg.is_set(ArgSettings::Required) { + assert!( + arg.default_vals.is_empty(), + "Argument '{}' is required and can't have a default value", + arg.name + ); + } + + assert_arg_flags(arg); +} + +fn assert_arg_flags(arg: &Arg) { + use ArgSettings::*; + + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if arg.is_set($a) { + let mut s = String::new(); + + $( + if !arg.is_set($b) { + s.push_str(&format!(" ArgSettings::{} is required when ArgSettings::{} is set.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("Argument {:?}\n{}", arg.get_name(), s) + } + } + } + } + + checker!(ForbidEmptyValues requires TakesValue); + checker!(RequireDelimiter requires TakesValue | UseValueDelimiter); + checker!(HidePossibleValues requires TakesValue); + checker!(AllowHyphenValues requires TakesValue); + checker!(RequireEquals requires TakesValue); + checker!(Last requires TakesValue); + checker!(HideDefaultValue requires TakesValue); + checker!(MultipleValues requires TakesValue); + checker!(IgnoreCase requires TakesValue); + checker!(AllowInvalidUtf8 requires TakesValue); +} diff --git a/third_party/rust/clap/src/build/arg/mod.rs b/third_party/rust/clap/src/build/arg/mod.rs new file mode 100644 index 000000000000..053cb2dd4a5d --- /dev/null +++ b/third_party/rust/clap/src/build/arg/mod.rs @@ -0,0 +1,5354 @@ +#[cfg(debug_assertions)] +pub mod debug_asserts; +mod possible_value; +mod settings; +#[cfg(test)] +mod tests; +mod value_hint; + +pub use self::possible_value::PossibleValue; +pub use self::settings::{ArgFlags, ArgSettings}; +pub use self::value_hint::ValueHint; + +// Std +use std::{ + borrow::Cow, + cmp::{Ord, Ordering}, + error::Error, + ffi::OsStr, + fmt::{self, Display, Formatter}, + iter, str, + sync::{Arc, Mutex}, +}; +#[cfg(feature = "env")] +use std::{env, ffi::OsString}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::{ + build::usage_parser::UsageParser, + util::{Id, Key}, + INTERNAL_ERROR_MSG, +}; + +#[cfg(feature = "regex")] +mod regex; + +#[cfg(feature = "regex")] +pub use self::regex::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. +/// +/// # 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) blacklist: Vec, + pub(crate) settings: ArgFlags, + pub(crate) overrides: Vec, + pub(crate) groups: Vec, + pub(crate) requires: Vec<(Option<&'help str>, 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: Option, + 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, Option<&'help OsStr>, 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: ValueHint, +} + +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::{App, 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 name>(mut self, n: S) -> Self { + let name = n.into(); + self.id = Id::from(&*name); + self.name = name; + self + } + + /// 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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("config") + /// .short('c')) + /// .get_matches_from(vec![ + /// "prog", "-c" + /// ]); + /// + /// assert!(m.is_present("config")); + /// ``` + #[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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config")) + /// .get_matches_from(vec![ + /// "prog", "--config" + /// ]); + /// + /// assert!(m.is_present("cfg")); + /// ``` + #[inline] + #[must_use] + pub fn long(mut self, l: &'help str) -> Self { + 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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .alias("alias") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--alias", "cool" + /// ]); + /// assert!(m.is_present("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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_alias('e') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-e", "cool" + /// ]); + /// assert!(m.is_present("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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .aliases(&["do-stuff", "do-tests", "tests"]) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "--do-tests" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_aliases(&['e', 's']) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "-s" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[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::{App, Arg}; + /// let m = App::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.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + /// [`App::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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_alias('t') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-t", "coffee" + /// ]); + /// assert!(m.is_present("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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_aliases(&["something", "awesome", "cool"])) + /// .get_matches_from(vec![ + /// "prog", "--awesome" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + /// [`App::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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_aliases(&['t', 'e'])) + /// .get_matches_from(vec![ + /// "prog", "-t" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[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 + /// + /// [`App`] 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::{App, Arg}; + /// Arg::new("config") + /// .index(1) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("mode") + /// .index(1)) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .get_matches_from(vec![ + /// "prog", "--debug", "fast" + /// ]); + /// + /// assert!(m.is_present("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 + /// [`App`]: crate::App + #[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::AppSettings::DontCollapseArgsInUsage`] 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::AppSettings::ArgsNegateSubcommands`] + /// (or [`crate::AppSettings::SubcommandsNegateReqs`] 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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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 + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input") + /// .index(1)) + /// .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::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input") + /// .index(1)) + /// .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((None, 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::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("exclusive") + /// .takes_value(true) + /// .exclusive(true) + /// .long("exclusive")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input") + /// .index(1)) + /// .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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("verb") + /// .long("verbose") + /// .short('v') + /// .global(true)) + /// .subcommand(App::new("test")) + /// .subcommand(App::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!(sub_m.is_present("verb")); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgMatches::is_present("flag")`]: ArgMatches::is_present() + #[inline] + #[must_use] + pub fn global(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Global) + } else { + self.unset_setting(ArgSettings::Global) + } + } + + /// Specifies that the argument may appear more than once. + /// + /// For flags, this results in the number of occurrences of the flag being recorded. For + /// example `-ddd` or `-d -d -d` would count as three occurrences. For options or arguments + /// that take a value, this *does not* affect how many values they can accept. (i.e. only one + /// at a time is allowed) + /// + /// For example, `--opt val1 --opt val2` is allowed, but `--opt val1 val2` is not. + /// + /// # Examples + /// + /// An example with flags + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("verbose") + /// .multiple_occurrences(true) + /// .short('v')) + /// .get_matches_from(vec![ + /// "prog", "-v", "-v", "-v" // note, -vvv would have same result + /// ]); + /// + /// assert!(m.is_present("verbose")); + /// assert_eq!(m.occurrences_of("verbose"), 3); + /// ``` + /// + /// An example with options + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("file") + /// .multiple_occurrences(true) + /// .takes_value(true) + /// .short('F')) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" + /// ]); + /// + /// assert!(m.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 3); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + #[inline] + #[must_use] + pub fn multiple_occurrences(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::MultipleOccurrences) + } else { + self.unset_setting(ArgSettings::MultipleOccurrences) + } + } + + /// The *maximum* number of occurrences for this argument. + /// + /// For example, if you had a + /// `-v` flag and you wanted up to 3 levels of verbosity you would set `.max_occurrences(3)`, and + /// this argument would be satisfied if the user provided it once or twice or thrice. + /// + /// **NOTE:** This implicitly sets [`Arg::multiple_occurrences(true)`] if the value is greater than 1. + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::new("verbosity") + /// .short('v') + /// .max_occurrences(3); + /// ``` + /// + /// Supplying less than the maximum number of arguments is allowed + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::new("verbosity") + /// .max_occurrences(3) + /// .short('v')) + /// .try_get_matches_from(vec![ + /// "prog", "-vvv" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.occurrences_of("verbosity"), 3); + /// ``` + /// + /// Supplying more than the maximum number of arguments is an error + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("verbosity") + /// .max_occurrences(2) + /// .short('v')) + /// .try_get_matches_from(vec![ + /// "prog", "-vvv" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyOccurrences); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + 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_delimiter(false)`][Arg::use_delimiter] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// + /// assert!(m.is_present("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) + } + } + + /// 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* [`Arg::multiple_occurrences`]. 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::{App, Arg}; + /// let m = App::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.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence + /// 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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .arg(Arg::new("word") + /// .index(1)) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! + /// assert!(!m.is_present("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 [`Arg::multiple_occurrences`] is ok, but multiple values is not. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_occurrences(true) + /// .short('F')) + /// .arg(Arg::new("word") + /// .index(1)) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert!(m.is_present("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::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_occurrences(true) + /// .short('F')) + /// .arg(Arg::new("word") + /// .index(1)) + /// .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::App::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::{App, Arg}; + /// Arg::new("file") + /// .short('f') + /// .number_of_values(3); + /// ``` + /// + /// Not supplying the correct number of values is an error + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// Arg::new("file") + /// .short('f') + /// .max_values(3); + /// ``` + /// + /// Supplying less than the maximum number of values is allowed + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::new("file") + /// .short('f') + /// .min_values(3); + /// ``` + /// + /// Supplying more than the minimum number of values is allowed + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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() + #[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::{App, Arg}; + /// Arg::new("cfg") + /// .long("config") + /// .value_name("FILE") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// Arg::new("speed") + /// .short('s') + /// .value_names(&["fast", "slow"]); + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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::{App, AppSettings, Arg, ValueHint}; + /// App::new("prog") + /// .setting(AppSettings::TrailingVarArg) + /// .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 = value_hint; + self.takes_value(true) + } + + /// Perform a custom validation on the argument value. + /// + /// You provide a closure + /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a + /// message displayed to the user. + /// + /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the + /// message as all errors will appear as + /// `error: Invalid value for '': ` where `` is replaced by the actual + /// arg, and `` is the `String` you return as the error. + /// + /// **NOTE:** There is a small performance hit for using validators, as they are implemented + /// with [`Arc`] pointers. And the value to be checked will be allocated an extra time in order + /// to be passed to the closure. This performance hit is extremely minimal in the grand + /// scheme of things. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// fn has_at(v: &str) -> Result<(), String> { + /// if v.contains("@") { return Ok(()); } + /// Err(String::from("The value did not contain the required @ sigil")) + /// } + /// let res = App::new("prog") + /// .arg(Arg::new("file") + /// .index(1) + /// .validator(has_at)) + /// .try_get_matches_from(vec![ + /// "prog", "some@file" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); + /// ``` + /// [`String`]: std::string::String + /// [`Result`]: std::result::Result + /// [`Err(String)`]: std::result::Result::Err + /// [`Arc`]: std::sync::Arc + #[must_use] + 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 + } + + /// Perform a custom validation on the argument value. + /// + /// See [validator][Arg::validator]. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```rust")] + /// # use clap::{App, Arg}; + /// # use std::ffi::{OsStr, OsString}; + /// # use std::os::unix::ffi::OsStrExt; + /// fn has_ampersand(v: &OsStr) -> Result<(), String> { + /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } + /// Err(String::from("The value did not contain the required & sigil")) + /// } + /// let res = App::new("prog") + /// .arg(Arg::new("file") + /// .index(1) + /// .validator_os(has_ampersand)) + /// .try_get_matches_from(vec![ + /// "prog", "Fish & chips" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); + /// ``` + /// [`String`]: std::string::String + /// [`OsStr`]: std::ffi::OsStr + /// [`OsString`]: std::ffi::OsString + /// [`Result`]: std::result::Result + /// [`Err(String)`]: std::result::Result::Err + /// [`Rc`]: std::rc::Rc + #[must_use] + 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 + } + + /// Validates the argument via the given regular expression. + /// + /// As regular expressions are not very user friendly, the additional `err_message` should + /// describe the expected format in clear words. All notes for [`Arg::validator()`] regarding the + /// error message and performance also hold for `validator_regex`. + /// + /// The regular expression can either be borrowed or moved into `validator_regex`. This happens + /// automatically via [`RegexRef`]'s `Into` implementation. + /// + /// # Performance + /// Regular expressions are expensive to compile. You should prefer sharing your regular expression. + /// We use a [`Cow`]-like internal structure to enable both sharing as well as taking ownership of a + /// provided regular expression. + /// + /// # Examples + /// + /// You can use the classical `"\d+"` regular expression to match digits only: + /// + /// ```rust + /// # use clap::{App, Arg}; + /// use regex::Regex; + /// + /// let digits = Regex::new(r"\d+").unwrap(); + /// + /// let res = App::new("prog") + /// .arg(Arg::new("digits") + /// .index(1) + /// .validator_regex(&digits, "only digits are allowed")) + /// .try_get_matches_from(vec![ + /// "prog", "12345" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("digits"), Some("12345")); + /// ``` + /// + /// However, any valid `Regex` can be used: + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// use regex::Regex; + /// + /// let priority = Regex::new(r"[A-C]").unwrap(); + /// + /// let res = App::new("prog") + /// .arg(Arg::new("priority") + /// .index(1) + /// .validator_regex(priority, "only priorities A, B or C are allowed")) + /// .try_get_matches_from(vec![ + /// "prog", "12345" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.err().unwrap().kind, ErrorKind::ValueValidation) + /// ``` + #[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) + } + }) + } + + /// Add a possible value for this argument. + /// + /// At runtime, `clap` verifies that only one of the specified values was used, or fails with + /// error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** You can use both strings directly or use [`PossibleValue`] if you want more control + /// over single possible values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::new("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium") + /// # ; + /// ``` + /// The same using [`PossibleValue`]: + /// + /// ```rust + /// # use clap::{App, Arg, PossibleValue}; + /// Arg::new("mode").takes_value(true) + /// .possible_value(PossibleValue::new("fast")) + /// // value with a help text + /// .possible_value(PossibleValue::new("slow").help("not that fast")) + /// // value that is hidden from completion and help text + /// .possible_value(PossibleValue::new("medium").hide(true)) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .try_get_matches_from(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + #[must_use] + pub fn possible_value(mut self, value: T) -> Self + where + T: Into>, + { + self.possible_vals.push(value.into()); + self.takes_value(true) + } + + /// Possible values for this argument. + /// + /// At runtime, `clap` verifies that + /// only one of the specified values was used, or fails with an error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** You can use both strings directly or use [`PossibleValue`] if you want more control + /// over single possible values. + /// + /// See also [hide_possible_values][Arg::hide_possible_values]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// Arg::new("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"]) + /// # ; + /// ``` + /// The same using [`PossibleValue`]: + /// + /// ```rust + /// # use clap::{App, Arg, PossibleValue}; + /// Arg::new("mode").takes_value(true).possible_values([ + /// PossibleValue::new("fast"), + /// // value with a help text + /// PossibleValue::new("slow").help("not that fast"), + /// // value that is hidden from completion and help text + /// PossibleValue::new("medium").hide(true), + /// ]) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"])) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"])) + /// .try_get_matches_from(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + #[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::{App, Arg}; + /// let m = App::new("pv") + /// .arg(Arg::new("option") + /// .long("--option") + /// .takes_value(true) + /// .ignore_case(true) + /// .possible_value("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::{App, Arg}; + /// let m = App::new("pv") + /// .arg(Arg::new("option") + /// .short('o') + /// .long("--option") + /// .takes_value(true) + /// .ignore_case(true) + /// .multiple_values(true) + /// .possible_values(&["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::{App, Arg}; + /// let m = App::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::{App, Arg, ErrorKind}; + /// let res = App::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) + } + } + + /// The argument's values can be invalid UTF-8 and should *not* be treated as an error. + /// + /// **NOTE:** Using argument values with invalid UTF-8 code points requires using + /// [`ArgMatches::value_of_os`], [`ArgMatches::values_of_os`], [`ArgMatches::value_of_lossy`], + /// or [`ArgMatches::values_of_lossy`] for those particular arguments which may contain invalid + /// UTF-8 values. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```rust")] + /// # use clap::{App, Arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// let r = App::new("myprog") + /// .arg(Arg::new("arg").allow_invalid_utf8(true)) + /// .try_get_matches_from(vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9]) + /// ]); + /// + /// assert!(r.is_ok()); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]); + /// ``` + /// [`ArgMatches::value_of_os`]: crate::ArgMatches::value_of_os() + /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os() + /// [`ArgMatches::value_of_lossy`]: crate::ArgMatches::value_of_lossy() + /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy() + #[inline] + #[must_use] + pub fn allow_invalid_utf8(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowInvalidUtf8) + } else { + self.unset_setting(ArgSettings::AllowInvalidUtf8) + } + } + + /// Don't allow an argument to accept explicitly empty values. + /// + /// An empty value must be specified at the command line with an explicit `""`, `''`, or + /// `--option=` + /// + /// **NOTE:** By default empty values are allowed. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`]. + /// + /// # Examples + /// + /// The default is allowing empty values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .short('v') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--config=" + /// ]); + /// + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("cfg"), Some("")); + /// ``` + /// + /// By adding this setting, we can forbid empty values. + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .short('v') + /// .takes_value(true) + /// .forbid_empty_values(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--config=" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); + /// ``` + #[inline] + #[must_use] + 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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let delims = App::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .use_delimiter(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("option")); + /// assert_eq!(delims.occurrences_of("option"), 1); + /// 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::{App, Arg}; + /// let nodelims = App::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(nodelims.is_present("option")); + /// assert_eq!(nodelims.occurrences_of("option"), 1); + /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); + /// ``` + /// [`Arg::value_delimiter`]: Arg::value_delimiter() + #[inline] + #[must_use] + pub fn use_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) + } + } + + /// Separator between the arguments values, defaults to `,` (comma). + /// + /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`] + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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_delimiter(true)`]: Arg::use_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_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_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::{App, Arg}; + /// let delims = App::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_delimiter(true) + /// .require_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("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::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_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::{App, Arg}; + /// let delims = App::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.is_present("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::>(), ["val1", "val2", "val3"]); + /// ``` + #[inline] + #[must_use] + pub fn require_delimiter(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireDelimiter) + } else { + self.unset_setting(ArgSettings::RequireDelimiter) + } + } + + /// 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::{App, 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::{App, Arg}; + /// let m = App::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::AppSettings::TrailingVarArg`] + /// 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::is_present`] will + /// still return `true`. If you wish to determine whether the argument was used at runtime or + /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* + /// used at runtime. + /// + /// **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)`]. + /// + /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in + /// conjunction as it ensures that some argument will always be present. + /// + /// # Examples + /// + /// First we use the default value without providing any value at runtime. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 0); + /// ``` + /// + /// Next we provide a value at runtime to override the default. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// ``` + /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`ArgMatches::is_present`]: crate::ArgMatches::is_present() + /// [`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 + /// + /// Here is an implementation of the common POSIX style `--color` argument. + /// + /// ```rust + /// # use clap::{App, Arg}; + /// + /// macro_rules! app { + /// () => {{ + /// App::new("prog") + /// .arg(Arg::new("color").long("color") + /// .value_name("WHEN") + /// .possible_values(["always", "auto", "never"]) + /// .default_value("auto") + /// .overrides_with("color") + /// .min_values(0) + /// .require_equals(true) + /// .default_missing_value("always") + /// .help("Specify WHEN to colorize output.") + /// ) + /// }}; + /// } + /// + /// let mut m; + /// + /// // first, we'll provide no arguments + /// + /// m = app!().get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("auto")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 0); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// + /// m = app!().get_matches_from(vec![ + /// "prog", "--color=never" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("never")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 1); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// + /// m = app!().get_matches_from(vec![ + /// "prog", "--color" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("always")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 1); + /// ``` + /// [`ArgMatches::occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`ArgMatches::is_present`]: ArgMatches::is_present() + /// [`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::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::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::{App, Arg}; + /// + /// env::set_var("TRUE_FLAG", "true"); + /// env::set_var("FALSE_FLAG", "0"); + /// + /// let m = App::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::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::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::{App, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = App::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::{App, Arg}; + /// + /// env::set_var("MY_FLAG_MULTI", "env1,env2"); + /// + /// let m = App::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG_MULTI") + /// .takes_value(true) + /// .multiple_values(true) + /// .use_delimiter(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.values_of("flag").unwrap().collect::>(), vec!["env1", "env2"]); + /// ``` + /// [`ArgMatches::occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`ArgMatches::is_present`]: ArgMatches::is_present() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::use_delimiter(true)`]: Arg::use_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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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 = Some(ord); + self + } + + /// Override the [current] help section. + /// + /// [current]: crate::App::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 consider using + /// [`crate::AppSettings::NextLineHelp`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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][Arg::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 + /// [`AppSettings::HidePossibleValues`][crate::AppSettings::HidePossibleValues]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .possible_values(["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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, 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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, 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::{App, Arg}; + /// let m = App::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.is_present("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::{App, 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::{App, Arg}; + /// let m = App::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.is_present("mode")); + /// assert!(m.is_present("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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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, 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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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.key(), *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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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`. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq("other_arg", "value") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let res = App::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 = App::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 = App::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 = App::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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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((Some(val), arg_id.into())); + self + } + + /// Allows multiple conditional requirements. + /// + /// The requirement will only become valid if this arg's value equals `val`. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg, ErrorKind}; + /// let res = App::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)| (Some(*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. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input") + /// .index(1)) + /// .arg(Arg::new("output") + /// .index(2)) + /// .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::{App, Arg, ErrorKind}; + /// let res = App::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_all(&["input", "output"]) + /// .long("config")) + /// .arg(Arg::new("input") + /// .index(1)) + /// .arg(Arg::new("output") + /// .index(2)) + /// .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| (None, 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. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg, ErrorKind}; + /// let res = App::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. + /// + /// **NOTE:** An argument is considered present when there is a [`Arg::default_value`] + /// + /// # 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::{App, Arg, ErrorKind}; + /// let res = App::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") + /// .index(1)) + /// .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().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 + /// + /// **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::{App, Arg}; + /// # use clap::{App, arg}; + /// let m = App::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::{App, arg}; + /// let m = App::new("posix") + /// .arg(arg!(--flag "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["posix", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + /// + /// 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::{App, arg}; + /// let m = App::new("posix") + /// .arg(arg!(--flag ... "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 4); + /// ``` + /// + /// Now notice with options (which *do not* set + /// [`Arg::multiple_occurrences`]), it's as if only the last + /// occurrence happened. + /// + /// ``` + /// # use clap::{App, arg}; + /// let m = App::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.occurrences_of("opt"), 1); + /// assert_eq!(m.value_of("opt"), Some("other")); + /// ``` + /// + /// This will also work when [`Arg::multiple_values`] is enabled: + /// + /// ``` + /// # use clap::{App, Arg}; + /// let m = App::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.occurrences_of("opt"), 1); + /// 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::{App, arg}; + /// let m = App::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.occurrences_of("opt"), 2); + /// 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 + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, arg}; + /// let m = App::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_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 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) + } + + /// Get the list of the possible values for this argument, if any + #[inline] + pub fn get_possible_values(&self) -> Option<&[PossibleValue]> { + if self.possible_vals.is_empty() { + None + } else { + Some(&self.possible_vals) + } + } + + /// 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 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 + } + + /// Get information on if this argument is global or not + pub fn get_global(&self) -> bool { + self.is_set(ArgSettings::Global) + } + + /// 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() + } +} + +/// Deprecated +impl<'help> Arg<'help> { + /// Deprecated, replaced with [`Arg::new`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::new`")] + 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")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + 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!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + pub fn from_usage(u: &'help str) -> Self { + UsageParser::from_usage(u).parse() + } + + /// Deprecated, replaced with [`Arg::required_unless_present`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`")] + #[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`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_all`" + )] + #[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`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_any`" + )] + #[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`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`")] + #[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`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`")] + #[must_use] + pub fn required_ifs(self, ifs: &[(T, &'help str)]) -> Self { + self.required_if_eq_any(ifs) + } + + /// Deprecated, replaced with [`Arg::hide`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`")] + #[inline] + #[must_use] + pub fn hidden(self, yes: bool) -> Self { + self.hide(yes) + } + + /// Deprecated, replaced with [`Arg::ignore_case`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`")] + #[inline] + #[must_use] + pub fn case_insensitive(self, yes: bool) -> Self { + self.ignore_case(yes) + } + + /// Deprecated, replaced with [`Arg::forbid_empty_values`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`")] + #[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`] + #[deprecated( + since = "3.0.0", + note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" + )] + #[must_use] + pub fn multiple(self, yes: bool) -> Self { + self.multiple_occurrences(yes).multiple_values(yes) + } + + /// Deprecated, replaced with [`Arg::hide_short_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`")] + #[inline] + #[must_use] + pub fn hidden_short_help(self, yes: bool) -> Self { + self.hide_short_help(yes) + } + + /// Deprecated, replaced with [`Arg::hide_long_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`")] + #[inline] + #[must_use] + pub fn hidden_long_help(self, yes: bool) -> Self { + self.hide_long_help(yes) + } + + /// Deprecated, replaced with [`Arg::setting`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`")] + #[must_use] + pub fn set(self, s: ArgSettings) -> Self { + self.setting(s) + } + + /// Deprecated, replaced with [`Arg::unset_setting`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`")] + #[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 (self.is_set(ArgSettings::UseValueDelimiter) + || self.is_set(ArgSettings::RequireDelimiter)) + && 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_set(ArgSettings::MultipleOccurrences) { + // 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_set(ArgSettings::TakesValue) || 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_set(ArgSettings::MultipleValues) + || self.is_set(ArgSettings::MultipleOccurrences)) + && !mult_vals + { + "..." + } else { + "" + } + } + + // Used for positionals when printing + pub(crate) fn name_no_brackets(&self) -> Cow { + debug!("Arg::name_no_brackets:{}", self.name); + let mut delim = String::new(); + delim.push(if self.is_set(ArgSettings::RequireDelimiter) { + self.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }); + 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_set(ArgSettings::MultipleValues) | self.is_set(ArgSettings::MultipleOccurrences) + } + + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.unwrap_or(999) + } +} + +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)?; + } + if !self.is_positional() && self.is_set(ArgSettings::TakesValue) { + let sep = if self.is_set(ArgSettings::RequireEquals) { + "=" + } else { + " " + }; + write!(f, "{}", sep)?; + } + if self.is_set(ArgSettings::TakesValue) || self.is_positional() { + display_arg_val(self, |s, _| write!(f, "{}", s))?; + } + + 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("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_set(ArgSettings::MultipleValues); + let mult_occ = arg.is_set(ArgSettings::MultipleOccurrences); + let delim = if arg.is_set(ArgSettings::RequireDelimiter) { + arg.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }; + 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()); + let mut it = iter::repeat(arg_name).take(num_vals).peekable(); + while let Some(arg_name) = it.next() { + write(&arg_name, true)?; + if it.peek().is_some() { + write(&delim.to_string(), 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.to_string(), false)?; + } + } + if (num_val_names == 1 && mult_val) || (arg.is_positional() && mult_occ) { + 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); + let mut it = iter::repeat(&arg_name).take(num_vals).peekable(); + while let Some(arg_name) = it.next() { + write(arg_name, true)?; + if it.peek().is_some() { + write(&delim.to_string(), 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(()) +} + +// 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!(&*format!("{}", f), "--flag"); + + let mut f2 = Arg::new("flg"); + f2.short = Some('f'); + + assert_eq!(&*format!("{}", f2), "-f"); + } + + #[test] + fn flag_display_single_alias() { + let mut f = Arg::new("flg"); + f.long = Some("flag"); + f.aliases = vec![("als", true)]; + + assert_eq!(&*format!("{}", f), "--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!(&*format!("{}", f), "-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!(&*format!("{}", f), "-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!(&*format!("{}", f), "-a"); + } + + // Options + + #[test] + fn option_display_multiple_occurrences() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(&*format!("{}", o), "--option "); + } + + #[test] + fn option_display_multiple_values() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_values(true); + + assert_eq!(&*format!("{}", o), "--option ..."); + } + + #[test] + fn option_display2() { + let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]); + + assert_eq!(&*format!("{}", o2), "-o "); + } + + #[test] + fn option_display3() { + let o2 = Arg::new("opt") + .short('o') + .takes_value(true) + .multiple_values(true) + .value_names(&["file", "name"]); + + assert_eq!(&*format!("{}", o2), "-o "); + } + + #[test] + fn option_display_single_alias() { + let o = Arg::new("opt") + .takes_value(true) + .long("option") + .visible_alias("als"); + + assert_eq!(&*format!("{}", o), "--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!(&*format!("{}", o), "--option "); + } + + #[test] + fn option_display_single_short_alias() { + let o = Arg::new("opt") + .takes_value(true) + .short('a') + .visible_short_alias('b'); + + assert_eq!(&*format!("{}", o), "-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!(&*format!("{}", o), "-a "); + } + + // Positionals + + #[test] + fn positional_display_multiple_values() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_values(true); + + assert_eq!(&*format!("{}", p), "..."); + } + + #[test] + fn positional_display_multiple_occurrences() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(&*format!("{}", p), "..."); + } + + #[test] + fn positional_display_required() { + let p2 = Arg::new("pos").index(1).required(true); + + assert_eq!(&*format!("{}", p2), ""); + } + + #[test] + fn positional_display_val_names() { + let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]); + + assert_eq!(&*format!("{}", p2), " "); + } + + #[test] + fn positional_display_val_names_req() { + let p2 = Arg::new("pos") + .index(1) + .required(true) + .value_names(&["file1", "file2"]); + + assert_eq!(&*format!("{}", p2), " "); + } +} diff --git a/third_party/rust/clap/src/build/arg/possible_value.rs b/third_party/rust/clap/src/build/arg/possible_value.rs new file mode 100644 index 000000000000..0bd795c3f3a7 --- /dev/null +++ b/third_party/rust/clap/src/build/arg/possible_value.rs @@ -0,0 +1,209 @@ +use std::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") +/// .possible_value(PossibleValue::new("fast")) +/// .possible_value(PossibleValue::new("slow").help("slower than fast")) +/// .possible_value(PossibleValue::new("secret speed").hide(true)); +/// ``` +/// [Args]: crate::Arg +/// [possible values]: crate::Arg::possible_value() +/// [hide]: PossibleValue::hide() +/// [help]: PossibleValue::help() +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct PossibleValue<'help> { + pub(crate) name: &'help str, + pub(crate) help: Option<&'help str>, + pub(crate) aliases: Vec<&'help str>, // (name, visible) + pub(crate) 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 + } + + /// Should the value be hidden from help messages and completion + #[inline] + pub fn is_hidden(&self) -> bool { + self.hide + } + + /// Get the name if argument value is not hidden, `None` otherwise + pub fn get_visible_name(&self) -> Option<&'help str> { + if self.hide { + None + } else { + Some(self.name) + } + } + + /// 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/third_party/rust/clap/src/build/arg/regex.rs b/third_party/rust/clap/src/build/arg/regex.rs new file mode 100644 index 000000000000..bf3a78e0c21d --- /dev/null +++ b/third_party/rust/clap/src/build/arg/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/third_party/rust/clap/src/build/arg/settings.rs b/third_party/rust/clap/src/build/arg/settings.rs new file mode 100644 index 000000000000..048944bb5144 --- /dev/null +++ b/third_party/rust/clap/src/build/arg/settings.rs @@ -0,0 +1,284 @@ +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +// Third party +use bitflags::bitflags; + +#[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 { + /// Specifies that an arg must be used + Required, + /// Allows an arg to accept multiple values + MultipleValues, + /// Allows an arg to appear multiple times + MultipleOccurrences, + /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and + /// [`ArgSettings::MultipleValues`] + #[deprecated( + since = "3.0.0", + note = "Split into `ArgSettings::MultipleOccurrences` (most likely what you want) and `ArgSettings::MultipleValues`" + )] + Multiple, + /// Forbids an arg from accepting empty values such as `""` + ForbidEmptyValues, + /// Sets an arg to be global (i.e. exist in all subcommands) + Global, + /// Hides an arg from the help message + Hidden, + /// Allows an argument to take a value (such as `--option value`) + TakesValue, + /// Enables a delimiter to break up arguments `--option val1,val2,val3` becomes three values + /// (`val1`, `val2`, and `val3`) instead of the default one (`val1,val2,val3`) + UseValueDelimiter, + /// Tells an arg to display it's help on the line below the arg itself in the help message + NextLineHelp, + /// Says that arg *must* use a delimiter to separate values + RequireDelimiter, + /// Hides the possible values from the help message + HidePossibleValues, + /// Allows values that start with a hyphen + AllowHyphenValues, + /// Deprecated, replaced with [`ArgSettings::AllowHyphenValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `ArgSettings::AllowHyphenValues`" + )] + AllowLeadingHyphen, + /// Requires that an equals be used to provide a value to an option such as `--option=value` + RequireEquals, + /// Says that a positional arg will be the last positional, and requires `--` to be accessed. + /// It can also be accessed early (i.e. before other positionals) by providing `--` + Last, + /// Hides the default value from the help message + HideDefaultValue, + /// Possible values become case insensitive + IgnoreCase, + /// Deprecated, replaced with [`ArgSettings::IgnoreCase`] + #[deprecated(since = "3.0.0", note = "Replaced with `ArgSettings::IgnoreCase`")] + CaseInsensitive, + /// Hides environment variable arguments from the help message + #[cfg(feature = "env")] + HideEnv, + /// Hides any values currently assigned to ENV variables in the help message (good for sensitive + /// information) + #[cfg(feature = "env")] + HideEnvValues, + /// The argument should **not** be shown in short help text + HiddenShortHelp, + /// The argument should **not** be shown in long help text + HiddenLongHelp, + /// Specifies that option values that are invalid UTF-8 should *not* be treated as an error. + AllowInvalidUtf8, + /// Specifies that option should exist on its own. + /// Having any other arguments present at runtime is an error. + 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/third_party/rust/clap/src/build/arg/tests.rs b/third_party/rust/clap/src/build/arg/tests.rs new file mode 100644 index 000000000000..6a6506e43f9b --- /dev/null +++ b/third_party/rust/clap/src/build/arg/tests.rs @@ -0,0 +1,8 @@ +use crate::Arg; + +// 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/third_party/rust/clap/src/build/arg/value_hint.rs b/third_party/rust/clap/src/build/arg/value_hint.rs new file mode 100644 index 000000000000..b61a3e778e05 --- /dev/null +++ b/third_party/rust/clap/src/build/arg/value_hint.rs @@ -0,0 +1,95 @@ +use std::str::FromStr; + +/// Provide shell with hint on how to complete an argument. +/// +/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument. +/// +/// See the `clap_complete` crate for completion script generation. +/// +/// Overview of which hints are supported by which shell: +/// +/// | Hint | zsh | fish[^1]| +/// | ---------------------- | --- | ------- | +/// | `AnyPath` | Yes | Yes | +/// | `FilePath` | Yes | Yes | +/// | `DirPath` | Yes | Yes | +/// | `ExecutablePath` | Yes | Partial | +/// | `CommandName` | Yes | Yes | +/// | `CommandString` | Yes | Partial | +/// | `CommandWithArguments` | Yes | | +/// | `Username` | Yes | Yes | +/// | `Hostname` | Yes | Yes | +/// | `Url` | Yes | | +/// | `EmailAddress` | Yes | | +/// +/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not +/// positional arguments. +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum ValueHint { + /// Default value if hint is not specified. Follows shell default behavior, which is usually + /// auto-completing filenames. + Unknown, + /// None of the hints below apply. Disables shell completion for this argument. + Other, + /// Any existing path. + AnyPath, + /// Path to a file. + FilePath, + /// Path to a directory. + DirPath, + /// Path to an executable file. + ExecutablePath, + /// Name of a command, without arguments. May be relative to PATH, or full path to executable. + CommandName, + /// A single string containing a command and its arguments. + CommandString, + /// Capture the remaining arguments as a command name and arguments for that command. This is + /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`. + /// + /// This hint is special, the argument must be a positional argument and have + /// [`.multiple_values(true)`] and App must use [`AppSettings::TrailingVarArg`]. The result is that the + /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to + /// parse the `-la` argument itself. + /// + /// [`AppSettings::TrailingVarArg`]: crate::AppSettings::TrailingVarArg + /// [`.multiple_values(true)`]: crate::Arg::multiple_values() + CommandWithArguments, + /// Name of a local operating system user. + Username, + /// Host name of a computer. + /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames. + Hostname, + /// Complete web address. + Url, + /// Email address. + EmailAddress, +} + +impl Default for ValueHint { + fn default() -> Self { + ValueHint::Unknown + } +} + +impl FromStr for ValueHint { + type Err = String; + fn from_str(s: &str) -> Result::Err> { + Ok(match &*s.to_ascii_lowercase() { + "unknown" => ValueHint::Unknown, + "other" => ValueHint::Other, + "anypath" => ValueHint::AnyPath, + "filepath" => ValueHint::FilePath, + "dirpath" => ValueHint::DirPath, + "executablepath" => ValueHint::ExecutablePath, + "commandname" => ValueHint::CommandName, + "commandstring" => ValueHint::CommandString, + "commandwitharguments" => ValueHint::CommandWithArguments, + "username" => ValueHint::Username, + "hostname" => ValueHint::Hostname, + "url" => ValueHint::Url, + "emailaddress" => ValueHint::EmailAddress, + _ => return Err(format!("unknown ValueHint: `{}`", s)), + }) + } +} diff --git a/third_party/rust/clap/src/args/group.rs b/third_party/rust/clap/src/build/arg_group.rs similarity index 50% rename from third_party/rust/clap/src/args/group.rs rename to third_party/rust/clap/src/build/arg_group.rs index a2992b2970dc..49d95a869fe2 100644 --- a/third_party/rust/clap/src/args/group.rs +++ b/third_party/rust/clap/src/build/arg_group.rs @@ -1,12 +1,12 @@ -#[cfg(feature = "yaml")] -use std::collections::BTreeMap; -use std::fmt::{Debug, Formatter, Result}; +// Internal +use crate::util::{Id, Key}; #[cfg(feature = "yaml")] use yaml_rust::Yaml; -/// `ArgGroup`s are a family of related [arguments] and way for you to express, "Any of these -/// arguments". By placing arguments in a logical group, you can create easier requirement and +/// 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. /// @@ -37,17 +37,16 @@ use yaml_rust::Yaml; /// the arguments from the specified group is present at runtime. /// /// ```rust -/// # use clap::{App, ArgGroup, ErrorKind}; +/// # use clap::{App, arg, ArgGroup, ErrorKind}; /// let result = App::new("app") -/// .args_from_usage( -/// "--set-ver [ver] 'set the version manually' -/// --major 'auto increase major' -/// --minor 'auto increase minor' -/// --patch 'auto increase patch'") -/// .group(ArgGroup::with_name("vers") +/// .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)) -/// .get_matches_from_safe(vec!["app", "--major", "--patch"]); +/// .try_get_matches_from(vec!["app", "--major", "--patch"]); /// // Because we used two args in the group it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); @@ -56,81 +55,77 @@ use yaml_rust::Yaml; /// This next example shows a passing parse of the same scenario /// /// ```rust -/// # use clap::{App, ArgGroup}; +/// # use clap::{App, arg, ArgGroup}; /// let result = App::new("app") -/// .args_from_usage( -/// "--set-ver [ver] 'set the version manually' -/// --major 'auto increase major' -/// --minor 'auto increase minor' -/// --patch 'auto increase patch'") -/// .group(ArgGroup::with_name("vers") +/// .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)) -/// .get_matches_from_safe(vec!["app", "--major"]); +/// .try_get_matches_from(vec!["app", "--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.is_present("vers")); /// // we could also alternatively check each arg individually (not shown here) /// ``` -/// [`ArgGroup::multiple(true)`]: ./struct.ArgGroup.html#method.multiple -/// [arguments]: ./struct.Arg.html -/// [conflict]: ./struct.Arg.html#method.conflicts_with -/// [requirement]: ./struct.Arg.html#method.requires -#[derive(Default)] -pub struct ArgGroup<'a> { - #[doc(hidden)] - pub name: &'a str, - #[doc(hidden)] - pub args: Vec<&'a str>, - #[doc(hidden)] - pub required: bool, - #[doc(hidden)] - pub requires: Option>, - #[doc(hidden)] - pub conflicts: Option>, - #[doc(hidden)] - pub multiple: bool, +/// [`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<'a> ArgGroup<'a> { - /// Creates a new instance of `ArgGroup` using a unique string name. The name will be used to - /// get values from the group or refer to the group inside of conflict and requirement rules. +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::{App, ArgGroup}; - /// ArgGroup::with_name("config") + /// ArgGroup::new("config") /// # ; /// ``` - pub fn with_name(n: &'a str) -> Self { - ArgGroup { - name: n, - required: false, - args: vec![], - requires: None, - conflicts: None, - multiple: false, - } + pub fn new>(n: S) -> Self { + ArgGroup::default().name(n) } - /// Creates a new instance of `ArgGroup` from a .yml (YAML) file. + /// Sets the group name. /// /// # Examples /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::ArgGroup; - /// # fn main() { - /// let yml = load_yaml!("group.yml"); - /// let ag = ArgGroup::from_yaml(yml); - /// # } + /// ```rust + /// # use clap::{App, ArgGroup}; + /// ArgGroup::default().name("config") + /// # ; /// ``` - #[cfg(feature = "yaml")] - pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> { - ArgGroup::from(y.as_hash().unwrap()) + #[must_use] + pub fn name>(mut self, n: S) -> Self { + self.name = n.into(); + self.id = Id::from(&self.name); + self } /// Adds an [argument] to this group by name @@ -140,11 +135,11 @@ impl<'a> ArgGroup<'a> { /// ```rust /// # use clap::{App, Arg, ArgGroup}; /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") + /// .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"]); @@ -153,14 +148,10 @@ impl<'a> ArgGroup<'a> { /// // but we can also check individually if needed /// assert!(m.is_present("flag")); /// ``` - /// [argument]: ./struct.Arg.html - pub fn arg(mut self, n: &'a str) -> Self { - assert!( - self.name != n, - "ArgGroup '{}' can not have same name as arg inside it", - &*self.name - ); - self.args.push(n); + /// [argument]: crate::Arg + #[must_use] + pub fn arg(mut self, arg_id: T) -> Self { + self.args.push(arg_id.into()); self } @@ -171,11 +162,11 @@ impl<'a> ArgGroup<'a> { /// ```rust /// # use clap::{App, Arg, ArgGroup}; /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") + /// .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... @@ -183,15 +174,16 @@ impl<'a> ArgGroup<'a> { /// // but we can also check individually if needed /// assert!(m.is_present("flag")); /// ``` - /// [arguments]: ./struct.Arg.html - pub fn args(mut self, ns: &[&'a str]) -> Self { + /// [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`) + /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) /// /// # Examples /// @@ -201,11 +193,11 @@ impl<'a> ArgGroup<'a> { /// ```rust /// # use clap::{App, Arg, ArgGroup}; /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") + /// .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"]); @@ -218,30 +210,33 @@ impl<'a> ArgGroup<'a> { /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") /// .args(&["flag", "color"])) - /// .get_matches_from_safe(vec!["myprog", "-f", "-c"]); + /// .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']: ./struct.Arg.html - pub fn multiple(mut self, m: bool) -> Self { - self.multiple = m; + /// + /// [`Arg`]: crate::Arg + #[inline] + #[must_use] + pub fn multiple(mut self, yes: bool) -> Self { + self.multiple = yes; self } - /// Sets the group as required or not. A required group will be displayed in the usage string - /// of the application in the format ``. A required `ArgGroup` simply states - /// that one argument from this group *must* be present at runtime (unless - /// conflicting with another argument). + /// Require an argument from the group to be present when parsing. /// - /// **NOTE:** This setting only applies to the current [`App`] / [`SubCommand`], and not + /// 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 [`App`] / [`Subcommand`]s, and not /// globally. /// /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with @@ -249,203 +244,224 @@ impl<'a> ArgGroup<'a> { /// 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." /// + /// **NOTE:** An argument is considered present when there is a + /// [`Arg::default_value`](crate::Arg::default_value) + /// /// # Examples /// /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") /// .args(&["flag", "color"]) /// .required(true)) - /// .get_matches_from_safe(vec!["myprog"]); + /// .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); /// ``` - /// [`App`]: ./struct.App.html - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`ArgGroup::multiple`]: ./struct.ArgGroup.html#method.multiple - pub fn required(mut self, r: bool) -> Self { - self.required = r; + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgGroup::multiple`]: ArgGroup::multiple() + /// [`App`]: crate::App + #[inline] + #[must_use] + pub fn required(mut self, yes: bool) -> Self { + self.required = yes; self } - /// Sets the requirement rules of this group. 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. + /// Specify an argument or group that must be present when this group is. /// - /// **NOTE:** The name provided may be an argument, or group name + /// 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:** An argument is considered present when there is a + /// [`Arg::default_value`](crate::Arg::default_value) + /// + /// **NOTE:** The name provided may be an argument or group name /// /// # Examples /// /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .group(ArgGroup::with_name("req_flags") + /// .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")) - /// .get_matches_from_safe(vec!["myprog", "-c"]); + /// .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]: ./struct.ArgGroup.html#method.required - /// [argument requirement rules]: ./struct.Arg.html#method.requires - pub fn requires(mut self, n: &'a str) -> Self { - if let Some(ref mut reqs) = self.requires { - reqs.push(n); - } else { - self.requires = Some(vec![n]); - } + /// [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 } - /// Sets the requirement rules of this group. 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. + /// Specify arguments or groups that must be present when this group is. /// - /// **NOTE:** The names provided may be an argument, or group name + /// 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 + /// + /// **NOTE:** An argument is considered present when there is a + /// [`Arg::default_value`](crate::Arg::default_value) /// /// # Examples /// /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .arg(Arg::with_name("verb") - /// .short("v")) - /// .group(ArgGroup::with_name("req_flags") + /// .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"])) - /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); + /// .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]: ./struct.ArgGroup.html#method.required - /// [argument requirement rules]: ./struct.Arg.html#method.requires_all - pub fn requires_all(mut self, ns: &[&'a str]) -> Self { + /// [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 } - /// Sets the exclusion rules of this group. 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. + /// 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 /// + /// **NOTE:** An argument is considered present when there is a + /// [`Arg::default_value`](crate::Arg::default_value) + /// /// # Examples /// /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .group(ArgGroup::with_name("req_flags") + /// .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")) - /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); + /// .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]: ./struct.Arg.html#method.conflicts_with - pub fn conflicts_with(mut self, n: &'a str) -> Self { - if let Some(ref mut confs) = self.conflicts { - confs.push(n); - } else { - self.conflicts = Some(vec![n]); - } + /// [argument exclusion rules]: crate::Arg::conflicts_with() + #[must_use] + pub fn conflicts_with(mut self, id: T) -> Self { + self.conflicts.push(id.into()); self } - /// Sets the exclusion rules of this group. 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. + /// 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 /// + /// **NOTE:** An argument is considered present when there is a + /// [`Arg::default_value`](crate::Arg::default_value) + /// /// # Examples /// /// ```rust /// # use clap::{App, Arg, ArgGroup, ErrorKind}; /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .arg(Arg::with_name("verb") - /// .short("v")) - /// .group(ArgGroup::with_name("req_flags") + /// .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"])) - /// .get_matches_from_safe(vec!["myprog", "-c", "-v"]); + /// .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]: ./struct.Arg.html#method.conflicts_with_all - pub fn conflicts_with_all(mut self, ns: &[&'a str]) -> Self { + /// + /// [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 } -} -impl<'a> Debug for ArgGroup<'a> { - fn fmt(&self, f: &mut Formatter) -> Result { - write!( - f, - "{{\n\ - \tname: {:?},\n\ - \targs: {:?},\n\ - \trequired: {:?},\n\ - \trequires: {:?},\n\ - \tconflicts: {:?},\n\ - }}", - self.name, self.args, self.required, self.requires, self.conflicts - ) + /// Deprecated, replaced with [`ArgGroup::new`] + #[deprecated(since = "3.0.0", note = "Replaced with `ArgGroup::new`")] + 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")] + #[deprecated( + since = "3.0.0", + note = "Maybe clap::Parser would fit your use case? (Issue #3087)" + )] + pub fn from_yaml(yaml: &'help Yaml) -> Self { + Self::from(yaml) } } -impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> { - fn from(g: &'z ArgGroup<'a>) -> Self { +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(), @@ -456,18 +472,22 @@ impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> { } } +/// 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<'a> From<&'a BTreeMap> for ArgGroup<'a> { - fn from(b: &'a BTreeMap) -> Self { +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_yml = b.keys().nth(0).expect("failed to get name"); - let name_str = name_yml + 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; - b.get(name_yml) + 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") @@ -479,18 +499,18 @@ impl<'a> From<&'a BTreeMap> for ArgGroup<'a> { 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!(v, a, arg), + "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!(v, a, requires), - "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), + "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.name = ys; + a = a.name(ys); } a } @@ -514,7 +534,7 @@ mod test { #[test] fn groups() { - let g = ArgGroup::with_name("test") + let g = ArgGroup::new("test") .arg("a1") .arg("a4") .args(&["a2", "a3"]) @@ -526,52 +546,18 @@ mod test { .requires_all(&["r2", "r3"]) .requires("r4"); - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; + 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, Some(reqs)); - assert_eq!(g.conflicts, Some(confs)); - } - - #[test] - fn test_debug() { - let g = ArgGroup::with_name("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", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; - - let debug_str = format!( - "{{\n\ - \tname: \"test\",\n\ - \targs: {:?},\n\ - \trequired: {:?},\n\ - \trequires: {:?},\n\ - \tconflicts: {:?},\n\ - }}", - args, - true, - Some(reqs), - Some(confs) - ); - assert_eq!(&*format!("{:?}", g), &*debug_str); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); } #[test] fn test_from() { - let g = ArgGroup::with_name("test") + let g = ArgGroup::new("test") .arg("a1") .arg("a4") .args(&["a2", "a3"]) @@ -583,18 +569,18 @@ mod test { .requires_all(&["r2", "r3"]) .requires("r4"); - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; + 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, Some(reqs)); - assert_eq!(g2.conflicts, Some(confs)); + assert_eq!(g2.requires, reqs); + assert_eq!(g2.conflicts, confs); } #[cfg(feature = "yaml")] - #[cfg_attr(feature = "yaml", test)] + #[test] fn test_yaml() { let g_yaml = "name: test args: @@ -612,20 +598,28 @@ requires: - r2 - r3 - r4"; - let yml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; - let g = ArgGroup::from_yaml(yml); - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; + 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, Some(reqs)); - assert_eq!(g.conflicts, Some(confs)); + 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<'a> Clone for ArgGroup<'a> { +impl Clone for ArgGroup<'_> { fn clone(&self) -> Self { ArgGroup { + id: self.id.clone(), name: self.name, required: self.required, args: self.args.clone(), diff --git a/third_party/rust/clap/src/args/macros.rs b/third_party/rust/clap/src/build/macros.rs similarity index 59% rename from third_party/rust/clap/src/args/macros.rs rename to third_party/rust/clap/src/build/macros.rs index ac4b1a2d5514..5be4d205e0b6 100644 --- a/third_party/rust/clap/src/args/macros.rs +++ b/third_party/rust/clap/src/build/macros.rs @@ -24,7 +24,11 @@ macro_rules! yaml_tuple3 { 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_str!(tup[2])); + $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"); } @@ -38,7 +42,7 @@ macro_rules! yaml_tuple3 { #[cfg(feature = "yaml")] macro_rules! yaml_vec_or_str { - ($v:ident, $a:ident, $c:ident) => {{ + ($a:ident, $v:ident, $c:ident) => {{ let maybe_vec = $v.as_vec(); if let Some(vec) = maybe_vec { for ys in vec { @@ -62,10 +66,30 @@ macro_rules! yaml_vec_or_str { }}; } +#[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() { + if !$v.is_null() { Some( $v.as_str() .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), @@ -76,6 +100,17 @@ macro_rules! yaml_opt_str { }}; } +#[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) => {{ @@ -84,6 +119,13 @@ macro_rules! yaml_str { }}; } +#[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) => {{ @@ -100,16 +142,6 @@ macro_rules! yaml_to_bool { }}; } -#[cfg(feature = "yaml")] -macro_rules! yaml_to_u64 { - ($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 u64) - }}; -} - #[cfg(feature = "yaml")] macro_rules! yaml_to_usize { ($a:ident, $v:ident, $c:ident) => {{ @@ -119,3 +151,30 @@ macro_rules! yaml_to_usize { 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/third_party/rust/clap/src/build/mod.rs b/third_party/rust/clap/src/build/mod.rs new file mode 100644 index 000000000000..d23694dd1cab --- /dev/null +++ b/third_party/rust/clap/src/build/mod.rs @@ -0,0 +1,14 @@ +#[macro_use] +mod macros; + +pub mod app; +pub mod arg; + +mod arg_group; +mod usage_parser; + +pub use self::{ + app::{App, AppFlags, AppSettings}, + arg::{Arg, ArgFlags, ArgSettings, PossibleValue, ValueHint}, + arg_group::ArgGroup, +}; diff --git a/third_party/rust/clap/src/build/usage_parser.rs b/third_party/rust/clap/src/build/usage_parser.rs new file mode 100644 index 000000000000..1da76e24f0e0 --- /dev/null +++ b/third_party/rust/clap/src/build/usage_parser.rs @@ -0,0 +1,1276 @@ +// Internal +use crate::{ + build::{Arg, ArgSettings}, + 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_set(ArgSettings::TakesValue) { + 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::build::{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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + 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_set(ArgSettings::MultipleOccurrences)); + assert!(!a.is_set(ArgSettings::MultipleValues)); + assert!(a.is_set(ArgSettings::TakesValue)); + assert!(!a.is_set(ArgSettings::Required)); + 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_set(ArgSettings::MultipleOccurrences)); + assert!(!a.is_set(ArgSettings::MultipleValues)); + assert!(a.is_set(ArgSettings::TakesValue)); + assert!(!a.is_set(ArgSettings::Required)); + assert_eq!(a.val_names.iter().collect::>(), [&"opt"]); + } + + #[test] + fn create_option_usage2() { + let a = Arg::from_usage("(arg: A) -> Self - where - A: Into, - { - let a = arg.into(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }); - Error { - message: format!("{} The argument '{}' wasn't found", c.error("error:"), a), - kind: ErrorKind::ArgumentNotFound, - info: Some(vec![a]), - } - } - - /// Create an error with a custom description. - /// - /// This can be used in combination with `Error::exit` to exit your program - /// with a custom error message. - pub fn with_description(description: &str, kind: ErrorKind) -> Self { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }); - Error { - message: format!("{} {}", c.error("error:"), description), - kind, - info: None, - } - } -} - -impl StdError for Error { - fn description(&self) -> &str { - &*self.message - } -} - -impl Display for Error { - fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result { - writeln!(f, "{}", self.message) - } -} - -impl From for Error { - fn from(e: io::Error) -> Self { - Error::with_description(e.description(), ErrorKind::Io) - } -} - -impl From for Error { - fn from(e: std_fmt::Error) -> Self { - Error::with_description(e.description(), ErrorKind::Format) - } -} diff --git a/third_party/rust/clap/src/fmt.rs b/third_party/rust/clap/src/fmt.rs deleted file mode 100644 index f447565bd598..000000000000 --- a/third_party/rust/clap/src/fmt.rs +++ /dev/null @@ -1,192 +0,0 @@ -#[cfg(all(feature = "color", not(target_os = "windows")))] -use ansi_term::ANSIString; - -#[cfg(all(feature = "color", not(target_os = "windows")))] -use ansi_term::Colour::{Green, Red, Yellow}; - -use std::env; -use std::fmt; - -#[doc(hidden)] -#[derive(Debug, Copy, Clone, PartialEq)] -pub enum ColorWhen { - Auto, - Always, - Never, -} - -#[cfg(feature = "color")] -pub fn is_a_tty(stderr: bool) -> bool { - debugln!("is_a_tty: stderr={:?}", stderr); - let stream = if stderr { - atty::Stream::Stderr - } else { - atty::Stream::Stdout - }; - atty::is(stream) -} - -#[cfg(not(feature = "color"))] -pub fn is_a_tty(_: bool) -> bool { - debugln!("is_a_tty;"); - false -} - -pub fn is_term_dumb() -> bool { - env::var("TERM").ok() == Some(String::from("dumb")) -} - -#[doc(hidden)] -pub struct ColorizerOption { - pub use_stderr: bool, - pub when: ColorWhen, -} - -#[doc(hidden)] -pub struct Colorizer { - when: ColorWhen, -} - -macro_rules! color { - ($_self:ident, $c:ident, $m:expr) => { - match $_self.when { - ColorWhen::Auto => Format::$c($m), - ColorWhen::Always => Format::$c($m), - ColorWhen::Never => Format::None($m), - } - }; -} - -impl Colorizer { - pub fn new(option: ColorizerOption) -> Colorizer { - let is_a_tty = is_a_tty(option.use_stderr); - let is_term_dumb = is_term_dumb(); - Colorizer { - when: match option.when { - ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto, - ColorWhen::Auto => ColorWhen::Never, - when => when, - }, - } - } - - pub fn good(&self, msg: T) -> Format - where - T: fmt::Display + AsRef, - { - debugln!("Colorizer::good;"); - color!(self, Good, msg) - } - - pub fn warning(&self, msg: T) -> Format - where - T: fmt::Display + AsRef, - { - debugln!("Colorizer::warning;"); - color!(self, Warning, msg) - } - - pub fn error(&self, msg: T) -> Format - where - T: fmt::Display + AsRef, - { - debugln!("Colorizer::error;"); - color!(self, Error, msg) - } - - pub fn none(&self, msg: T) -> Format - where - T: fmt::Display + AsRef, - { - debugln!("Colorizer::none;"); - Format::None(msg) - } -} - -impl Default for Colorizer { - fn default() -> Self { - Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }) - } -} - -/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow, -/// and Good=Green -#[derive(Debug)] -#[doc(hidden)] -pub enum Format { - /// Defines the style used for errors, defaults to Red - Error(T), - /// Defines the style used for warnings, defaults to Yellow - Warning(T), - /// Defines the style used for good values, defaults to Green - Good(T), - /// Defines no formatting style - None(T), -} - -#[cfg(all(feature = "color", not(target_os = "windows")))] -impl> Format { - fn format(&self) -> ANSIString { - match *self { - Format::Error(ref e) => Red.bold().paint(e.as_ref()), - Format::Warning(ref e) => Yellow.paint(e.as_ref()), - Format::Good(ref e) => Green.paint(e.as_ref()), - Format::None(ref e) => ANSIString::from(e.as_ref()), - } - } -} - -#[cfg(any(not(feature = "color"), target_os = "windows"))] -#[cfg_attr(feature = "cargo-clippy", allow(clippy::match_same_arms))] -impl Format { - fn format(&self) -> &T { - match *self { - Format::Error(ref e) => e, - Format::Warning(ref e) => e, - Format::Good(ref e) => e, - Format::None(ref e) => e, - } - } -} - -#[cfg(all(feature = "color", not(target_os = "windows")))] -impl> fmt::Display for Format { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", &self.format()) - } -} - -#[cfg(any(not(feature = "color"), target_os = "windows"))] -impl fmt::Display for Format { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", &self.format()) - } -} - -#[cfg(all(test, feature = "color", not(target_os = "windows")))] -mod test { - use super::Format; - use ansi_term::ANSIString; - use ansi_term::Colour::{Green, Red, Yellow}; - - #[test] - fn colored_output() { - let err = Format::Error("error"); - assert_eq!( - &*format!("{}", err), - &*format!("{}", Red.bold().paint("error")) - ); - let good = Format::Good("good"); - assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good"))); - let warn = Format::Warning("warn"); - assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn"))); - let none = Format::None("none"); - assert_eq!( - &*format!("{}", none), - &*format!("{}", ANSIString::from("none")) - ); - } -} diff --git a/third_party/rust/clap/src/lib.rs b/third_party/rust/clap/src/lib.rs index 8c47b779ee1e..87dd42a66717 100644 --- a/third_party/rust/clap/src/lib.rs +++ b/third_party/rust/clap/src/lib.rs @@ -1,638 +1,107 @@ -// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/v2.33.1/CONTRIBUTORS.md). +// 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. -//! `clap` is a simple-to-use, efficient, and full-featured library for parsing command line -//! arguments and subcommands when writing console/terminal applications. -//! -//! ## About -//! -//! `clap` is used to parse *and validate* the string of command line arguments provided by the user -//! at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means -//! you focus on your *applications* functionality, and less on the parsing and validating of -//! arguments. -//! -//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning -//! automatically with no configuration. It does this by checking the list of valid possibilities you -//! supplied and adding only the ones you haven't already defined. If you are using subcommands, -//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags. -//! -//! Once `clap` parses the user provided string of arguments, it returns the matches along with any -//! applicable values. If the user made an error or typo, `clap` informs them of the mistake and -//! exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to -//! exit). Because of this, you can make reasonable assumptions in your code about the validity of -//! the arguments. -//! -//! -//! ## Quick Example -//! -//! The following examples show a quick example of some of the very basic functionality of `clap`. -//! For more advanced usage, such as requirements, conflicts, groups, multiple values and -//! occurrences see the [documentation](https://docs.rs/clap/), [examples/] directory of -//! this repository or the [video tutorials]. -//! -//! **NOTE:** All of these examples are functionally the same, but show different styles in which to -//! use `clap` -//! -//! The first example shows a method that allows more advanced configuration options (not shown in -//! this small example), or even dynamically generating arguments when desired. The downside is it's -//! more verbose. -//! -//! ```no_run -//! // (Full example with detailed comments in examples/01b_quick_example.rs) -//! // -//! // This example demonstrates clap's full 'builder pattern' style of creating arguments which is -//! // more verbose, but allows easier editing, and at times more advanced options, or the possibility -//! // to generate arguments dynamically. -//! extern crate clap; -//! use clap::{Arg, App, SubCommand}; -//! -//! fn main() { -//! let matches = App::new("My Super Program") -//! .version("1.0") -//! .author("Kevin K. ") -//! .about("Does awesome things") -//! .arg(Arg::with_name("config") -//! .short("c") -//! .long("config") -//! .value_name("FILE") -//! .help("Sets a custom config file") -//! .takes_value(true)) -//! .arg(Arg::with_name("INPUT") -//! .help("Sets the input file to use") -//! .required(true) -//! .index(1)) -//! .arg(Arg::with_name("v") -//! .short("v") -//! .multiple(true) -//! .help("Sets the level of verbosity")) -//! .subcommand(SubCommand::with_name("test") -//! .about("controls testing features") -//! .version("1.3") -//! .author("Someone E. ") -//! .arg(Arg::with_name("debug") -//! .short("d") -//! .help("print debug information verbosely"))) -//! .get_matches(); -//! -//! // Gets a value for config if supplied by user, or defaults to "default.conf" -//! let config = matches.value_of("config").unwrap_or("default.conf"); -//! println!("Value for config: {}", config); -//! -//! // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't -//! // required we could have used an 'if let' to conditionally get the value) -//! println!("Using input file: {}", matches.value_of("INPUT").unwrap()); -//! -//! // Vary the output based on how many times the user used the "verbose" flag -//! // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' -//! match matches.occurrences_of("v") { -//! 0 => println!("No verbose info"), -//! 1 => println!("Some verbose info"), -//! 2 => println!("Tons of verbose info"), -//! 3 | _ => println!("Don't be crazy"), -//! } -//! -//! // You can handle information about subcommands by requesting their matches by name -//! // (as below), requesting just the name used, or both at the same time -//! if let Some(matches) = matches.subcommand_matches("test") { -//! if matches.is_present("debug") { -//! println!("Printing debug info..."); -//! } else { -//! println!("Printing normally..."); -//! } -//! } -//! -//! // more program logic goes here... -//! } -//! ``` -//! -//! The next example shows a far less verbose method, but sacrifices some of the advanced -//! configuration options (not shown in this small example). This method also takes a *very* minor -//! runtime penalty. -//! -//! ```no_run -//! // (Full example with detailed comments in examples/01a_quick_example.rs) -//! // -//! // This example demonstrates clap's "usage strings" method of creating arguments -//! // which is less verbose -//! extern crate clap; -//! use clap::{Arg, App, SubCommand}; -//! -//! fn main() { -//! let matches = App::new("myapp") -//! .version("1.0") -//! .author("Kevin K. ") -//! .about("Does awesome things") -//! .args_from_usage( -//! "-c, --config=[FILE] 'Sets a custom config file' -//! 'Sets the input file to use' -//! -v... 'Sets the level of verbosity'") -//! .subcommand(SubCommand::with_name("test") -//! .about("controls testing features") -//! .version("1.3") -//! .author("Someone E. ") -//! .arg_from_usage("-d, --debug 'Print debug information'")) -//! .get_matches(); -//! -//! // Same as previous example... -//! } -//! ``` -//! -//! This third method shows how you can use a YAML file to build your CLI and keep your Rust source -//! tidy or support multiple localized translations by having different YAML files for each -//! localization. -//! -//! First, create the `cli.yml` file to hold your CLI options, but it could be called anything we -//! like: -//! -//! ```yaml -//! name: myapp -//! version: "1.0" -//! author: Kevin K. -//! about: Does awesome things -//! args: -//! - config: -//! short: c -//! long: config -//! value_name: FILE -//! help: Sets a custom config file -//! takes_value: true -//! - INPUT: -//! help: Sets the input file to use -//! required: true -//! index: 1 -//! - verbose: -//! short: v -//! multiple: true -//! help: Sets the level of verbosity -//! subcommands: -//! - test: -//! about: controls testing features -//! version: "1.3" -//! author: Someone E. -//! args: -//! - debug: -//! short: d -//! help: print debug information -//! ``` -//! -//! Since this feature requires additional dependencies that not everyone may want, it is *not* -//! compiled in by default and we need to enable a feature flag in Cargo.toml: -//! -//! Simply change your `clap = "~2.27.0"` to `clap = {version = "~2.27.0", features = ["yaml"]}`. -//! -//! At last we create our `main.rs` file just like we would have with the previous two examples: -//! -//! ```ignore -//! // (Full example with detailed comments in examples/17_yaml.rs) -//! // -//! // This example demonstrates clap's building from YAML style of creating arguments which is far -//! // more clean, but takes a very small performance hit compared to the other two methods. -//! #[macro_use] -//! extern crate clap; -//! use clap::App; -//! -//! fn main() { -//! // The YAML file is found relative to the current file, similar to how modules are found -//! let yaml = load_yaml!("cli.yml"); -//! let matches = App::from_yaml(yaml).get_matches(); -//! -//! // Same as previous examples... -//! } -//! ``` -//! -//! Finally there is a macro version, which is like a hybrid approach offering the speed of the -//! builder pattern (the first example), but without all the verbosity. -//! -//! ```no_run -//! #[macro_use] -//! extern crate clap; -//! -//! fn main() { -//! let matches = clap_app!(myapp => -//! (version: "1.0") -//! (author: "Kevin K. ") -//! (about: "Does awesome things") -//! (@arg CONFIG: -c --config +takes_value "Sets a custom config file") -//! (@arg INPUT: +required "Sets the input file to use") -//! (@arg debug: -d ... "Sets the level of debugging information") -//! (@subcommand test => -//! (about: "controls testing features") -//! (version: "1.3") -//! (author: "Someone E. ") -//! (@arg verbose: -v --verbose "Print test information verbosely") -//! ) -//! ).get_matches(); -//! -//! // Same as before... -//! } -//! ``` -//! -//! If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or -//! `help` subcommand, since we defined `test` as a subcommand) the following would be output -//! -//! ```text -//! $ myprog --help -//! My Super Program 1.0 -//! Kevin K. -//! Does awesome things -//! -//! USAGE: -//! MyApp [FLAGS] [OPTIONS] [SUBCOMMAND] -//! -//! FLAGS: -//! -h, --help Prints this message -//! -v Sets the level of verbosity -//! -V, --version Prints version information -//! -//! OPTIONS: -//! -c, --config Sets a custom config file -//! -//! ARGS: -//! INPUT The input file to use -//! -//! SUBCOMMANDS: -//! help Prints this message -//! test Controls testing features -//! ``` -//! -//! **NOTE:** You could also run `myapp test --help` to see similar output and options for the -//! `test` subcommand. -//! -//! ## Try it! -//! -//! ### Pre-Built Test -//! -//! To try out the pre-built example, use the following steps: -//! -//! * Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests` -//! * Compile the example `$ cargo build --release` -//! * Run the help info `$ ./target/release/claptests --help` -//! * Play with the arguments! -//! -//! ### BYOB (Build Your Own Binary) -//! -//! To test out `clap`'s default auto-generated help/version follow these steps: -//! -//! * Create a new cargo project `$ cargo new fake --bin && cd fake` -//! * Add `clap` to your `Cargo.toml` -//! -//! ```toml -//! [dependencies] -//! clap = "2" -//! ``` -//! -//! * Add the following to your `src/main.rs` -//! -//! ```no_run -//! extern crate clap; -//! use clap::App; -//! -//! fn main() { -//! App::new("fake").version("v1.0-beta").get_matches(); -//! } -//! ``` -//! -//! * Build your program `$ cargo build --release` -//! * Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake -//! --version` -//! -//! ## Usage -//! -//! For full usage, add `clap` as a dependency in your `Cargo.toml` (it is **highly** recommended to -//! use the `~major.minor.patch` style versions in your `Cargo.toml`, for more information see -//! [Compatibility Policy](#compatibility-policy)) to use from crates.io: -//! -//! ```toml -//! [dependencies] -//! clap = "~2.27.0" -//! ``` -//! -//! Or get the latest changes from the master branch at github: -//! -//! ```toml -//! [dependencies.clap] -//! git = "https://github.com/clap-rs/clap.git" -//! ``` -//! -//! Add `extern crate clap;` to your crate root. -//! -//! Define a list of valid arguments for your program (see the -//! [documentation](https://docs.rs/clap/) or [examples/] directory of this repo) -//! -//! Then run `cargo build` or `cargo update && cargo build` for your project. -//! -//! ### Optional Dependencies / Features -//! -//! #### Features enabled by default -//! -//! * `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`) -//! * `color`: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` and `atty`) -//! * `wrap_help`: Wraps the help at the actual terminal width when -//! available, instead of 120 characters. (builds dependency `textwrap` -//! with feature `term_size`) -//! -//! To disable these, add this to your `Cargo.toml`: -//! -//! ```toml -//! [dependencies.clap] -//! version = "~2.27.0" -//! default-features = false -//! ``` -//! -//! You can also selectively enable only the features you'd like to include, by adding: -//! -//! ```toml -//! [dependencies.clap] -//! version = "~2.27.0" -//! default-features = false -//! -//! # Cherry-pick the features you'd like to use -//! features = [ "suggestions", "color" ] -//! ``` -//! -//! #### Opt-in features -//! -//! * **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`) -//! * **"unstable"**: Enables unstable `clap` features that may change from release to release -//! -//! ### Dependencies Tree -//! -//! The following graphic depicts `clap`s dependency graph (generated using -//! [cargo-graph](https://github.com/kbknapp/cargo-graph)). -//! -//! * **Dashed** Line: Optional dependency -//! * **Red** Color: **NOT** included by default (must use cargo `features` to enable) -//! * **Blue** Color: Dev dependency, only used while developing. -//! -//! ![clap dependencies](https://github.com/clap-rs/clap/blob/v2.34.0/clap_dep_graph.png) -//! -//! ### More Information -//! -//! You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project. -//! -//! You can also find usage examples in the [examples/] directory of this repo. -//! -//! #### Video Tutorials -//! -//! There's also the video tutorial series [Argument Parsing with Rust v2][video tutorials]. -//! -//! These videos slowly trickle out as I finish them and currently a work in progress. -//! -//! ## How to Contribute -//! -//! Contributions are always welcome! And there is a multitude of ways in which you can help -//! depending on what you like to do, or are good at. Anything from documentation, code cleanup, -//! issue completion, new features, you name it, even filing issues is contributing and greatly -//! appreciated! -//! -//! Another really great way to help is if you find an interesting, or helpful way in which to use -//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell -//! me. I'm all about giving credit where credit is due :) -//! -//! Please read [CONTRIBUTING.md](https://github.com/clap-rs/clap/blob/v2.34.0/.github/CONTRIBUTING.md) before you start contributing. -//! -//! -//! ### Testing Code -//! -//! To test with all features both enabled and disabled, you can run theese commands: -//! -//! ```text -//! $ cargo test --no-default-features -//! $ cargo test --features "yaml unstable" -//! ``` -//! -//! Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the -//! prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands -//! automatically. -//! -//! For example, to test the code, as above simply run: -//! -//! ```text -//! $ just run-tests -//! ``` -//! -//! From here on, I will list the appropriate `cargo` command as well as the `just` command. -//! -//! Sometimes it's helpful to only run a subset of the tests, which can be done via: -//! -//! ```text -//! $ cargo test --test -//! -//! # Or -//! -//! $ just run-test -//! ``` -//! -//! ### Linting Code -//! -//! During the CI process `clap` runs against many different lints using -//! [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on -//! your own computer prior to submitting a PR you'll need a nightly compiler. -//! -//! In order to check the code for lints run either: -//! -//! ```text -//! $ rustup override add nightly -//! $ cargo build --features lints -//! $ rustup override remove -//! -//! # Or -//! -//! $ just lint -//! ``` -//! -//! ### Debugging Code -//! -//! Another helpful technique is to see the `clap` debug output while developing features. In order -//! to see the debug output while running the full test suite or individual tests, run: -//! -//! ```text -//! $ cargo test --features debug -//! -//! # Or for individual tests -//! $ cargo test --test --features debug -//! -//! # The corresponding just command for individual debugging tests is: -//! $ just debug -//! ``` -//! -//! ### Goals -//! -//! There are a few goals of `clap` that I'd like to maintain throughout contributions. If your -//! proposed changes break, or go against any of these goals we'll discuss the changes further -//! before merging (but will *not* be ignored, all contributes are welcome!). These are by no means -//! hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by -//! mistake or ignorance). -//! -//! * Remain backwards compatible when possible -//! - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before -//! removing legacy code - This does not apply for security concerns -//! * Parse arguments quickly -//! - Parsing of arguments shouldn't slow down usage of the main program - This is also true of -//! generating help and usage information (although *slightly* less stringent, as the program is about -//! to exit) -//! * Try to be cognizant of memory usage -//! - Once parsing is complete, the memory footprint of `clap` should be low since the main program -//! is the star of the show -//! * `panic!` on *developer* error, exit gracefully on *end-user* error -//! -//! ### Compatibility Policy -//! -//! Because `clap` takes `SemVer` and compatibility seriously, this is the official policy regarding -//! breaking changes and previous versions of Rust. -//! -//! `clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum -//! version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version -//! of `clap` will be bumped. -//! -//! In order to keep from being surprised by breaking changes, it is **highly** recommended to use -//! the `~major.minor.patch` style in your `Cargo.toml`: -//! -//! ```toml -//! [dependencies] clap = "~2.27.0" -//! ``` -//! -//! This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore -//! cannot break due to new features, or bumped minimum versions of Rust. -//! -//! #### Minimum Version of Rust -//! -//! `clap` will officially support current stable Rust, minus two releases, but may work with prior -//! releases as well. For example, current stable Rust at the time of this writing is 1.21.0, -//! meaning `clap` is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, `clap` -//! will be guaranteed to compile with 1.20.0 and beyond, etc. -//! -//! Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be -//! clearly annotated in the `CHANGELOG.md` -//! -//! ## License -//! -//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in -//! this repository for more information. -//! -//! [examples/]: https://github.com/clap-rs/clap/tree/v2.34.0/examples -//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U -//! [license]: https://github.com/clap-rs/clap/blob/v2.34.0/LICENSE-MIT - -#![crate_type = "lib"] -#![doc(html_root_url = "https://docs.rs/clap/2.34.0")] -#![deny( +#![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_import_braces, - unused_allocation + unused_allocation, + trivial_numeric_casts, + clippy::single_char_pattern )] -// Lints we'd like to deny but are currently failing for upstream crates -// unused_qualifications (bitflags, clippy) -// trivial_numeric_casts (bitflags) -#![cfg_attr( - not(any(feature = "cargo-clippy", feature = "nightly")), - forbid(unstable_features) -)] -//#![cfg_attr(feature = "lints", feature(plugin))] -//#![cfg_attr(feature = "lints", plugin(clippy))] -// Need to disable deny(warnings) while deprecations are active -//#![cfg_attr(feature = "cargo-clippy", deny(warnings))] -// Due to our "MSRV for 2.x will remain unchanged" policy, we can't fix these warnings -#![allow(bare_trait_objects, deprecated)] +#![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`"); -#[cfg(all(feature = "color", not(target_os = "windows")))] -extern crate ansi_term; #[cfg(feature = "color")] -extern crate atty; -#[macro_use] -extern crate bitflags; -#[cfg(feature = "suggestions")] -extern crate strsim; -#[cfg(feature = "wrap_help")] -extern crate term_size; -extern crate textwrap; -extern crate unicode_width; -#[cfg(feature = "vec_map")] -extern crate vec_map; -#[cfg(feature = "yaml")] -extern crate yaml_rust; +pub use crate::util::color::ColorChoice; +pub use crate::{ + build::{ + App, AppFlags, AppSettings, Arg, ArgFlags, ArgGroup, ArgSettings, PossibleValue, ValueHint, + }, + parse::errors::{Error, ErrorKind, Result}, + parse::{ArgMatches, Indices, OsValues, Values}, +}; + +pub use crate::derive::{ArgEnum, Args, FromArgMatches, IntoApp, Parser, Subcommand}; -pub use app::{App, AppSettings}; -pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values}; -pub use completions::Shell; -pub use errors::{Error, ErrorKind, Result}; -pub use fmt::Format; #[cfg(feature = "yaml")] +#[doc(hidden)] +#[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" +)] pub use yaml_rust::YamlLoader; +#[cfg(feature = "derive")] +#[doc(hidden)] +pub use clap_derive::{self, *}; + +/// Deprecated, replaced with [`Parser`] +#[deprecated(since = "3.0.0", note = "Replaced with `Parser`")] +pub use Parser as StructOpt; + +#[cfg(any(feature = "derive", feature = "cargo"))] +#[doc(hidden)] +pub use lazy_static; + #[macro_use] +#[allow(missing_docs)] mod macros; -mod app; -mod args; -mod completions; -mod errors; -mod fmt; -mod map; -mod osstringext; -mod strext; -mod suggestions; -mod usage_parser; + +mod derive; + +#[cfg(feature = "regex")] +pub use crate::build::arg::RegexRef; + +mod build; +mod mkeymap; +mod output; +mod parse; +mod util; const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ - report at https://github.com/clap-rs/clap/issues"; + report at https://github.com/clap-rs/clap/issues"; const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; -#[cfg(unstable)] -pub use derive::{ArgEnum, ClapApp, FromArgMatches, IntoApp}; +/// Deprecated, replaced with [`App::new`], unless you were looking for [Subcommand] +#[deprecated( + since = "3.0.0", + note = "Replaced with `App::new` unless you intended the `Subcommand` trait" +)] +#[derive(Debug, Copy, Clone)] +pub struct SubCommand {} -#[cfg(unstable)] -mod derive { - /// @TODO @release @docs - pub trait ClapApp: IntoApp + FromArgMatches + Sized { - /// @TODO @release @docs - fn parse() -> Self { - Self::from_argmatches(Self::into_app().get_matches()) - } - - /// @TODO @release @docs - fn parse_from(argv: I) -> Self - where - I: IntoIterator, - T: Into + Clone, - { - Self::from_argmatches(Self::into_app().get_matches_from(argv)) - } - - /// @TODO @release @docs - fn try_parse() -> Result { - Self::try_from_argmatches(Self::into_app().get_matches_safe()?) - } - - /// @TODO @release @docs - fn try_parse_from(argv: I) -> Result - where - I: IntoIterator, - T: Into + Clone, - { - Self::try_from_argmatches(Self::into_app().get_matches_from_safe(argv)?) - } +#[allow(deprecated)] +impl SubCommand { + /// Deprecated, replaced with [`App::new`]. + /// Did you mean Subcommand (lower-case c)? + #[deprecated(since = "3.0.0", note = "Replaced with `App::new`")] + pub fn with_name<'help>(name: &str) -> App<'help> { + App::new(name) } - /// @TODO @release @docs - pub trait IntoApp { - /// @TODO @release @docs - fn into_app<'a, 'b>() -> clap::App<'a, 'b>; + /// 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")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App { + #![allow(deprecated)] + App::from_yaml(yaml) } - - /// @TODO @release @docs - pub trait FromArgMatches: Sized { - /// @TODO @release @docs - fn from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Self; - - /// @TODO @release @docs - fn try_from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Result; - } - - /// @TODO @release @docs - pub trait ArgEnum {} } diff --git a/third_party/rust/clap/src/macros.rs b/third_party/rust/clap/src/macros.rs index 01cbca8095da..a706c28cb026 100644 --- a/third_party/rust/clap/src/macros.rs +++ b/third_party/rust/clap/src/macros.rs @@ -1,323 +1,78 @@ -/// A convenience macro for loading the YAML file at compile time (relative to the current file, -/// like modules work). That YAML object can then be passed to this function. -/// -/// # Panics -/// -/// The YAML file must be properly formatted or this function will panic!(). A good way to -/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes -/// without error, you needn't worry because the YAML is properly formatted. -/// -/// # Examples -/// -/// The following example shows how to load a properly formatted YAML file to build an instance -/// of an `App` struct. -/// -/// ```ignore -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let yml = load_yaml!("app.yml"); -/// let app = App::from_yaml(yml); -/// -/// // continued logic goes here, such as `app.get_matches()` etc. -/// # } -/// ``` +/// 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")] +#[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" +)] #[macro_export] macro_rules! load_yaml { - ($yml:expr) => { - &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0] + ($yaml:expr) => { + &$crate::YamlLoader::load_from_str(include_str!($yaml)).expect("failed to load YAML file") + [0] }; } -/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an -/// argument value. This macro returns a `Result` which allows you as the developer to -/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures -/// and those where the argument wasn't present (such as a non-required argument). You can use -/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") -/// .get_matches(); -/// -/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit()); -/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit()); -/// -/// println!("{} + 2: {}", len, len + 2); -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of -/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html +/// Deprecated, replaced with [`ArgMatches::value_of_t`][crate::ArgMatches::value_of_t] #[macro_export] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::value_of_t`")] macro_rules! value_t { ($m:ident, $v:expr, $t:ty) => { - value_t!($m.value_of($v), $t) + $crate::value_t!($m.value_of($v), $t) }; ($m:ident.value_of($v:expr), $t:ty) => { - if let Some(v) = $m.value_of($v) { - match v.parse::<$t>() { - Ok(val) => Ok(val), - Err(_) => Err(::clap::Error::value_validation_auto(format!( - "The argument '{}' isn't a valid value", - v - ))), - } - } else { - Err(::clap::Error::argument_not_found_auto($v)) - } + $m.value_of_t::<$t>($v) }; } -/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or -/// exiting upon error, instead of returning a [`Result`] type. -/// -/// **NOTE:** This macro is for backwards compatibility sake. Prefer -/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") -/// .get_matches(); -/// -/// let len = value_t_or_exit!(matches.value_of("length"), u32); -/// let also_len = value_t_or_exit!(matches, "length", u32); -/// -/// println!("{} + 2: {}", len, len + 2); -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html -/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html +/// Deprecated, replaced with [`ArgMatches::value_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] #[macro_export] +#[deprecated( + since = "3.0.0", + note = "Replaced with `ArgMatches::value_of_t_or_exit`" +)] 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) => { - if let Some(v) = $m.value_of($v) { - match v.parse::<$t>() { - Ok(val) => val, - Err(_) => ::clap::Error::value_validation_auto(format!( - "The argument '{}' isn't a valid value", - v - )) - .exit(), - } - } else { - ::clap::Error::argument_not_found_auto($v).exit() - } + $m.value_of_t_or_exit::<$t>($v) }; } -/// Convenience macro getting a typed value [`Vec`] where `T` implements [`std::str::FromStr`] -/// This macro returns a [`clap::Result>`] which allows you as the developer to decide -/// what you'd like to do on a failed parse. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") -/// .get_matches(); -/// -/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit()); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// -/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit()); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html -/// [`clap::Result>`]: ./type.Result.html +/// Deprecated, replaced with [`ArgMatches::values_of_t`][crate::ArgMatches::value_of_t] #[macro_export] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::values_of_t`")] 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) => { - if let Some(vals) = $m.values_of($v) { - let mut tmp = vec![]; - let mut err = None; - for pv in vals { - match pv.parse::<$t>() { - Ok(rv) => tmp.push(rv), - Err(..) => { - err = Some(::clap::Error::value_validation_auto(format!( - "The argument '{}' isn't a valid value", - pv - ))); - break; - } - } - } - match err { - Some(e) => Err(e), - None => Ok(tmp), - } - } else { - Err(::clap::Error::argument_not_found_auto($v)) - } + $m.values_of_t::<$t>($v) }; } -/// Convenience macro getting a typed value [`Vec`] where `T` implements [`std::str::FromStr`] -/// or exiting upon error. -/// -/// **NOTE:** This macro is for backwards compatibility sake. Prefer -/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") -/// .get_matches(); -/// -/// let vals = values_t_or_exit!(matches.values_of("seq"), u32); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// -/// // type for example only -/// let vals: Vec = values_t_or_exit!(matches, "seq", u32); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// # } -/// ``` -/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html +/// Deprecated, replaced with [`ArgMatches::values_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] #[macro_export] +#[deprecated( + since = "3.0.0", + note = "Replaced with `ArgMatches::values_of_t_or_exit`" +)] 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) => { - if let Some(vals) = $m.values_of($v) { - vals.map(|v| { - v.parse::<$t>().unwrap_or_else(|_| { - ::clap::Error::value_validation_auto(format!( - "One or more arguments aren't valid values" - )) - .exit() - }) - }) - .collect::>() - } else { - ::clap::Error::argument_not_found_auto($v).exit() - } + $m.values_of_t_or_exit::<$t>($v) }; } -// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag -// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07 -// License: MIT -// Copyright ⓒ 2015 grabbag contributors. -// Licensed under the MIT license (see LICENSE or ) or the Apache License, Version 2.0 (see LICENSE of -// ), at your option. All -// files in the project carrying such notice may not be copied, modified, -// or distributed except according to those terms. -// -/// Counts the number of comma-delimited expressions passed to it. The result is a compile-time -/// evaluable expression, suitable for use as a static array size, or the value of a `const`. -/// -/// # Examples -/// -/// ``` -/// # #[macro_use] extern crate clap; -/// # fn main() { -/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string()); -/// assert_eq!(COUNT, 3); -/// # } -/// ``` -#[macro_export] -macro_rules! _clap_count_exprs { - () => { 0 }; - ($e:expr) => { 1 }; - ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; -} - -/// Convenience macro to generate more complete enums with variants to be used as a type when -/// parsing arguments. This enum also provides a `variants()` function which can be used to -/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and -/// [`Display`] automatically. -/// -/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to -/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums -/// -/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`] -/// -/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits -/// -/// # Examples -/// -/// ```rust -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::{App, Arg}; -/// arg_enum!{ -/// #[derive(PartialEq, Debug)] -/// pub enum Foo { -/// Bar, -/// Baz, -/// Qux -/// } -/// } -/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc -/// // and implements std::str::FromStr to use with the value_t! macros -/// fn main() { -/// let m = App::new("app") -/// .arg(Arg::from_usage(" 'the foo'") -/// .possible_values(&Foo::variants()) -/// .case_insensitive(true)) -/// .get_matches_from(vec![ -/// "app", "baz" -/// ]); -/// let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit()); -/// -/// assert_eq!(f, Foo::Baz); -/// } -/// ``` -/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html -/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html -/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive +/// Deprecated, replaced with [`ArgEnum`][crate::ArgEnum] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`")] #[macro_export] macro_rules! arg_enum { (@as_item $($i:item)*) => ($($i)*); (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { - arg_enum!(@as_item + $crate::arg_enum!(@as_item $($tts)* impl ::std::str::FromStr for $e { @@ -356,7 +111,7 @@ macro_rules! arg_enum { }); }; ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls ($(#[$($m),+])+ pub enum $e { $($v$(=$val)*),+ @@ -364,7 +119,7 @@ macro_rules! arg_enum { ); }; ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls ($(#[$($m),+])+ pub enum $e { $($v$(=$val)*),+ @@ -372,7 +127,7 @@ macro_rules! arg_enum { ); }; ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls ($(#[$($m),+])+ enum $e { $($v$(=$val)*),+ @@ -380,7 +135,7 @@ macro_rules! arg_enum { ); }; ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls ($(#[$($m),+])+ enum $e { $($v$(=$val)*),+ @@ -388,28 +143,28 @@ macro_rules! arg_enum { ); }; (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls (pub enum $e { $($v$(=$val)*),+ }) -> ($e, $($v),+) ); }; (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls (pub enum $e { $($v$(=$val)*),+ }) -> ($e, $($v),+) ); }; (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls (enum $e { $($v$(=$val)*),+ }) -> ($e, $($v),+) ); }; (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls + $crate::arg_enum!(@impls (enum $e { $($v$(=$val)*),+ }) -> ($e, $($v),+) @@ -432,7 +187,7 @@ macro_rules! arg_enum { /// .get_matches(); /// # } /// ``` -#[cfg(not(feature = "no_cargo"))] +#[cfg(feature = "cargo")] #[macro_export] macro_rules! crate_version { () => { @@ -461,43 +216,16 @@ macro_rules! crate_version { /// .get_matches(); /// # } /// ``` -#[cfg(not(feature = "no_cargo"))] +#[cfg(feature = "cargo")] #[macro_export] macro_rules! crate_authors { ($sep:expr) => {{ - use std::ops::Deref; - #[allow(deprecated)] - use std::sync::{Once, ONCE_INIT}; - - #[allow(missing_copy_implementations)] - #[allow(dead_code)] - struct CargoAuthors { - __private_field: (), - }; - - impl Deref for CargoAuthors { - type Target = str; - - #[allow(unsafe_code)] - fn deref(&self) -> &'static str { - #[allow(deprecated)] - static ONCE: Once = ONCE_INIT; - static mut VALUE: *const String = 0 as *const String; - - unsafe { - ONCE.call_once(|| { - let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep); - VALUE = Box::into_raw(Box::new(s)); - }); - - &(*VALUE)[..] - } - } + clap::lazy_static::lazy_static! { + static ref CACHED: String = env!("CARGO_PKG_AUTHORS").replace(':', $sep); } - &*CargoAuthors { - __private_field: (), - } + let s: &'static str = &*CACHED; + s }}; () => { env!("CARGO_PKG_AUTHORS") @@ -518,7 +246,7 @@ macro_rules! crate_authors { /// .get_matches(); /// # } /// ``` -#[cfg(not(feature = "no_cargo"))] +#[cfg(feature = "cargo")] #[macro_export] macro_rules! crate_description { () => { @@ -539,7 +267,7 @@ macro_rules! crate_description { /// .get_matches(); /// # } /// ``` -#[cfg(not(feature = "no_cargo"))] +#[cfg(feature = "cargo")] #[macro_export] macro_rules! crate_name { () => { @@ -551,7 +279,7 @@ macro_rules! crate_name { /// /// Equivalent to using the `crate_*!` macros with their respective fields. /// -/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro, +/// Provided separator is for the [`crate_authors!`] macro, /// refer to the documentation therefor. /// /// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, @@ -570,156 +298,398 @@ macro_rules! crate_name { /// let m = app_from_crate!().get_matches(); /// # } /// ``` -#[cfg(not(feature = "no_cargo"))] +#[cfg(feature = "cargo")] #[macro_export] macro_rules! app_from_crate { - () => { - $crate::App::new(crate_name!()) - .version(crate_version!()) - .author(crate_authors!()) - .about(crate_description!()) + () => {{ + let mut app = $crate::App::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!(", "); + if !author.is_empty() { + app = app.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + app = app.about(about) + } + + app + }}; + ($sep:expr) => {{ + let mut app = $crate::App::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!($sep); + if !author.is_empty() { + app = app.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + app = app.about(about) + } + + app + }}; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! arg_impl { + ( @string $val:ident ) => { + stringify!($val) }; - ($sep:expr) => { - $crate::App::new(crate_name!()) - .version(crate_version!()) - .author(crate_authors!($sep)) - .about(crate_description!()) + ( @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"); + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "Flags should precede `...`"); + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_name().is_empty() { + arg = arg.name(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"); + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "Flags should precede `...`"); + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_name().is_empty() { + arg = arg.name(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"); + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "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"); + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "Flags should precede `...`"); + + $arg.short($crate::arg_impl! { @char $short }) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + <$value_name:ident> + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "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_name().is_empty() { + arg = arg.name(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + [$value_name:ident] + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_set($crate::ArgSettings::MultipleOccurrences), "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_name().is_empty() { + arg = arg.name(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + ... + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + $arg.multiple_occurrences(true) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + $help:literal + ) => { + $arg.help($help) + }; + ( + @arg + ($arg:expr) + ) => { + $arg }; } -/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input -/// but without the associated parsing runtime cost. +/// Create an [`Arg`] from a usage string. /// -/// `clap_app!` also supports several shorthand syntaxes. +/// 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 single quotes `''` and may contain any +/// characters. /// /// # Examples /// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let matches = clap_app!(myapp => -/// (version: "1.0") -/// (author: "Kevin K. ") -/// (about: "Does awesome things") -/// (@arg CONFIG: -c --config +takes_value "Sets a custom config file") -/// (@arg INPUT: +required "Sets the input file to use") -/// (@arg debug: -d ... "Sets the level of debugging information") -/// (@group difficulty => -/// (@arg hard: -h --hard "Sets hard mode") -/// (@arg normal: -n --normal "Sets normal mode") -/// (@arg easy: -e --easy "Sets easy mode") -/// ) -/// (@subcommand test => -/// (about: "controls testing features") -/// (version: "1.3") -/// (author: "Someone E. ") -/// (@arg verbose: -v --verbose "Print test information verbosely") -/// ) -/// ) -/// .get_matches(); -/// # } +/// ```rust +/// # use clap::{App, Arg, arg}; +/// App::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") +/// ]) +/// # ; /// ``` -/// # Shorthand Syntax for Args -/// -/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`] -/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`] -/// * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you -/// must use `--("config-file")` due to limitations of the Rust macro system. -/// * Three dots (`...`) sets [`Arg::multiple(true)`] -/// * Angled brackets after either a short or long will set [`Arg::value_name`] and -/// `Arg::required(true)` such as `--config ` = `Arg::value_name("FILE")` and -/// `Arg::required(true)` -/// * Square brackets after either a short or long will set [`Arg::value_name`] and -/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and -/// `Arg::required(false)` -/// * There are short hand syntaxes for Arg methods that accept booleans -/// * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)` -/// * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)` -/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`] -/// * An asterisk (`*`) will set `Arg::required(true)` -/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)` -/// * An Arg method that accepts a string followed by square brackets will set that method such as -/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around -/// `FOO` in the macro) -/// * An Arg method that takes a string and can be set multiple times (such as -/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces -/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set -/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")` -/// (note the lack of quotes around the values in the macro) -/// -/// # Shorthand Syntax for Groups -/// -/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans -/// * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)` -/// * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)` -/// -/// [`Arg::short`]: ./struct.Arg.html#method.short -/// [`Arg::long`]: ./struct.Arg.html#method.long -/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple -/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name -/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values -/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values -/// [`Arg::validator`]: ./struct.Arg.html#method.validator -/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with +/// [`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_name().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) +#[deprecated( + since = "3.0.0", + note = "Replaced with `clap::Parser` for a declarative API (Issue clap-rs/clap#2835)" +)] #[macro_export] macro_rules! clap_app { (@app ($builder:expr)) => { $builder }; (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app + $crate::clap_app!{ @app ($builder.arg( - clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* })) + $crate::clap_app!{ @arg ($crate::Arg::new($name)) (-) $($tail)* })) $($tt)* } }; (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app + $crate::clap_app!{ @app ($builder.arg( - clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* })) + $crate::clap_app!{ @arg ($crate::Arg::new(stringify!($name))) (-) $($tail)* })) $($tt)* } }; (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { - clap_app!{ @app + $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)*) => { - clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } + $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } }; (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* }) + $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)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* }) + $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)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* }) + $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)*) => { - clap_app!{ @app + $crate::clap_app!{ @app ($builder.subcommand( - clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } + $crate::clap_app!{ @app ($crate::App::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)*) => { -// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } - clap_app!{ @app +// $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } + $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } @@ -729,11 +699,11 @@ macro_rules! clap_app { (@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)*) => { - clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($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)*) => { - clap_app!{ @group - (clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, + $crate::clap_app!{ @group + ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, $group.arg(stringify!($name))) $($tt)* } @@ -743,388 +713,196 @@ macro_rules! clap_app { (@arg ($arg:expr) $modes:tt) => { $arg }; // Shorthand tokens influenced by the usage_string (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { - clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } }; (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } }; (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* } }; (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } }; (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } }; (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } }; (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } }; (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes +multiple $($tail)* } + $crate::clap_app!{ @arg ($arg) $modes +multiple +takes_value $($tail)* } }; // Shorthand magic (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } + $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } }; (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes +required $($tail)* } + $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* } }; // !foo -> .foo(false) (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } }; // +foo -> .foo(true) (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } }; // Validator (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { - clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } }; (@as_expr $expr:expr) => { $expr }; // Help - (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) }; + (@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)*) => { - clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } + $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)*) => { - clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + $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)*) => { - clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } }; // Build a subcommand outside of an app. (@subcommand $name:ident => $($tail:tt)*) => { - clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } + $crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)* } }; // Start the magic (($name:expr) => $($tail:tt)*) => {{ - clap_app!{ @app ($crate::App::new($name)) $($tail)*} + $crate::clap_app!{ @app ($crate::App::new($name)) $($tail)*} }}; ($name:ident => $($tail:tt)*) => {{ - clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*} + $crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*} }}; } macro_rules! impl_settings { - ($n:ident, $($v:ident => $c:path),+) => { - pub fn set(&mut self, s: $n) { - match s { - $($n::$v => self.0.insert($c)),+ + ($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), + )* + } } } - pub fn unset(&mut self, s: $n) { - match s { - $($n::$v => self.0.remove($c)),+ + impl BitOr for $flags { + type Output = Self; + + fn bitor(mut self, rhs: Self) -> Self::Output { + self.0.insert(rhs.0); + self } } - pub fn is_set(&self, s: $n) -> bool { - match s { - $($n::$v => self.0.contains($c)),+ + 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( - (@nopanic $($arg:tt)*) => ({ - use std::io::{Write, stderr}; - let _ = writeln!(&mut stderr().lock(), $($arg)*); - }); +macro_rules! wlnerr { ($($arg:tt)*) => ({ use std::io::{Write, stderr}; writeln!(&mut stderr(), $($arg)*).ok(); }) -); +} #[cfg(feature = "debug")] -#[cfg_attr(feature = "debug", macro_use)] -#[cfg_attr(feature = "debug", allow(unused_macros))] -mod debug_macros { - macro_rules! debugln { - ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt))); - ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*)); - } - macro_rules! sdebugln { - ($fmt:expr) => (println!($fmt)); - ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*)); - } - macro_rules! debug { - ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt))); - ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*)); - } - macro_rules! sdebug { - ($fmt:expr) => (print!($fmt)); - ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*)); - } +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(true, $crate::ColorChoice::Auto); + color.hint(prefix); + color.hint(body); + color.none("\n"); + let _ = color.print(); + }) } #[cfg(not(feature = "debug"))] -#[cfg_attr(not(feature = "debug"), macro_use)] -mod debug_macros { - macro_rules! debugln { - ($fmt:expr) => {}; - ($fmt:expr, $($arg:tt)*) => {}; - } - macro_rules! sdebugln { - ($fmt:expr) => {}; - ($fmt:expr, $($arg:tt)*) => {}; - } - macro_rules! debug { - ($fmt:expr) => {}; - ($fmt:expr, $($arg:tt)*) => {}; - } -} - -// Helper/deduplication macro for printing the correct number of spaces in help messages -// used in: -// src/args/arg_builder/*.rs -// src/app/mod.rs -macro_rules! write_nspaces { - ($dst:expr, $num:expr) => {{ - debugln!("write_spaces!: num={}", $num); - for _ in 0..$num { - $dst.write_all(b" ")?; - } - }}; -} - -// convenience macro for remove an item from a vec -//macro_rules! vec_remove_all { -// ($vec:expr, $to_rem:expr) => { -// debugln!("vec_remove_all! to_rem={:?}", $to_rem); -// for i in (0 .. $vec.len()).rev() { -// let should_remove = $to_rem.any(|name| name == &$vec[i]); -// if should_remove { $vec.swap_remove(i); } -// } -// }; -//} -macro_rules! find_from { - ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ - let mut ret = None; - for k in $matcher.arg_names() { - if let Some(f) = find_by_name!($_self, k, flags, iter) { - if let Some(ref v) = f.$from() { - if v.contains($arg_name) { - ret = Some(f.to_string()); - } - } - } - if let Some(o) = find_by_name!($_self, k, opts, iter) { - if let Some(ref v) = o.$from() { - if v.contains(&$arg_name) { - ret = Some(o.to_string()); - } - } - } - if let Some(pos) = find_by_name!($_self, k, positionals, values) { - if let Some(ref v) = pos.$from() { - if v.contains($arg_name) { - ret = Some(pos.b.name.to_owned()); - } - } - } - } - ret - }}; -} - -//macro_rules! find_name_from { -// ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ -// let mut ret = None; -// for k in $matcher.arg_names() { -// if let Some(f) = find_by_name!($_self, k, flags, iter) { -// if let Some(ref v) = f.$from() { -// if v.contains($arg_name) { -// ret = Some(f.b.name); -// } -// } -// } -// if let Some(o) = find_by_name!($_self, k, opts, iter) { -// if let Some(ref v) = o.$from() { -// if v.contains(&$arg_name) { -// ret = Some(o.b.name); -// } -// } -// } -// if let Some(pos) = find_by_name!($_self, k, positionals, values) { -// if let Some(ref v) = pos.$from() { -// if v.contains($arg_name) { -// ret = Some(pos.b.name); -// } -// } -// } -// } -// ret -// }}; -//} - -macro_rules! find_any_by_name { - ($p:expr, $name:expr) => {{ - fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { - x - } - find_by_name!($p, $name, flags, iter) - .map(as_trait_obj) - .or(find_by_name!($p, $name, opts, iter) - .map(as_trait_obj) - .or(find_by_name!($p, $name, positionals, values).map(as_trait_obj))) - }}; -} -// Finds an arg by name -macro_rules! find_by_name { - ($p:expr, $name:expr, $what:ident, $how:ident) => { - $p.$what.$how().find(|o| o.b.name == $name) - }; -} - -// Finds an option including if it's aliased -macro_rules! find_opt_by_long { - (@os $_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, opts) - }}; - ($_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, opts) - }}; -} - -macro_rules! find_flag_by_long { - (@os $_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, flags) - }}; - ($_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, flags) - }}; -} - -macro_rules! _find_by_long { - ($_self:ident, $long:expr, $what:ident) => {{ - $_self - .$what - .iter() - .filter(|a| a.s.long.is_some()) - .find(|a| { - a.s.long.unwrap() == $long - || (a.s.aliases.is_some() - && a.s - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(alias, _)| alias == $long)) - }) - }}; -} - -// Finds an option -macro_rules! find_opt_by_short { - ($_self:ident, $short:expr) => {{ - _find_by_short!($_self, $short, opts) - }}; -} - -macro_rules! find_flag_by_short { - ($_self:ident, $short:expr) => {{ - _find_by_short!($_self, $short, flags) - }}; -} - -macro_rules! _find_by_short { - ($_self:ident, $short:expr, $what:ident) => {{ - $_self - .$what - .iter() - .filter(|a| a.s.short.is_some()) - .find(|a| a.s.short.unwrap() == $short) - }}; -} - -macro_rules! find_subcmd { - ($_self:expr, $sc:expr) => {{ - $_self.subcommands.iter().find(|s| { - &*s.p.meta.name == $sc - || (s.p.meta.aliases.is_some() - && s.p - .meta - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(n, _)| n == $sc)) - }) - }}; -} - -macro_rules! shorts { - ($_self:ident) => {{ - _shorts_longs!($_self, short) - }}; -} - -macro_rules! longs { - ($_self:ident) => {{ - _shorts_longs!($_self, long) - }}; -} - -macro_rules! _shorts_longs { - ($_self:ident, $what:ident) => {{ - $_self - .flags - .iter() - .filter(|f| f.s.$what.is_some()) - .map(|f| f.s.$what.as_ref().unwrap()) - .chain( - $_self - .opts - .iter() - .filter(|o| o.s.$what.is_some()) - .map(|o| o.s.$what.as_ref().unwrap()), - ) - }}; -} - -macro_rules! arg_names { - ($_self:ident) => {{ - _names!(@args $_self) - }}; -} - -macro_rules! sc_names { - ($_self:ident) => {{ - _names!(@sc $_self) - }}; -} - -macro_rules! _names { - (@args $_self:ident) => {{ - $_self.flags.iter().map(|f| &*f.b.name).chain( - $_self - .opts - .iter() - .map(|o| &*o.b.name) - .chain($_self.positionals.values().map(|p| &*p.b.name)), - ) - }}; - (@sc $_self:ident) => {{ - $_self.subcommands.iter().map(|s| &*s.p.meta.name).chain( - $_self - .subcommands - .iter() - .filter(|s| s.p.meta.aliases.is_some()) - .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)), - ) - }}; +macro_rules! debug { + ($($arg:tt)*) => {}; } diff --git a/third_party/rust/clap/src/map.rs b/third_party/rust/clap/src/map.rs deleted file mode 100644 index 13497834d42a..000000000000 --- a/third_party/rust/clap/src/map.rs +++ /dev/null @@ -1,88 +0,0 @@ -#[cfg(feature = "vec_map")] -pub use vec_map::{Values, VecMap}; - -#[cfg(not(feature = "vec_map"))] -pub use self::vec_map::{Values, VecMap}; - -#[cfg(not(feature = "vec_map"))] -mod vec_map { - use std::collections::btree_map; - use std::collections::BTreeMap; - use std::fmt::{self, Debug, Formatter}; - - #[derive(Clone, Default, Debug)] - pub struct VecMap { - inner: BTreeMap, - } - - impl VecMap { - pub fn new() -> Self { - VecMap { - inner: Default::default(), - } - } - - pub fn len(&self) -> usize { - self.inner.len() - } - - pub fn is_empty(&self) -> bool { - self.inner.is_empty() - } - - pub fn insert(&mut self, key: usize, value: V) -> Option { - self.inner.insert(key, value) - } - - pub fn values(&self) -> Values { - self.inner.values() - } - - pub fn iter(&self) -> Iter { - Iter { - inner: self.inner.iter(), - } - } - - pub fn contains_key(&self, key: usize) -> bool { - self.inner.contains_key(&key) - } - - pub fn entry(&mut self, key: usize) -> Entry { - self.inner.entry(key) - } - - pub fn get(&self, key: usize) -> Option<&V> { - self.inner.get(&key) - } - } - - pub type Values<'a, V> = btree_map::Values<'a, usize, V>; - - pub type Entry<'a, V> = btree_map::Entry<'a, usize, V>; - - #[derive(Clone)] - pub struct Iter<'a, V: 'a> { - inner: btree_map::Iter<'a, usize, V>, - } - - impl<'a, V: 'a + Debug> Debug for Iter<'a, V> { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - f.debug_list().entries(self.inner.clone()).finish() - } - } - - impl<'a, V: 'a> Iterator for Iter<'a, V> { - type Item = (usize, &'a V); - - fn next(&mut self) -> Option { - self.inner.next().map(|(k, v)| (*k, v)) - } - } - - impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> { - fn next_back(&mut self) -> Option { - self.inner.next_back().map(|(k, v)| (*k, v)) - } - } -} diff --git a/third_party/rust/clap/src/mkeymap.rs b/third_party/rust/clap/src/mkeymap.rs new file mode 100644 index 000000000000..54d29e814c75 --- /dev/null +++ b/third_party/rust/clap/src/mkeymap.rs @@ -0,0 +1,180 @@ +use crate::{build::Arg, util::Id, INTERNAL_ERROR_MSG}; + +use std::{ffi::OsStr, ffi::OsString, iter::Iterator, ops::Index}; + +#[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: &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/third_party/rust/clap/src/osstringext.rs b/third_party/rust/clap/src/osstringext.rs deleted file mode 100644 index ef765c8d1f6f..000000000000 --- a/third_party/rust/clap/src/osstringext.rs +++ /dev/null @@ -1,203 +0,0 @@ -use std::ffi::OsStr; -#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] -use std::os::unix::ffi::OsStrExt; -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use crate::INVALID_UTF8; - -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -pub trait OsStrExt3 { - fn from_bytes(b: &[u8]) -> &Self; - fn as_bytes(&self) -> &[u8]; -} - -#[doc(hidden)] -pub trait OsStrExt2 { - fn starts_with(&self, s: &[u8]) -> bool; - fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr); - fn split_at(&self, i: usize) -> (&OsStr, &OsStr); - fn trim_left_matches(&self, b: u8) -> &OsStr; - fn contains_byte(&self, b: u8) -> bool; - fn split(&self, b: u8) -> OsSplit; -} - -// A starts-with implementation that does not panic when the OsStr contains -// invalid Unicode. -// -// A Windows OsStr is usually UTF-16. If `prefix` is valid UTF-8, we can -// re-encode it as UTF-16, and ask whether `osstr` starts with the same series -// of u16 code units. If `prefix` is not valid UTF-8, then this comparison -// isn't meaningful, and we just return false. -#[cfg(target_os = "windows")] -fn windows_osstr_starts_with(osstr: &OsStr, prefix: &[u8]) -> bool { - use std::os::windows::ffi::OsStrExt; - let prefix_str = if let Ok(s) = std::str::from_utf8(prefix) { - s - } else { - return false; - }; - let mut osstr_units = osstr.encode_wide(); - let mut prefix_units = prefix_str.encode_utf16(); - loop { - match (osstr_units.next(), prefix_units.next()) { - // These code units match. Keep looping. - (Some(o), Some(p)) if o == p => continue, - // We've reached the end of the prefix. It's a match. - (_, None) => return true, - // Otherwise, it's not a match. - _ => return false, - } - } -} - -#[test] -#[cfg(target_os = "windows")] -fn test_windows_osstr_starts_with() { - use std::ffi::OsString; - use std::os::windows::ffi::OsStringExt; - - fn from_ascii(ascii: &[u8]) -> OsString { - let u16_vec: Vec = ascii.iter().map(|&c| c as u16).collect(); - OsString::from_wide(&u16_vec) - } - - // Test all the basic cases. - assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abc")); - assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abcdef")); - assert!(!windows_osstr_starts_with(&from_ascii(b"abcdef"), b"def")); - assert!(!windows_osstr_starts_with(&from_ascii(b"abc"), b"abcd")); - - // Test the case where the candidate prefix is not valid UTF-8. Note that a - // standalone \xff byte is valid ASCII but not valid UTF-8. Thus although - // these strings look identical, they do not match. - assert!(!windows_osstr_starts_with(&from_ascii(b"\xff"), b"\xff")); - - // Test the case where the OsString is not valid UTF-16. It should still be - // possible to match the valid characters at the front. - // - // UTF-16 surrogate characters are only valid in pairs. Including one on - // the end by itself makes this invalid UTF-16. - let surrogate_char: u16 = 0xDC00; - let invalid_unicode = - OsString::from_wide(&['a' as u16, 'b' as u16, 'c' as u16, surrogate_char]); - assert!( - invalid_unicode.to_str().is_none(), - "This string is invalid Unicode, and conversion to &str should fail.", - ); - assert!(windows_osstr_starts_with(&invalid_unicode, b"abc")); - assert!(!windows_osstr_starts_with(&invalid_unicode, b"abcd")); -} - -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -impl OsStrExt3 for OsStr { - fn from_bytes(b: &[u8]) -> &Self { - use std::mem; - unsafe { mem::transmute(b) } - } - fn as_bytes(&self) -> &[u8] { - self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8) - } -} - -impl OsStrExt2 for OsStr { - fn starts_with(&self, s: &[u8]) -> bool { - #[cfg(target_os = "windows")] - { - // On Windows, the as_bytes() method will panic if the OsStr - // contains invalid Unicode. To avoid this, we use a - // Windows-specific starts-with function that doesn't rely on - // as_bytes(). This is necessary for Windows command line - // applications to handle non-Unicode arguments successfully. This - // allows common cases like `clap.exe [invalid]` to succeed, though - // cases that require string splitting will still fail, like - // `clap.exe --arg=[invalid]`. Note that this entire module is - // replaced in Clap 3.x, so this workaround is specific to the 2.x - // branch. - windows_osstr_starts_with(self, s) - } - #[cfg(not(target_os = "windows"))] - { - self.as_bytes().starts_with(s) - } - } - - fn contains_byte(&self, byte: u8) -> bool { - for b in self.as_bytes() { - if b == &byte { - return true; - } - } - false - } - - fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) { - for (i, b) in self.as_bytes().iter().enumerate() { - if b == &byte { - return ( - OsStr::from_bytes(&self.as_bytes()[..i]), - OsStr::from_bytes(&self.as_bytes()[i + 1..]), - ); - } - } - ( - &*self, - OsStr::from_bytes(&self.as_bytes()[self.len()..self.len()]), - ) - } - - fn trim_left_matches(&self, byte: u8) -> &OsStr { - let mut found = false; - for (i, b) in self.as_bytes().iter().enumerate() { - if b != &byte { - return OsStr::from_bytes(&self.as_bytes()[i..]); - } else { - found = true; - } - } - if found { - return OsStr::from_bytes(&self.as_bytes()[self.len()..]); - } - &*self - } - - fn split_at(&self, i: usize) -> (&OsStr, &OsStr) { - ( - OsStr::from_bytes(&self.as_bytes()[..i]), - OsStr::from_bytes(&self.as_bytes()[i..]), - ) - } - - fn split(&self, b: u8) -> OsSplit { - OsSplit { - sep: b, - val: self.as_bytes(), - pos: 0, - } - } -} - -#[doc(hidden)] -#[derive(Clone, Debug)] -pub struct OsSplit<'a> { - sep: u8, - val: &'a [u8], - pos: usize, -} - -impl<'a> Iterator for OsSplit<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { - debugln!("OsSplit::next: self={:?}", self); - if self.pos == self.val.len() { - return None; - } - let start = self.pos; - for b in &self.val[start..] { - self.pos += 1; - if *b == self.sep { - return Some(OsStr::from_bytes(&self.val[start..self.pos - 1])); - } - } - Some(OsStr::from_bytes(&self.val[start..])) - } -} diff --git a/third_party/rust/clap/src/output/fmt.rs b/third_party/rust/clap/src/output/fmt.rs new file mode 100644 index 000000000000..a416935bb8a9 --- /dev/null +++ b/third_party/rust/clap/src/output/fmt.rs @@ -0,0 +1,151 @@ +use crate::util::color::ColorChoice; + +use std::{ + fmt::{self, Display, Formatter}, + io::{self, Write}, +}; + +#[derive(Clone, Debug)] +pub(crate) struct Colorizer { + use_stderr: bool, + #[allow(unused)] + color_when: ColorChoice, + pieces: Vec<(String, Style)>, +} + +impl Colorizer { + #[inline] + pub(crate) fn new(use_stderr: bool, color_when: ColorChoice) -> Self { + Colorizer { + use_stderr, + color_when, + pieces: vec![], + } + } + + #[inline] + pub(crate) fn good(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Good)); + } + + #[inline] + pub(crate) fn warning(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Warning)); + } + + #[inline] + pub(crate) fn error(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Error)); + } + + #[inline] + #[allow(dead_code)] + pub(crate) fn hint(&mut self, msg: impl Into) { + self.pieces.push((msg.into(), Style::Hint)); + } + + #[inline] + 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.use_stderr) => DepColorChoice::Auto, + _ => DepColorChoice::Never, + }; + + let writer = if self.use_stderr { + BufferWriter::stderr(color_when) + } else { + 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. + if self.use_stderr { + let stderr = std::io::stderr(); + let mut stderr = stderr.lock(); + write!(stderr, "{}", self) + } else { + let stdout = std::io::stdout(); + let mut stdout = stdout.lock(); + write!(stdout, "{}", 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(stderr: bool) -> bool { + let stream = if stderr { + atty::Stream::Stderr + } else { + atty::Stream::Stdout + }; + + atty::is(stream) +} diff --git a/third_party/rust/clap/src/output/help.rs b/third_party/rust/clap/src/output/help.rs new file mode 100644 index 000000000000..7544b0c18df3 --- /dev/null +++ b/third_party/rust/clap/src/output/help.rs @@ -0,0 +1,1056 @@ +// Std +use std::{ + borrow::Cow, + cmp, + collections::BTreeMap, + io::{self, Write}, + usize, +}; + +// Internal +use crate::{ + build::{arg::display_arg_val, App, AppSettings, Arg, ArgSettings}, + output::{fmt::Colorizer, Usage}, + parse::Parser, +}; + +// 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, 'app, 'parser, 'writer> { + writer: HelpWriter<'writer>, + parser: &'parser Parser<'help, 'app>, + next_line_help: bool, + hide_pv: bool, + term_w: usize, + use_long: bool, +} + +// Public Functions +impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { + 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}\ + "; + + 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>, + parser: &'parser Parser<'help, 'app>, + use_long: bool, + ) -> Self { + debug!("Help::new"); + let term_w = match parser.app.term_w { + Some(0) => usize::MAX, + Some(w) => w, + None => cmp::min( + dimensions().map_or(100, |(w, _)| w), + match parser.app.max_w { + None | Some(0) => usize::MAX, + Some(mw) => mw, + }, + ), + }; + let next_line_help = parser.is_set(AppSettings::NextLineHelp); + let hide_pv = parser.is_set(AppSettings::HidePossibleValues); + + Help { + writer, + parser, + next_line_help, + hide_pv, + 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.parser.app.help_str { + self.none(h)?; + } else if let Some(tmpl) = self.parser.app.template { + self.write_templated_help(tmpl)?; + } else { + let pos = self + .parser + .app + .get_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let non_pos = self + .parser + .app + .get_non_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let subcmds = self.parser.app.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, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { + fn good + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, good) + } + + fn warning + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, warning) + } + + fn none + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, none) + } + + 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().as_str())); + } + 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>]) -> io::Result<()> { + debug!("Help::write_args"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut ord_m = BTreeMap::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() { + debug!("Help::write_args: Current Longest...{}", longest); + longest = longest.max(display_width(arg.to_string().as_str())); + debug!("Help::write_args: New Longest...{}", longest); + } + let btm = ord_m + .entry(arg.get_display_order()) + .or_insert_with(BTreeMap::new); + + // 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 + }; + btm.insert(key, arg); + } + + let next_line_help = self.will_args_wrap(args, longest); + + let num_ord_m = ord_m.len(); + for (i, btm) in ord_m.values().enumerate() { + let last_btm = i + 1 == num_ord_m; + let num_args = btm.len(); + for (i, arg) in btm.values().enumerate() { + let last_arg = last_btm && i + 1 == num_args; + 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.write_arg_inner(arg, 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 arg.is_positional() { + return Ok(()); + } + if arg.is_set(ArgSettings::TakesValue) { + if let Some(l) = arg.long { + if arg.short.is_some() { + self.none(", ")?; + } + self.good(&format!("--{}", l))? + } + + let sep = if arg.is_set(ArgSettings::RequireEquals) { + "=" + } else { + " " + }; + self.none(sep)?; + } else if let Some(l) = arg.long { + if arg.short.is_some() { + self.none(", ")?; + } + self.good(&format!("--{}", l))?; + } + Ok(()) + } + + /// Writes argument's possible values to the wrapped stream. + fn val(&mut self, arg: &Arg<'help>, next_line_help: bool, longest: usize) -> io::Result<()> { + debug!("Help::val: arg={}", arg.name); + if arg.is_set(ArgSettings::TakesValue) || arg.is_positional() { + display_arg_val( + arg, + |s, good| if good { self.good(s) } else { self.none(s) }, + )?; + } + + debug!("Help::val: Has switch..."); + if self.use_long { + // long help prints messages on the next line so it don't need to align text + debug!("Help::val: printing long help so skip alignment"); + } else if !arg.is_positional() { + debug!("Yes"); + debug!("Help::val: nlh...{:?}", next_line_help); + if !next_line_help { + let self_len = display_width(arg.to_string().as_str()); + // subtract ourself + let mut spcs = longest - self_len; + // Since we're writing spaces from the tab point we first need to know if we + // had a long and short, or just short + if arg.long.is_some() { + // Only account 4 after the val + spcs += 4; + } else { + // Only account for ', --' + 4 after the val + spcs += 8; + } + + self.spaces(spcs)?; + } + } else if !next_line_help { + debug!("No, and not next_line"); + self.spaces(longest + 4 - display_width(&arg.to_string()))?; + } else { + debug!("No"); + } + Ok(()) + } + + fn write_before_help(&mut self) -> io::Result<()> { + debug!("Help::write_before_help"); + let before_help = if self.use_long { + self.parser + .app + .before_long_help + .or(self.parser.app.before_help) + } else { + self.parser.app.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.parser + .app + .after_long_help + .or(self.parser.app.after_help) + } else { + self.parser.app.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, + is_not_positional: bool, + 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(about) + display_width(spec_vals) >= 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)?; + } + for part in help.lines().skip(1) { + self.none("\n")?; + if next_line_help { + self.none(&format!("{}{}{}", TAB, TAB, TAB))?; + } else if is_not_positional { + self.spaces(longest + 12)?; + } else { + self.spaces(longest + 8)?; + } + self.none(part)?; + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg_inner( + &mut self, + arg: &Arg<'help>, + spec_vals: &str, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + self.short(arg)?; + self.long(arg)?; + self.val(arg, next_line_help, longest)?; + + let about = if self.use_long { + arg.long_help.unwrap_or_else(|| arg.help.unwrap_or("")) + } else { + arg.help.unwrap_or_else(|| arg.long_help.unwrap_or("")) + }; + + self.help( + !arg.is_positional(), + about, + spec_vals, + next_line_help, + longest, + )?; + 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_set(ArgSettings::NextLineHelp) || 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_set(ArgSettings::HideEnv) { + debug!( + "Help::spec_vals: Found environment variable...[{:?}:{:?}]", + env.0, env.1 + ); + let env_val = if !a.is_set(ArgSettings::HideEnvValues) { + 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_set(ArgSettings::HideDefaultValue) && !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)); + } + } + + if !self.hide_pv + && !a.is_set(ArgSettings::HidePossibleValues) + && !a.possible_vals.is_empty() + { + debug!( + "Help::spec_vals: Found possible vals...{:?}", + a.possible_vals + ); + + let pvs = a + .possible_vals + .iter() + .filter_map(|value| { + if value.is_hidden() { + None + } else if value.get_name().contains(char::is_whitespace) { + Some(format!("{:?}", value.get_name())) + } else { + Some(value.get_name().to_string()) + } + }) + .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.parser.app.long_about.or(self.parser.app.about) + } else { + self.parser.app.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.parser.app.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.parser.app.version.or(self.parser.app.long_version); + if let Some(output) = version { + self.none(text_wrapper(output, self.term_w))?; + } + Ok(()) + } +} + +/// Methods to write a single subcommand +impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { + fn write_subcommand( + &mut self, + sc_str: &str, + app: &App<'help>, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::write_subcommand"); + + let spec_vals = &self.sc_spec_vals(app); + + let about = app.about.unwrap_or_else(|| app.long_about.unwrap_or("")); + + self.subcmd(sc_str, next_line_help, longest)?; + self.help(false, about, spec_vals, next_line_help, longest) + } + + fn sc_spec_vals(&self, a: &App) -> String { + debug!("Help::sc_spec_vals: a={}", a.name); + let mut spec_vals = vec![]; + if !a.aliases.is_empty() || !a.short_flag_aliases.is_empty() { + debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); + debug!( + "Help::spec_vals: Found short flag aliases...{:?}", + a.short_flag_aliases + ); + + 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, app: &App<'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 = app.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, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, '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 + .parser + .app + .get_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::>(); + let non_pos = self + .parser + .app + .get_non_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::>(); + let subcmds = self.parser.app.has_visible_subcommands(); + + let custom_headings = self + .parser + .app + .args + .args() + .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)?; + first = false; + } + if !custom_headings.is_empty() { + for heading in custom_headings { + let args = self + .parser + .app + .args + .args() + .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)?; + first = false + } + } + } + + if subcmds { + if !first { + self.none("\n\n")?; + } + + self.warning(self.parser.app.subcommand_heading.unwrap_or("SUBCOMMANDS"))?; + self.warning(":\n")?; + + self.write_subcommands(self.parser.app)?; + } + + Ok(()) + } + + /// Will use next line help on writing subcommands. + fn will_subcommands_wrap(&self, subcommands: &[App<'help>], longest: usize) -> bool { + subcommands + .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, app: &App<'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_m = BTreeMap::new(); + for subcommand in app + .subcommands + .iter() + .filter(|subcommand| should_show_subcommand(subcommand)) + { + let btm = ord_m + .entry(subcommand.get_display_order()) + .or_insert_with(BTreeMap::new); + let mut sc_str = String::new(); + sc_str.push_str( + &subcommand + .short_flag + .map_or(String::new(), |c| format!("-{}, ", c)), + ); + sc_str.push_str( + &subcommand + .long_flag + .map_or(String::new(), |c| format!("--{}, ", c)), + ); + sc_str.push_str(&subcommand.name); + longest = longest.max(display_width(&sc_str)); + btm.insert(sc_str, subcommand.clone()); + } + + debug!("Help::write_subcommands longest = {}", longest); + + let next_line_help = self.will_subcommands_wrap(&app.subcommands, longest); + + let mut first = true; + for btm in ord_m.values() { + for (sc_str, sc) in btm { + 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_bin_name(&mut self) -> io::Result<()> { + debug!("Help::write_bin_name"); + + let bin_name = if let Some(bn) = self.parser.app.bin_name.as_ref() { + 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.parser.app.name.replace("{n}", "\n"), self.term_w) + } + } else { + text_wrapper(&self.parser.app.name.replace("{n}", "\n"), self.term_w) + }; + self.good(&bin_name)?; + Ok(()) + } +} + +// Methods to write Parser help using templates. +impl<'help, 'app, 'parser, 'writer> Help<'help, 'app, 'parser, 'writer> { + /// Write help to stream for the parser in the format defined by the template. + /// + /// For details about the template language see [`App::help_template`]. + /// + /// [`App::help_template`]: App::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 { + "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(Usage::new(self.parser).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.parser.app.get_non_positionals().collect::>())?; + } + "positionals" => { + self.write_args(&self.parser.app.get_positionals().collect::>())?; + } + "subcommands" => { + self.write_subcommands(self.parser.app)?; + } + "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 = " "; + +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_set(ArgSettings::Hidden) { + return false; + } + (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long) + || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long) + || arg.is_set(ArgSettings::NextLineHelp) +} + +fn should_show_subcommand(subcommand: &App) -> bool { + !subcommand.is_set(AppSettings::Hidden) +} + +fn text_wrapper(help: &str, width: usize) -> String { + let wrapper = textwrap::Options::new(width).break_words(false); + 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/third_party/rust/clap/src/output/mod.rs b/third_party/rust/clap/src/output/mod.rs new file mode 100644 index 000000000000..e32aac26a01b --- /dev/null +++ b/third_party/rust/clap/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/third_party/rust/clap/src/output/usage.rs b/third_party/rust/clap/src/output/usage.rs new file mode 100644 index 000000000000..b520b3d99dc3 --- /dev/null +++ b/third_party/rust/clap/src/output/usage.rs @@ -0,0 +1,466 @@ +// std +use std::collections::BTreeMap; + +use indexmap::IndexSet; + +// Internal +use crate::{ + build::AppSettings as AS, + build::{Arg, ArgSettings}, + parse::{ArgMatcher, Parser}, + util::Id, + INTERNAL_ERROR_MSG, +}; + +pub(crate) struct Usage<'help, 'app, 'parser> { + p: &'parser Parser<'help, 'app>, +} + +impl<'help, 'app, 'parser> Usage<'help, 'app, 'parser> { + pub(crate) fn new(p: &'parser Parser<'help, 'app>) -> Self { + Usage { p } + } + + // 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.p.app.usage_str { + 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) + pub(crate) 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 + .p + .app + .usage + .as_ref() + .unwrap_or_else(|| self.p.app.bin_name.as_ref().unwrap_or(&self.p.app.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 + &format!(" {}", s)[..]) + } else { + String::new() + }; + + if self.needs_options_tag() { + usage.push_str(" [OPTIONS]"); + } + + let allow_missing_positional = self.p.app.is_set(AS::AllowMissingPositional); + if !allow_missing_positional { + usage.push_str(&req_string); + } + + let has_last = self + .p + .app + .get_positionals() + .any(|p| p.is_set(ArgSettings::Last)); + // places a '--' in the usage string if there are args and options + // supporting multiple values + if self + .p + .app + .get_non_positionals() + .any(|o| o.is_set(ArgSettings::MultipleValues)) + && self + .p + .app + .get_positionals() + .any(|p| !p.is_set(ArgSettings::Required)) + && !(self.p.app.has_visible_subcommands() + || self.p.is_set(AS::AllowExternalSubcommands)) + && !has_last + { + usage.push_str(" [--]"); + } + let not_req_or_hidden = |p: &Arg| { + (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last)) + && !p.is_set(ArgSettings::Hidden) + }; + if self.p.app.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 + .p + .app + .get_positionals() + .find(|p| p.is_set(ArgSettings::Last)) + .expect(INTERNAL_ERROR_MSG); + debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name); + let req = pos.is_set(ArgSettings::Required); + if req + && self + .p + .app + .get_positionals() + .any(|p| !p.is_set(ArgSettings::Required)) + { + 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.p.app.has_visible_subcommands() && incl_reqs + || self.p.is_set(AS::AllowExternalSubcommands) + { + let placeholder = self.p.app.subcommand_value_name.unwrap_or("SUBCOMMAND"); + if self.p.is_set(AS::SubcommandsNegateReqs) || self.p.is_set(AS::ArgsNegateSubcommands) + { + usage.push_str("\n "); + if !self.p.is_set(AS::ArgsNegateSubcommands) { + 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.p.is_set(AS::SubcommandRequired) + || self.p.is_set(AS::SubcommandRequiredElseHelp) + { + usage.push_str(" <"); + usage.push_str(placeholder); + usage.push('>'); + } else { + usage.push_str(" ["); + usage.push_str(placeholder); + usage.push(']'); + } + } + usage.shrink_to_fit(); + 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 + &format!(" {}", s)[..]); + + usage.push_str( + &self + .p + .app + .usage + .as_ref() + .unwrap_or_else(|| self.p.app.bin_name.as_ref().unwrap_or(&self.p.app.name))[..], + ); + usage.push_str(&*r_string); + if self.p.is_set(AS::SubcommandRequired) { + usage.push_str(" <"); + usage.push_str(self.p.app.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 + .p + .app + .get_positionals() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + { + debug!("Usage::get_args_tag:iter:{}", pos.name); + let required = self.p.app.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.p + .app + .groups + .iter() + .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.p.is_set(AS::DontCollapseArgsInUsage) && count > 1 { + debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]"); + + // [ARGS] + None + } else if count == 1 && incl_reqs { + let pos = self + .p + .app + .get_positionals() + .find(|pos| { + !pos.is_set(ArgSettings::Required) + && !pos.is_set(ArgSettings::Hidden) + && !pos.is_set(ArgSettings::Last) + && !self.p.app.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.p + .app + .groups + .iter() + .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.p.is_set(AS::DontCollapseArgsInUsage) + && self.p.app.has_positionals() + && incl_reqs + { + debug!("Usage::get_args_tag:iter: Don't collapse returning all"); + Some( + self.p + .app + .get_positionals() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .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 + .p + .app + .get_positionals() + .filter_map(|pos| { + if pos.is_set(ArgSettings::Required) && !pos.is_set(ArgSettings::Last) { + Some(pos.index) + } else { + None + } + }) + .max() + .unwrap_or_else(|| Some(self.p.app.get_positionals().count())); + Some( + self.p + .app + .get_positionals() + .filter(|pos| pos.index <= highest_req_pos) + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .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.p.app.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_set(ArgSettings::Hidden) { + debug!("Usage::needs_options_tag:iter Option is hidden"); + continue; + } + if f.is_set(ArgSettings::Required) { + debug!("Usage::needs_options_tag:iter Option is required"); + continue; + } + for grp_s in self.p.app.groups_for_arg(&f.id) { + debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s); + if self + .p + .app + .groups + .iter() + .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, + ) -> Vec { + debug!( + "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}", + incls, + matcher.is_some(), + incl_last + ); + let mut ret_val = Vec::new(); + + let mut unrolled_reqs = IndexSet::new(); + + for a in self.p.required.iter() { + if let Some(m) = matcher { + for aa in self.p.app.unroll_requirements_for_arg(a, m) { + // 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 + .p + .app + .groups + .iter() + .filter(|gn| self.p.required.contains(&gn.id)) + .flat_map(|g| self.p.app.unroll_args_in_group(&g.id)) + .collect::>(); + + for a in unrolled_reqs + .iter() + .chain(incls.iter()) + .filter(|name| !self.p.app.get_positionals().any(|p| &&p.id == name)) + .filter(|name| !self.p.app.groups.iter().any(|g| &&g.id == name)) + .filter(|name| !args_in_groups.contains(name)) + .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name))) + { + debug!("Usage::get_required_usage_from:iter:{:?}", a); + let arg = self.p.app.find(a).expect(INTERNAL_ERROR_MSG).to_string(); + ret_val.push(arg); + } + let mut g_vec: Vec = vec![]; + for g in unrolled_reqs + .iter() + .filter(|n| self.p.app.groups.iter().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 + .p + .app + .unroll_args_in_group(g) + .iter() + .any(|arg| m.contains(arg)); + if have_group_entry { + continue; + } + } + + let elem = self.p.app.format_group(g); + if !g_vec.contains(&elem) { + g_vec.push(elem); + } + } + ret_val.extend_from_slice(&g_vec); + + let pmap = unrolled_reqs + .iter() + .chain(incls.iter()) + .filter(|a| self.p.app.get_positionals().any(|p| &&p.id == a)) + .filter(|&pos| matcher.map_or(true, |m| !m.contains(pos))) + .filter_map(|pos| self.p.app.find(pos)) + .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) + .filter(|pos| !args_in_groups.contains(&pos.id)) + .map(|pos| (pos.index.unwrap(), pos)) + .collect::>(); // sort by index + + for p in pmap.values() { + debug!("Usage::get_required_usage_from:iter:{:?}", p.id); + if !args_in_groups.contains(&p.id) { + ret_val.push(p.to_string()); + } + } + + debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val); + ret_val + } +} diff --git a/third_party/rust/clap/src/parse/arg_matcher.rs b/third_party/rust/clap/src/parse/arg_matcher.rs new file mode 100644 index 000000000000..9e5a59c03515 --- /dev/null +++ b/third_party/rust/clap/src/parse/arg_matcher.rs @@ -0,0 +1,222 @@ +// Std +use std::{collections::HashMap, ffi::OsString, mem, ops::Deref}; + +// Internal +use crate::{ + build::{App, Arg, ArgSettings}, + parse::{ArgMatches, MatchedArg, SubCommand, ValueType}, + util::Id, +}; + +// Third party +use indexmap::map::Entry; + +#[derive(Debug, Default)] +pub(crate) struct ArgMatcher(pub(crate) ArgMatches); + +impl ArgMatcher { + pub(crate) fn new(_app: &App) -> Self { + ArgMatcher(ArgMatches { + #[cfg(debug_assertions)] + valid_args: { + let args = _app.args.args().map(|a| a.id.clone()); + let groups = _app.groups.iter().map(|g| g.id.clone()); + args.chain(groups).collect() + }, + #[cfg(debug_assertions)] + valid_subcommands: _app.subcommands.iter().map(|sc| sc.id.clone()).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)] + disable_asserts: _app.is_set(crate::AppSettings::AllowExternalSubcommands), + ..Default::default() + }) + } + + pub(crate) fn into_inner(self) -> ArgMatches { + self.0 + } + + 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`, however the occurs will be 0. + let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { + if parent_ma.occurs > 0 && ma.occurs == 0 { + parent_ma.clone() + } else { + ma.clone() + } + } else { + ma.clone() + }; + vals_map.insert(global_arg.clone(), to_update); + } + } + if let Some(ref mut sc) = self.0.subcommand { + let mut am = ArgMatcher(mem::take(&mut sc.matches)); + am.fill_in_global_values(global_arg_vec, vals_map); + mem::swap(&mut am.0, &mut sc.matches); + } + + for (name, matched_arg) in vals_map.iter_mut() { + self.0.args.insert(name.clone(), matched_arg.clone()); + } + } + + pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> { + self.0.args.get_mut(arg) + } + + pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> { + self.0.args.get(arg) + } + + pub(crate) fn remove(&mut self, arg: &Id) { + self.0.args.swap_remove(arg); + } + + pub(crate) fn contains(&self, arg: &Id) -> bool { + self.0.args.contains_key(arg) + } + + pub(crate) fn contains_explicit(&self, arg: &Id) -> bool { + self.0 + .args + .get(arg) + .map_or(false, |a| a.ty != ValueType::DefaultValue) + } + + pub(crate) fn is_empty(&self) -> bool { + self.0.args.is_empty() + } + + pub(crate) fn arg_names(&self) -> indexmap::map::Keys { + self.0.args.keys() + } + + pub(crate) fn entry(&mut self, arg: &Id) -> indexmap::map::Entry { + self.0.args.entry(arg.clone()) + } + + pub(crate) fn subcommand(&mut self, sc: SubCommand) { + self.0.subcommand = Some(Box::new(sc)); + } + + pub(crate) fn subcommand_name(&self) -> Option<&str> { + self.0.subcommand_name() + } + + pub(crate) fn iter(&self) -> indexmap::map::Iter { + self.0.args.iter() + } + + pub(crate) fn inc_occurrence_of_arg(&mut self, arg: &Arg) { + let id = &arg.id; + debug!("ArgMatcher::inc_occurrence_of_arg: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new()); + ma.set_ty(ValueType::CommandLine); + ma.set_ignore_case(arg.is_set(ArgSettings::IgnoreCase)); + ma.invalid_utf8_allowed(arg.is_set(ArgSettings::AllowInvalidUtf8)); + ma.occurs += 1; + } + + pub(crate) fn inc_occurrence_of_group(&mut self, id: &Id) { + debug!("ArgMatcher::inc_occurrence_of_group: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new()); + ma.set_ty(ValueType::CommandLine); + ma.occurs += 1; + } + + pub(crate) fn add_val_to(&mut self, arg: &Id, val: OsString, ty: ValueType, append: bool) { + if append { + self.append_val_to(arg, val, ty); + } else { + self.push_val_to(arg, val, ty); + } + } + + fn push_val_to(&mut self, arg: &Id, val: OsString, ty: ValueType) { + // We will manually inc occurrences later(for flexibility under + // specific circumstances, like only add one occurrence for flag + // when we met: `--flag=one,two`). + let ma = self.entry(arg).or_default(); + ma.set_ty(ty); + ma.push_val(val); + } + + fn append_val_to(&mut self, arg: &Id, val: OsString, ty: ValueType) { + let ma = self.entry(arg).or_default(); + ma.set_ty(ty); + ma.append_val(val); + } + + pub(crate) fn new_val_group(&mut self, arg: &Id) { + let ma = self.entry(arg).or_default(); + ma.new_val_group(); + } + + pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize, ty: ValueType) { + let ma = self.entry(arg).or_default(); + ma.set_ty(ty); + ma.push_index(idx); + } + + pub(crate) fn has_val_groups(&mut self, arg: &Id) -> bool { + match self.entry(arg) { + Entry::Occupied(e) => e.get().has_val_groups(), + Entry::Vacant(_) => false, + } + } + + pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool { + debug!("ArgMatcher::needs_more_vals: o={}", o.name); + if let Some(ma) = self.get(&o.id) { + let current_num = ma.num_vals(); + if let Some(num) = o.num_vals { + debug!("ArgMatcher::needs_more_vals: num_vals...{}", num); + return if o.is_set(ArgSettings::MultipleOccurrences) { + (current_num % num) != 0 + } else { + num != current_num + }; + } else if let Some(num) = o.max_vals { + debug!("ArgMatcher::needs_more_vals: max_vals...{}", num); + return current_num < num; + } else if o.min_vals.is_some() { + debug!("ArgMatcher::needs_more_vals: min_vals...true"); + return true; + } + return o.is_set(ArgSettings::MultipleValues); + } + true + } +} + +impl Deref for ArgMatcher { + type Target = ArgMatches; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/third_party/rust/clap/src/parse/errors.rs b/third_party/rust/clap/src/parse/errors.rs new file mode 100644 index 000000000000..454834b965ab --- /dev/null +++ b/third_party/rust/clap/src/parse/errors.rs @@ -0,0 +1,1242 @@ +// Std +use std::{ + borrow::Cow, + convert::From, + error, + fmt::{self, Debug, Display, Formatter}, + io::{self, BufRead}, + result::Result as StdResult, +}; + +// Internal +use crate::{ + build::Arg, + output::fmt::Colorizer, + parse::features::suggestions, + util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}, + App, AppSettings, +}; + +/// Short hand for [`Result`] type +/// +/// [`Result`]: std::result::Result +pub type Result = StdResult; + +/// Command line argument parser kind of error +#[derive(Debug, Copy, Clone, PartialEq)] +#[non_exhaustive] +pub enum ErrorKind { + /// Occurs when an [`Arg`] has a set of possible values, + /// and the user provides a value which isn't in that set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::new("prog") + /// .arg(Arg::new("speed") + /// .possible_value("fast") + /// .possible_value("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::{App, arg, ErrorKind}; + /// let result = App::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::{App, Arg, ErrorKind, }; + /// let result = App::new("prog") + /// .subcommand(App::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use") + /// .index(1))) + /// .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::{App, Arg, ErrorKind, }; + /// let result = App::new("prog") + /// .subcommand(App::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use") + /// .index(1))) + /// .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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, Arg, ErrorKind}; + /// let res = App::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::{App, 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 = App::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::{App, Arg, ErrorKind}; + /// let result = App::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`]: 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::{App, Arg, ErrorKind}; + /// let result = App::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`]: 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::{App, Arg, ErrorKind}; + /// let result = App::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`]: 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::{App, Arg, ErrorKind}; + /// let result = App::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`]: Arg::number_of_values() + /// [`Arg::value_names`]: 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::{App, Arg, ErrorKind}; + /// let result = App::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::{App, Arg, ErrorKind}; + /// let result = App::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 [`AppSettings::SubcommandRequired`]), + /// but the user does not provide one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let err = App::new("prog") + /// .setting(AppSettings::SubcommandRequired) + /// .subcommand(App::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`AppSettings::SubcommandRequired`]: crate::AppSettings::SubcommandRequired + MissingSubcommand, + + /// Occurs when the user provides multiple values to an argument which doesn't allow that. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::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 [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`] 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::{App, Arg, ErrorKind, AppSettings}; + /// # use std::os::unix::ffi::OsStringExt; + /// # use std::ffi::OsString; + /// let result = App::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 + /// [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`]: crate::AppSettings::AllowInvalidUtf8ForExternalSubcommands + 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::{App, Arg, ErrorKind}; + /// let result = App::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 + /// [`AppSettings::ArgRequiredElseHelp`] and + /// [`AppSettings::SubcommandRequiredElseHelp`], but the user did not provide + /// one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, ErrorKind, }; + /// let result = App::new("prog") + /// .setting(AppSettings::ArgRequiredElseHelp) + /// .subcommand(App::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 + /// [`AppSettings::ArgRequiredElseHelp`]: crate::AppSettings::ArgRequiredElseHelp + /// [`AppSettings::SubcommandRequiredElseHelp`]: crate::AppSettings::SubcommandRequiredElseHelp + DisplayHelpOnMissingArgumentOrSubcommand, + + /// Not a true "error" as it means `--version` or similar was used. + /// The message will be sent to `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, ErrorKind}; + /// let result = App::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, +} + +/// Command Line Argument Parser Error +/// +/// See [`App::error`] to create an error. +/// +/// [`App::error`]: crate::App::error +#[derive(Debug)] +pub struct Error { + /// Formatted error message, enhancing the cause message with extra information + pub(crate) message: Message, + /// The type of error + pub kind: ErrorKind, + /// Additional information depending on the error kind, like values and argument names. + /// Useful when you want to render an error of your own. + pub info: Vec, + pub(crate) source: Option>, + 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 `App` at which point you can call [`Error::format`]. + /// + /// Prefer [`App::error`] for generating errors. + /// + /// [`App::error`]: crate::App::error + pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { + Self::new(message.to_string(), kind, false) + } + + /// Format the existing message with the App's context + #[must_use] + pub fn format(mut self, app: &mut App) -> Self { + app._build(); + let usage = app.render_usage(); + self.message.format(app, usage); + self.wait_on_exit = app.settings.is_set(AppSettings::WaitOnError); + self + } + + /// Should the message be written to `stdout` or not? + #[inline] + pub fn use_stderr(&self) -> bool { + !matches!( + self.kind, + ErrorKind::DisplayHelp | ErrorKind::DisplayVersion + ) + } + + /// Prints the error and exits. + /// + /// Depending on the error kind, this either prints to `stderr` and exits with a status of `1` + /// 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.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::App; + /// + /// match App::new("App").try_get_matches() { + /// Ok(matches) => { + /// // do_something + /// }, + /// Err(err) => { + /// err.print().expect("Error writing Error"); + /// // do_something + /// }, + /// }; + /// ``` + pub fn print(&self) -> io::Result<()> { + self.message.formatted().print() + } + + /// Deprecated, replaced with [`App::error`] + /// + /// [`App::error`]: crate::App::error + #[deprecated(since = "3.0.0", note = "Replaced with `App::error`")] + pub fn with_description(description: String, kind: ErrorKind) -> Self { + Error::raw(kind, description) + } + + pub(crate) fn new(message: impl Into, kind: ErrorKind, wait_on_exit: bool) -> Self { + Self { + message: message.into(), + kind, + info: vec![], + source: None, + wait_on_exit, + backtrace: Backtrace::new(), + } + } + + 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.source = Some(source); + self + } + + pub(crate) fn argument_conflict( + app: &App, + arg: &Arg, + others: Vec, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let arg = arg.to_string(); + + start_error(&mut c, "The argument '"); + c.warning(arg); + c.none("' cannot be used with"); + + let mut info = vec![]; + match others.len() { + 0 => { + c.none(" one or more of the other specified arguments"); + } + 1 => { + let v = &others[0]; + c.none(" '"); + c.warning(v.clone()); + c.none("'"); + info.push(v.clone()); + } + _ => { + c.none(":"); + for v in others { + c.none("\n "); + c.warning(v.to_string()); + info.push(v.to_string()); + } + } + } + + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::ArgumentConflict, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(info) + } + + pub(crate) fn empty_value(app: &App, arg: &Arg, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let arg = arg.to_string(); + + start_error(&mut c, "The argument '"); + c.warning(arg.clone()); + c.none("' requires a value but none was supplied"); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::EmptyValue, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg]) + } + + pub(crate) fn no_equals(app: &App, arg: String, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "Equal sign is needed when assigning values to '"); + c.warning(&arg); + c.none("'."); + + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::NoEquals, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg]) + } + + pub(crate) fn invalid_value( + app: &App, + bad_val: String, + good_vals: &[G], + arg: &Arg, + usage: String, + ) -> Self + where + G: AsRef + Display, + { + let mut c = Colorizer::new(true, app.get_color()); + let suffix = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); + + let mut sorted: Vec = good_vals + .iter() + .map(|v| v.to_string()) + .map(|v| { + if v.contains(char::is_whitespace) { + format!("{:?}", v) + } else { + v + } + }) + .collect(); + sorted.sort(); + + start_error(&mut c, ""); + c.warning(format!("{:?}", bad_val)); + c.none(" isn't a valid value for '"); + c.warning(arg.to_string()); + c.none("'\n\t[possible values: "); + + if let Some((last, elements)) = sorted.split_last() { + for v in elements { + c.good(v); + c.none(", "); + } + + c.good(last); + } + + c.none("]"); + + if let Some(val) = suffix { + c.none("\n\n\tDid you mean "); + c.good(format!("{:?}", val)); + c.none("?"); + } + + put_usage(&mut c, usage); + try_help(app, &mut c); + + let mut info = vec![arg.to_string(), bad_val]; + info.extend(sorted); + + Self::new( + c, + ErrorKind::InvalidValue, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(info) + } + + pub(crate) fn invalid_subcommand( + app: &App, + subcmd: String, + did_you_mean: String, + name: String, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "The subcommand '"); + c.warning(subcmd.clone()); + c.none("' wasn't recognized\n\n\tDid you mean "); + c.good(did_you_mean); + c.none(""); + c.none(format!( + "?\n\nIf you believe you received this message in error, try re-running with '{} ", + name + )); + c.good("--"); + c.none(format!(" {}'", subcmd)); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::InvalidSubcommand, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![subcmd]) + } + + pub(crate) fn unrecognized_subcommand(app: &App, subcmd: String, name: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, " The subcommand '"); + c.warning(subcmd.clone()); + c.none("' wasn't recognized\n\n"); + c.warning("USAGE:"); + c.none(format!("\n {} ", name)); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::UnrecognizedSubcommand, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![subcmd]) + } + + pub(crate) fn missing_required_argument( + app: &App, + required: Vec, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error( + &mut c, + "The following required arguments were not provided:", + ); + + let mut info = vec![]; + for v in required { + c.none("\n "); + c.good(v.to_string()); + info.push(v.to_string()); + } + + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::MissingRequiredArgument, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(info) + } + + pub(crate) fn missing_subcommand(app: &App, name: String, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "'"); + c.warning(name); + c.none("' requires a subcommand, but one was not provided"); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::MissingSubcommand, + app.settings.is_set(AppSettings::WaitOnError), + ) + } + + pub(crate) fn invalid_utf8(app: &App, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error( + &mut c, + "Invalid UTF-8 was detected in one or more arguments", + ); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::InvalidUtf8, + app.settings.is_set(AppSettings::WaitOnError), + ) + } + + pub(crate) fn too_many_occurrences( + app: &App, + arg: &Arg, + max_occurs: usize, + curr_occurs: usize, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let verb = Error::singular_or_plural(curr_occurs); + + start_error(&mut c, "The argument '"); + c.warning(arg.to_string()); + c.none("' allows at most "); + c.warning(max_occurs.to_string()); + c.none(" occurrences, but "); + c.warning(curr_occurs.to_string()); + c.none(format!(" {} provided", verb)); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::TooManyOccurrences, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![ + arg.to_string(), + curr_occurs.to_string(), + max_occurs.to_string(), + ]) + } + + pub(crate) fn too_many_values(app: &App, val: String, arg: String, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "The value '"); + c.warning(val.clone()); + c.none("' was provided to '"); + c.warning(&arg); + c.none("' but it wasn't expecting any more values"); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::TooManyValues, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg, val]) + } + + pub(crate) fn too_few_values( + app: &App, + arg: &Arg, + min_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let verb = Error::singular_or_plural(curr_vals); + + start_error(&mut c, "The argument '"); + c.warning(arg.to_string()); + c.none("' requires at least "); + c.warning(min_vals.to_string()); + c.none(" values, but only "); + c.warning(curr_vals.to_string()); + c.none(format!(" {} provided", verb)); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::TooFewValues, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![ + arg.to_string(), + curr_vals.to_string(), + min_vals.to_string(), + ]) + } + + pub(crate) fn value_validation( + app: &App, + arg: String, + val: String, + err: Box, + ) -> Self { + let mut err = Self::value_validation_with_color( + arg, + val, + err, + app.get_color(), + app.settings.is_set(AppSettings::WaitOnError), + ); + match &mut err.message { + Message::Raw(_) => { + unreachable!("`value_validation_with_color` only deals in formatted errors") + } + Message::Formatted(c) => try_help(app, c), + } + err + } + + pub(crate) fn value_validation_without_app( + arg: String, + val: String, + err: Box, + ) -> Self { + let mut err = Self::value_validation_with_color(arg, val, err, ColorChoice::Never, false); + match &mut err.message { + Message::Raw(_) => { + unreachable!("`value_validation_with_color` only deals in formatted errors") + } + Message::Formatted(c) => { + c.none("\n"); + } + } + err + } + + fn value_validation_with_color( + arg: String, + val: String, + err: Box, + color: ColorChoice, + wait_on_exit: bool, + ) -> Self { + let mut c = Colorizer::new(true, color); + + start_error(&mut c, "Invalid value"); + + c.none(" for '"); + c.warning(arg.clone()); + c.none("'"); + + c.none(format!(": {}", err)); + + Self::new(c, ErrorKind::ValueValidation, wait_on_exit) + .set_info(vec![arg, val, err.to_string()]) + .set_source(err) + } + + pub(crate) fn wrong_number_of_values( + app: &App, + arg: &Arg, + num_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let verb = Error::singular_or_plural(curr_vals); + + start_error(&mut c, "The argument '"); + c.warning(arg.to_string()); + c.none("' requires "); + c.warning(num_vals.to_string()); + c.none(" values, but "); + c.warning(curr_vals.to_string()); + c.none(format!(" {} provided", verb)); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::WrongNumberOfValues, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![ + arg.to_string(), + curr_vals.to_string(), + num_vals.to_string(), + ]) + } + + pub(crate) fn unexpected_multiple_usage(app: &App, arg: &Arg, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + let arg = arg.to_string(); + + start_error(&mut c, "The argument '"); + c.warning(arg.clone()); + c.none("' was provided more than once, but cannot be used multiple times"); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::UnexpectedMultipleUsage, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg]) + } + + pub(crate) fn unknown_argument( + app: &App, + arg: String, + did_you_mean: Option<(String, Option)>, + usage: String, + ) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "Found argument '"); + c.warning(arg.clone()); + c.none("' which wasn't expected, or isn't valid in this context"); + + if let Some((flag, subcmd)) = did_you_mean { + let flag = format!("--{}", flag); + c.none("\n\n\tDid you mean "); + + if let Some(subcmd) = subcmd { + c.none("to put '"); + c.good(flag); + c.none("' after the subcommand '"); + c.good(subcmd); + c.none("'?"); + } else { + c.none("'"); + c.good(flag); + c.none("'?"); + } + } + + // If the user wants to supply things like `--a-flag` or `-b` as a value, + // suggest `--` for disambiguation. + if arg.starts_with('-') { + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a value rather than a flag, use `-- {}`", + arg, arg + )); + } + + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::UnknownArgument, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg]) + } + + pub(crate) fn unnecessary_double_dash(app: &App, arg: String, usage: String) -> Self { + let mut c = Colorizer::new(true, app.get_color()); + + start_error(&mut c, "Found argument '"); + c.warning(arg.clone()); + c.none("' which wasn't expected, or isn't valid in this context"); + + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a subcommand, remove the '--' before it.", + arg + )); + put_usage(&mut c, usage); + try_help(app, &mut c); + + Self::new( + c, + ErrorKind::UnknownArgument, + app.settings.is_set(AppSettings::WaitOnError), + ) + .set_info(vec![arg]) + } + + pub(crate) fn argument_not_found_auto(arg: String) -> Self { + let mut c = Colorizer::new(true, ColorChoice::Never); + + start_error(&mut c, "The argument '"); + c.warning(arg.clone()); + c.none("' wasn't found\n"); + + Self::new(c, ErrorKind::ArgumentNotFound, false).set_info(vec![arg]) + } + + /// Returns the singular or plural form on the verb to be based on the argument's value. + fn singular_or_plural(n: usize) -> String { + if n > 1 { + String::from("were") + } else { + String::from("was") + } + } +} + +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.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.message.formatted())?; + if let Some(backtrace) = self.backtrace.as_ref() { + writeln!(f)?; + writeln!(f, "Backtrace:")?; + writeln!(f, "{}", backtrace)?; + } + Ok(()) + } +} + +fn start_error(c: &mut Colorizer, msg: impl Into) { + c.error("error:"); + c.none(" "); + c.none(msg); +} + +fn put_usage(c: &mut Colorizer, usage: impl Into) { + c.none("\n\n"); + c.none(usage); +} + +fn try_help(app: &App, c: &mut Colorizer) { + if !app.settings.is_set(AppSettings::DisableHelpFlag) { + c.none("\n\nFor more information try "); + c.good("--help"); + c.none("\n"); + } else if app.has_subcommands() && !app.settings.is_set(AppSettings::DisableHelpSubcommand) { + c.none("\n\nFor more information try "); + c.good("help"); + c.none("\n"); + } else { + c.none("\n"); + } +} + +#[derive(Clone, Debug)] +pub(crate) enum Message { + Raw(String), + Formatted(Colorizer), +} + +impl Message { + fn format(&mut self, app: &App, usage: String) { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(true, app.get_color()); + + let mut message = String::new(); + std::mem::swap(s, &mut message); + start_error(&mut c, message); + put_usage(&mut c, usage); + try_help(app, &mut c); + *self = Self::Formatted(c); + } + Message::Formatted(_) => {} + } + } + + fn formatted(&self) -> Cow { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(true, ColorChoice::Never); + start_error(&mut c, 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/third_party/rust/clap/src/parse/features/mod.rs b/third_party/rust/clap/src/parse/features/mod.rs new file mode 100644 index 000000000000..bdeb766ecd37 --- /dev/null +++ b/third_party/rust/clap/src/parse/features/mod.rs @@ -0,0 +1 @@ +pub(crate) mod suggestions; diff --git a/third_party/rust/clap/src/parse/features/suggestions.rs b/third_party/rust/clap/src/parse/features/suggestions.rs new file mode 100644 index 000000000000..b690ec635746 --- /dev/null +++ b/third_party/rust/clap/src/parse/features/suggestions.rs @@ -0,0 +1,104 @@ +#[cfg(feature = "suggestions")] +use std::cmp::Ordering; + +// Internal +use crate::build::App; + +/// 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( + arg: &str, + remaining_args: &[&str], + longs: I, + subcommands: &mut [App], +) -> Option<(String, Option)> +where + T: AsRef, + I: IntoIterator, +{ + use crate::mkeymap::KeyType; + + match did_you_mean(arg, longs).pop() { + Some(candidate) => Some((candidate, None)), + None => subcommands + .iter_mut() + .filter_map(|subcommand| { + subcommand._build(); + + let longs = subcommand.args.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/third_party/rust/clap/src/parse/matches/arg_matches.rs b/third_party/rust/clap/src/parse/matches/arg_matches.rs new file mode 100644 index 000000000000..a4bb3f5a42e6 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/arg_matches.rs @@ -0,0 +1,1434 @@ +// Std +use std::{ + borrow::Cow, + ffi::{OsStr, OsString}, + fmt::{Debug, Display}, + iter::{Cloned, Flatten, Map}, + slice::Iter, + str::FromStr, +}; + +// Third Party +use indexmap::IndexMap; + +// Internal +use crate::{ + parse::MatchedArg, + util::{Id, Key}, + {Error, INVALID_UTF8}, +}; + +/// 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 [`App::get_matches`] family of +/// methods. +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{App, Arg}; +/// let matches = App::new("MyApp") +/// .arg(Arg::new("out") +/// .long("output") +/// .required(true) +/// .takes_value(true)) +/// .arg(Arg::new("debug") +/// .short('d') +/// .multiple_occurrences(true)) +/// .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::value_of +/// if let Some(c) = matches.value_of("cfg") { +/// println!("Value for -c: {}", c); +/// } +/// +/// // The ArgMatches::value_of 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.value_of("out").unwrap()); +/// +/// // You can check the presence of an argument +/// if matches.is_present("out") { +/// // Another way to check if an argument was present, or if it occurred multiple times is to +/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the +/// // number of times that it occurred, if it was. To allow an argument to appear more than +/// // once, you must use the .multiple_occurrences(true) method, otherwise it will only return 1 or 0. +/// if matches.occurrences_of("debug") > 2 { +/// println!("Debug mode is REALLY on, don't be crazy"); +/// } else { +/// println!("Debug mode kind of on"); +/// } +/// } +/// ``` +/// [`App::get_matches`]: crate::App::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>, +} + +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 `None` if the option wasn't present. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::new("output") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "something"]); + /// + /// assert_eq!(m.value_of("output"), Some("something")); + /// ``` + /// [option]: crate::Arg::takes_value() + /// [positional]: crate::Arg::index() + /// [`ArgMatches::values_of`]: ArgMatches::values_of() + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: crate::ArgMatches::occurrences_of() + pub fn value_of(&self, id: T) -> Option<&str> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.to_str().expect(INVALID_UTF8)) + } + + /// Gets the lossy value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// A lossy value is one which contains invalid UTF-8, those invalid points will be replaced + /// with `\u{FFFD}` + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of_lossy`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of_lossy` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(arg!( "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!"); + /// ``` + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + /// [`Arg::values_of_lossy`]: ArgMatches::values_of_lossy() + #[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)?; + assert_no_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.to_string_lossy()) + } + + /// Get the `OsStr` value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// 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. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of_os`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of_os` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(arg!( "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); + /// ``` + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::values_of_os`]: ArgMatches::values_of_os() + #[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)?; + assert_no_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.as_os_str()) + } + + /// Get an [`Iterator`] over [values] of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::new("output") + /// .multiple_occurrences(true) + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "myprog", "-o", "val1", "-o", "val2", "-o", "val3" + /// ]); + /// let vals: Vec<&str> = m.values_of("output").unwrap().collect(); + /// assert_eq!(vals, ["val1", "val2", "val3"]); + /// ``` + /// [values]: Values + /// [`Iterator`]: std::iter::Iterator + pub fn values_of(&self, id: T) -> Option { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + fn to_str_slice(o: &OsString) -> &str { + o.to_str().expect(INVALID_UTF8) + } + let v = Values { + iter: arg.vals_flatten().map(to_str_slice), + len: arg.num_vals(), + }; + Some(v) + } + + /// Placeholder documentation. + #[cfg(feature = "unstable-grouped")] + pub fn grouped_values_of(&self, id: T) -> Option { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + let v = GroupedValues { + iter: arg + .vals() + .map(|g| g.iter().map(|x| x.to_str().expect(INVALID_UTF8)).collect()), + len: arg.vals().len(), + }; + Some(v) + } + + /// Get the lossy values of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// A lossy value is one which contains invalid UTF-8, those invalid points will be replaced + /// with `\u{FFFD}` + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::OsStringExt; + /// + /// let m = App::new("utf8") + /// .arg(arg!( ... "some arg") + /// .allow_invalid_utf8(true)) + /// .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.values_of_lossy("arg").unwrap().into_iter(); + /// assert_eq!(&itr.next().unwrap()[..], "Hi"); + /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); + /// assert_eq!(itr.next(), None); + /// ``` + #[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)?; + assert_no_utf8_validation(arg, &id); + let v = arg + .vals_flatten() + .map(|v| v.to_string_lossy().into_owned()) + .collect(); + Some(v) + } + + /// Get an [`Iterator`] over [`OsStr`] [values] of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// 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. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, arg}; + /// use std::ffi::{OsStr,OsString}; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = App::new("utf8") + /// .arg(arg!( ... "some arg") + /// .allow_invalid_utf8(true)) + /// .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.values_of_os("arg").unwrap().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 + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_os(&self, id: T) -> Option { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_no_utf8_validation(arg, &id); + fn to_str_slice(o: &OsString) -> &OsStr { + o + } + let v = OsValues { + iter: arg.vals_flatten().map(to_str_slice), + len: arg.num_vals(), + }; + Some(v) + } + + /// Parse the value (with [`FromStr`]) of a specific option or positional argument. + /// + /// There are two types of errors, parse failures and those where the argument wasn't present + /// (such as a non-required argument). Check [`ErrorKind`] to distinguish them. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of_t`] as this method will only return the *first* + /// value. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{App, arg}; + /// let matches = App::new("myapp") + /// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20")) + /// .get_matches_from(&["test", "12"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: u32 = matches.value_of_t("length").unwrap_or_else(|e| e.exit()); + /// assert_eq!(len, 12); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.value_of_t("length").unwrap_or_else(|e| e.exit()); + /// // Something that expects u32 + /// let _: u32 = also_len; + /// ``` + /// + /// [`FromStr]: std::str::FromStr + /// [`ArgMatches::values_of_t`]: ArgMatches::values_of_t() + /// [`ErrorKind`]: crate::ErrorKind + pub fn value_of_t(&self, name: &str) -> Result + where + R: FromStr, + ::Err: Display, + { + 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_without_app(name.to_string(), v.to_string(), message.into()) + }) + } + + /// Parse the value (with [`FromStr`]) of a specific option or positional argument. + /// + /// If either the value is not present or parsing failed, exits the program. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{App, arg}; + /// let matches = App::new("myapp") + /// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20")) + /// .get_matches_from(&["test", "12"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: u32 = matches.value_of_t_or_exit("length"); + /// assert_eq!(len, 12); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.value_of_t_or_exit("length"); + /// // Something that expects u32 + /// let _: u32 = also_len; + /// ``` + /// + /// [`FromStr][std::str::FromStr] + pub fn value_of_t_or_exit(&self, name: &str) -> R + where + R: FromStr, + ::Err: Display, + { + self.value_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Parse the values (with [`FromStr`]) of a specific option or positional argument. + /// + /// There are two types of errors, parse failures and those where the argument wasn't present + /// (such as a non-required argument). Check [`ErrorKind`] to distinguish them. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of_t`] as this method will only return the *first* + /// value. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{App, arg}; + /// let matches = App::new("myapp") + /// .arg(arg!([length] ... "A sequence of integers because integers are neat!")) + /// .get_matches_from(&["test", "12", "77", "40"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: Vec = matches.values_of_t("length").unwrap_or_else(|e| e.exit()); + /// assert_eq!(len, vec![12, 77, 40]); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.values_of_t("length").unwrap_or_else(|e| e.exit()); + /// // Something that expects Vec + /// let _: Vec = also_len; + /// ``` + /// [`ErrorKind`]: crate::ErrorKind + pub fn values_of_t(&self, name: &str) -> Result, Error> + where + R: FromStr, + ::Err: Display, + { + 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_without_app(name.to_string(), v.to_string(), message.into()) + }) + }) + .collect() + } + + /// Parse the values (with [`FromStr`]) of a specific option or positional argument. + /// + /// If parsing (of any value) has failed, exits the program. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{App, arg}; + /// let matches = App::new("myapp") + /// .arg(arg!([length] ... "A sequence of integers because integers are neat!")) + /// .get_matches_from(&["test", "12", "77", "40"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: Vec = matches.values_of_t_or_exit("length"); + /// assert_eq!(len, vec![12, 77, 40]); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.values_of_t_or_exit("length"); + /// // Something that expects Vec + /// let _: Vec = also_len; + /// ``` + pub fn values_of_t_or_exit(&self, name: &str) -> Vec + where + R: FromStr, + ::Err: Display, + { + self.values_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Check if an argument was present at runtime. + /// + /// *NOTE:* This will always return `true` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert!(m.is_present("debug")); + /// ``` + /// + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + 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) + } + + /// The number of times an argument was used at runtime. + /// + /// If an argument isn't present it will return `0`. + /// + /// **NOTE:** This returns the number of times the argument was used, *not* the number of + /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4 + /// values). See [Arg::multiple_occurrences][crate::Arg::multiple_occurrences]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d') + /// .multiple_occurrences(true)) + /// .get_matches_from(vec![ + /// "myprog", "-d", "-d", "-d" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// ``` + /// + /// This next example shows that counts actual uses of the argument, not just `-`'s + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d') + /// .multiple_occurrences(true)) + /// .arg(Arg::new("flag") + /// .short('f')) + /// .get_matches_from(vec![ + /// "myprog", "-ddfd" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + pub fn occurrences_of(&self, id: T) -> u64 { + self.get_arg(&Id::from(id)).map_or(0, |a| a.occurs) + } + + /// 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 name. + /// + /// # 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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::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::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_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() + 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 name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_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::{App, Arg}; + /// let m = App::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true) + /// .multiple_occurrences(true)) + /// .arg(Arg::new("flag") + /// .short('f') + /// .multiple_occurrences(true)) + /// .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::>(), &[3, 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::{App, Arg}; + /// let m = App::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() + 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) + } + + /// 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::{App, Arg, }; + /// let app_m = App::new("git") + /// .subcommand(App::new("clone")) + /// .subcommand(App::new("push")) + /// .subcommand(App::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::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let app_m = App::new("myprog") + /// .setting(AppSettings::AllowExternalSubcommands) + /// .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.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [subcommand]: crate::App::subcommand + #[inline] + pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> { + self.subcommand.as_ref().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::{App, Arg, }; + /// let app_m = App::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .subcommand(App::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.is_present("debug")); + /// + /// // 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.value_of("opt"), Some("val")); + /// } + /// ``` + /// + /// [subcommand]: crate::App::subcommand + /// [`App`]: crate::App + 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::{App, Arg, }; + /// let app_m = App::new("git") + /// .subcommand(App::new("clone")) + /// .subcommand(App::new("push")) + /// .subcommand(App::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::App::subcommand + /// [`App`]: crate::App + #[inline] + pub fn subcommand_name(&self) -> Option<&str> { + self.subcommand.as_ref().map(|sc| &*sc.name) + } + + /// Check if an arg 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_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 + } + } + + /// 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 + } + } +} + +// Private methods +impl ArgMatches { + #[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 a name 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, +} + +// 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 + +/// Iterate over multiple values for an argument via [`ArgMatches::values_of`]. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{App, Arg}; +/// let m = App::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .multiple_occurrences(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); +/// +/// let mut values = m.values_of("output").unwrap(); +/// +/// assert_eq!(values.next(), Some("val1")); +/// assert_eq!(values.next(), Some("val2")); +/// assert_eq!(values.next(), None); +/// ``` +/// [`ArgMatches::values_of`]: ArgMatches::values_of() +#[derive(Clone)] +#[allow(missing_debug_implementations)] +pub struct Values<'a> { + #[allow(clippy::type_complexity)] + iter: Map>>, for<'r> fn(&'r OsString) -> &'r str>, + len: usize, +} + +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)) + } +} + +impl<'a> DoubleEndedIterator for Values<'a> { + fn next_back(&mut self) -> Option<&'a str> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Values<'a> {} + +/// Creates an empty iterator. +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 { + static EMPTY: [Vec; 0] = []; + GroupedValues { + iter: EMPTY[..].iter().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over multiple values for an argument via [`ArgMatches::values_of_os`]. +/// +/// # Examples +/// +#[cfg_attr(not(unix), doc = " ```ignore")] +#[cfg_attr(unix, doc = " ```")] +/// # use clap::{App, arg}; +/// use std::ffi::OsString; +/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; +/// +/// let m = App::new("utf8") +/// .arg(arg!( "some arg") +/// .allow_invalid_utf8(true)) +/// .get_matches_from(vec![OsString::from("myprog"), +/// // "Hi {0xe9}!" +/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); +/// ``` +/// [`ArgMatches::values_of_os`]: ArgMatches::values_of_os() +#[derive(Clone)] +#[allow(missing_debug_implementations)] +pub struct OsValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map>>, fn(&OsString) -> &OsStr>, + len: usize, +} + +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)) + } +} + +impl<'a> DoubleEndedIterator for OsValues<'a> { + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for OsValues<'a> {} + +/// Creates an empty iterator. +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::{App, Arg}; +/// let m = App::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)] +#[allow(missing_debug_implementations)] +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 assert_utf8_validation(arg: &MatchedArg, id: &Id) { + debug_assert!( + matches!(arg.is_invalid_utf8_allowed(), None | Some(false)), + "Must use `_os` lookups with `Arg::allow_invalid_utf8` at `{:?}`", + id + ); +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn assert_no_utf8_validation(arg: &MatchedArg, id: &Id) { + debug_assert!( + matches!(arg.is_invalid_utf8_allowed(), None | Some(true)), + "Must use `Arg::allow_invalid_utf8` with `_os` lookups at `{:?}`", + id + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default_values() { + let mut values: Values = Values::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_values_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut values = matches.values_of("").unwrap_or_default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues() { + let mut values: OsValues = OsValues::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut values = matches.values_of_os("").unwrap_or_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::App::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .values_of("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } + + #[test] + fn os_values_exact_size() { + let l = crate::App::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .allow_invalid_utf8(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .values_of_os("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } + + #[test] + fn indices_exact_size() { + let l = crate::App::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/third_party/rust/clap/src/parse/matches/matched_arg.rs b/third_party/rust/clap/src/parse/matches/matched_arg.rs new file mode 100644 index 000000000000..e453b1e18ef7 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/matched_arg.rs @@ -0,0 +1,349 @@ +// Std +use std::{ + ffi::{OsStr, OsString}, + iter::{Cloned, Flatten}, + slice::Iter, +}; + +use crate::util::eq_ignore_case; +use crate::INTERNAL_ERROR_MSG; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MatchedArg { + pub(crate) occurs: u64, + pub(crate) ty: ValueType, + indices: Vec, + vals: Vec>, + ignore_case: bool, + invalid_utf8_allowed: Option, +} + +impl MatchedArg { + pub(crate) fn new() -> Self { + MatchedArg { + occurs: 0, + ty: ValueType::Unknown, + indices: Vec::new(), + vals: Vec::new(), + ignore_case: false, + invalid_utf8_allowed: None, + } + } + + 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) + } + + pub(crate) fn vals(&self) -> Iter> { + self.vals.iter() + } + + pub(crate) fn vals_flatten(&self) -> Flatten>> { + self.vals.iter().flatten() + } + + pub(crate) fn first(&self) -> Option<&OsString> { + self.vals_flatten().next() + } + + pub(crate) fn push_val(&mut self, val: OsString) { + self.vals.push(vec![val]) + } + + pub(crate) fn new_val_group(&mut self) { + self.vals.push(vec![]) + } + + pub(crate) fn append_val(&mut self, val: OsString) { + // We assume there is always a group created before. + self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val) + } + + pub(crate) fn num_vals(&self) -> usize { + self.vals.iter().flatten().count() + } + + // 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 has_val_groups(&self) -> bool { + !self.vals.is_empty() + } + + // Will be used later + #[allow(dead_code)] + pub(crate) fn remove_vals(&mut self, len: usize) { + let mut want_remove = len; + let mut remove_group = None; + let mut remove_val = None; + for (i, g) in self.vals().enumerate() { + if g.len() <= want_remove { + want_remove -= g.len(); + remove_group = Some(i); + } else { + remove_val = Some(want_remove); + break; + } + } + if let Some(remove_group) = remove_group { + self.vals.drain(0..=remove_group); + } + if let Some(remove_val) = remove_val { + self.vals[0].drain(0..remove_val); + } + } + + pub(crate) fn contains_val(&self, val: &str) -> bool { + self.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 + v.to_str().map_or(false, |v| eq_ignore_case(v, val)) + } else { + OsString::as_os_str(v) == OsStr::new(val) + } + }) + } + + pub(crate) fn set_ty(&mut self, ty: ValueType) { + self.ty = ty; + } + + pub(crate) fn set_ignore_case(&mut self, yes: bool) { + self.ignore_case = yes; + } + + pub(crate) fn invalid_utf8_allowed(&mut self, yes: bool) { + self.invalid_utf8_allowed = Some(yes); + } + + pub(crate) fn is_invalid_utf8_allowed(&self) -> Option { + self.invalid_utf8_allowed + } +} + +impl Default for MatchedArg { + fn default() -> Self { + Self::new() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ValueType { + Unknown, + #[cfg(feature = "env")] + EnvVariable, + CommandLine, + DefaultValue, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_grouped_vals_first() { + let mut m = MatchedArg::new(); + m.new_val_group(); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + assert_eq!(m.first(), Some(&OsString::from("bbb"))); + } + + #[test] + fn test_grouped_vals_push_and_append() { + let mut m = MatchedArg::new(); + m.push_val("aaa".into()); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + m.new_val_group(); + m.append_val("ddd".into()); + m.push_val("eee".into()); + m.new_val_group(); + m.append_val("fff".into()); + m.append_val("ggg".into()); + m.append_val("hhh".into()); + m.append_val("iii".into()); + + let vals: Vec<&Vec> = m.vals().collect(); + assert_eq!( + vals, + vec![ + &vec![OsString::from("aaa")], + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ) + } + + #[test] + fn test_grouped_vals_removal() { + let m = { + let mut m = MatchedArg::new(); + m.push_val("aaa".into()); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + m.new_val_group(); + m.append_val("ddd".into()); + m.push_val("eee".into()); + m.new_val_group(); + m.append_val("fff".into()); + m.append_val("ggg".into()); + m.append_val("hhh".into()); + m.append_val("iii".into()); + m + }; + { + let mut m = m.clone(); + m.remove_vals(0); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("aaa")], + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(1); + let vals0 = m.vals().collect::>(); + assert_eq!( + vals0, + vec![ + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(2); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(3); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(4); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(5); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![&vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ]] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(7); + let vals1 = m.vals().collect::>(); + assert_eq!( + vals1, + vec![&vec![OsString::from("hhh"), OsString::from("iii"),]] + ); + } + + { + let mut m = m; + m.remove_vals(9); + assert_eq!(m.vals().next(), None); + } + } +} diff --git a/third_party/rust/clap/src/parse/matches/mod.rs b/third_party/rust/clap/src/parse/matches/mod.rs new file mode 100644 index 000000000000..6d6bd0d14353 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/mod.rs @@ -0,0 +1,9 @@ +mod arg_matches; +mod matched_arg; + +pub(crate) use self::{ + arg_matches::SubCommand, + matched_arg::{MatchedArg, ValueType}, +}; + +pub use self::arg_matches::{ArgMatches, Indices, OsValues, Values}; diff --git a/third_party/rust/clap/src/parse/mod.rs b/third_party/rust/clap/src/parse/mod.rs new file mode 100644 index 000000000000..f2f0d1fd034d --- /dev/null +++ b/third_party/rust/clap/src/parse/mod.rs @@ -0,0 +1,16 @@ +pub mod errors; +pub mod features; + +mod arg_matcher; +pub mod matches; +mod parser; +mod validator; + +pub(crate) use self::{ + arg_matcher::ArgMatcher, + matches::{MatchedArg, SubCommand, ValueType}, + parser::{Input, ParseState, Parser}, + validator::Validator, +}; + +pub use self::matches::{ArgMatches, Indices, OsValues, Values}; diff --git a/third_party/rust/clap/src/parse/parser.rs b/third_party/rust/clap/src/parse/parser.rs new file mode 100644 index 000000000000..7e4db3bad7c4 --- /dev/null +++ b/third_party/rust/clap/src/parse/parser.rs @@ -0,0 +1,1707 @@ +// Std +use std::{ + cell::{Cell, RefCell}, + ffi::{OsStr, OsString}, +}; + +// Third Party +use os_str_bytes::RawOsStr; + +// Internal +use crate::{ + build::AppSettings as AS, + build::{App, Arg, ArgSettings}, + mkeymap::KeyType, + output::{fmt::Colorizer, Help, HelpWriter, Usage}, + parse::errors::Error as ClapError, + parse::errors::ErrorKind, + parse::errors::Result as ClapResult, + parse::features::suggestions, + parse::{ArgMatcher, SubCommand}, + parse::{Validator, ValueType}, + util::{color::ColorChoice, ChildGraph, Id}, + INTERNAL_ERROR_MSG, INVALID_UTF8, +}; + +pub(crate) struct Parser<'help, 'app> { + pub(crate) app: &'app mut App<'help>, + pub(crate) required: ChildGraph, + pub(crate) overridden: RefCell>, + pub(crate) seen: Vec, + pub(crate) cur_idx: Cell, + /// Index of the previous flag subcommand in a group of flags. + pub(crate) flag_subcmd_at: Option, + /// Counter indicating the number of items to skip + /// when revisiting the group of flags which includes the flag subcommand. + pub(crate) flag_subcmd_skip: usize, +} + +// Initializing Methods +impl<'help, 'app> Parser<'help, 'app> { + pub(crate) fn new(app: &'app mut App<'help>) -> Self { + let mut reqs = ChildGraph::with_capacity(5); + for a in app + .args + .args() + .filter(|a| a.settings.is_set(ArgSettings::Required)) + { + reqs.insert(a.id.clone()); + } + + Parser { + app, + required: reqs, + overridden: Default::default(), + seen: Vec::new(), + cur_idx: Cell::new(0), + flag_subcmd_at: None, + flag_subcmd_skip: 0, + } + } + + // Does all the initializing and prepares the parser + pub(crate) fn _build(&mut self) { + debug!("Parser::_build"); + + for group in &self.app.groups { + if group.required { + let idx = self.required.insert(group.id.clone()); + for a in &group.requires { + self.required.insert_child(idx, a.clone()); + } + } + } + } + + // Should we color the help? + pub(crate) fn color_help(&self) -> ColorChoice { + #[cfg(feature = "color")] + if self.is_set(AS::DisableColoredHelp) { + return ColorChoice::Never; + } + + self.app.get_color() + } +} + +// Parsing Methods +impl<'help, 'app> Parser<'help, 'app> { + // The actual parsing function + #[allow(clippy::cognitive_complexity)] + pub(crate) fn get_matches_with( + &mut self, + matcher: &mut ArgMatcher, + it: &mut Input, + ) -> ClapResult<()> { + debug!("Parser::get_matches_with"); + // Verify all positional assertions pass + self._build(); + + 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.app.args.keys().filter(|x| x.is_position()).count(); + // If any arg sets .last(true) + let contains_last = self.app.args.args().any(|x| x.is_set(ArgSettings::Last)); + + while let Some((arg_os, remaining_args)) = it.next() { + // Recover the replaced items if any. + if let Some((_replacer, replaced_items)) = self + .app + .replacers + .iter() + .find(|(key, _)| OsStr::new(key) == arg_os) + { + it.insert(replaced_items); + debug!( + "Parser::get_matches_with: found replacer: {:?}, target: {:?}", + _replacer, replaced_items + ); + continue; + } + + let arg_os = RawOsStr::new(arg_os); + debug!( + "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", + arg_os, + arg_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 + .app + .get_positionals() + .any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0))) + && self + .app + .get_positionals() + .last() + .map_or(false, |p_name| !p_name.is_set(ArgSettings::Last)); + + let missing_pos = self.is_set(AS::AllowMissingPositional) + && 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) = remaining_args.get(0) { + if let Some(p) = self + .app + .get_positionals() + .find(|p| p.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. + let n = RawOsStr::new(n); + self.is_new_arg(&n, p) + || self.possible_subcommand(&n, 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.is_set(AS::AllowMissingPositional) || 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.is_set(AS::SubcommandPrecedenceOverArg) + || !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, valid_arg_found); + debug!("Parser::get_matches_with: sc={:?}", sc_name); + if let Some(sc_name) = sc_name { + if sc_name == "help" + && !self.is_set(AS::NoAutoHelp) + && !self.is_set(AS::DisableHelpSubcommand) + { + self.parse_help_subcommand(remaining_args)?; + } + subcmd_name = Some(sc_name.to_owned()); + break; + } + } + + if let Some(long_arg) = arg_os.strip_prefix("--") { + let parse_result = self.parse_long_arg( + matcher, + long_arg, + &parse_state, + &mut valid_arg_found, + trailing_values, + ); + debug!( + "Parser::get_matches_with: After parse_long_arg {:?}", + parse_result + ); + match parse_result { + ParseResult::NoArg => { + debug!("Parser::get_matches_with: setting TrailingVals=true"); + trailing_values = true; + continue; + } + 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 } => { + return Err(ClapError::no_equals( + self.app, + arg, + Usage::new(self).create_usage_with_title(&[]), + )); + } + ParseResult::NoMatchingArg { arg } => { + let remaining_args: Vec<_> = remaining_args + .iter() + .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 } => { + return Err(ClapError::too_many_values( + self.app, + rest, + arg, + Usage::new(self).create_usage_no_title(&used), + )) + } + ParseResult::HelpFlag => { + return Err(self.help_err(true)); + } + ParseResult::VersionFlag => { + return Err(self.version_err(true)); + } + ParseResult::MaybeHyphenValue => { + // Maybe a hyphen value, do nothing. + } + ParseResult::AttachedValueNotConsumed => { + unreachable!() + } + } + } else if let Some(short_arg) = arg_os.strip_prefix("-") { + // Arg looks like a short flag, and not a possible number + + // Try to parse short args like normal, if AllowHyphenValues 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| { + it.cursor -= 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 } => { + return Err(ClapError::no_equals( + self.app, + arg, + Usage::new(self).create_usage_with_title(&[]), + )) + } + ParseResult::NoMatchingArg { arg } => { + return Err(ClapError::unknown_argument( + self.app, + arg, + None, + Usage::new(self).create_usage_with_title(&[]), + )); + } + ParseResult::HelpFlag => { + return Err(self.help_err(false)); + } + ParseResult::VersionFlag => { + return Err(self.version_err(false)); + } + 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 parse_result = self.add_val_to_arg( + &self.app[id], + &arg_os, + matcher, + ValueType::CommandLine, + true, + trailing_values, + ); + 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(p) = self.app.args.get(&pos_counter) { + if p.is_set(ArgSettings::Last) && !trailing_values { + return Err(ClapError::unknown_argument( + self.app, + arg_os.to_str_lossy().into_owned(), + None, + Usage::new(self).create_usage_with_title(&[]), + )); + } + + if self.is_set(AS::TrailingVarArg) && pos_counter == positional_count { + trailing_values = true; + } + + self.seen.push(p.id.clone()); + // Increase occurrence no matter if we are appending, occurrences + // of positional argument equals to number of values rather than + // the number of value groups. + self.inc_occurrence_of_arg(matcher, p); + // Creating new value group rather than appending when the arg + // doesn't have any value. This behaviour is right because + // positional arguments are always present continuously. + let append = self.has_val_groups(matcher, p); + self.add_val_to_arg( + p, + &arg_os, + matcher, + ValueType::CommandLine, + append, + trailing_values, + ); + + // Only increment the positional counter if it doesn't allow multiples + if !p.is_multiple() { + pos_counter += 1; + parse_state = ParseState::ValuesDone; + } else { + parse_state = ParseState::Pos(p.id.clone()); + } + valid_arg_found = true; + } else if self.is_set(AS::AllowExternalSubcommands) { + // Get external subcommand name + let sc_name = match arg_os.to_str() { + Some(s) => s.to_string(), + None => { + return Err(ClapError::invalid_utf8( + self.app, + Usage::new(self).create_usage_with_title(&[]), + )); + } + }; + + // Collect the external subcommand args + let mut sc_m = ArgMatcher::new(self.app); + + while let Some((v, _)) = it.next() { + let allow_invalid_utf8 = + self.is_set(AS::AllowInvalidUtf8ForExternalSubcommands); + if !allow_invalid_utf8 && v.to_str().is_none() { + return Err(ClapError::invalid_utf8( + self.app, + Usage::new(self).create_usage_with_title(&[]), + )); + } + sc_m.add_val_to( + &Id::empty_hash(), + v.to_os_string(), + ValueType::CommandLine, + false, + ); + sc_m.get_mut(&Id::empty_hash()) + .expect("just inserted") + .invalid_utf8_allowed(allow_invalid_utf8); + } + + matcher.subcommand(SubCommand { + name: sc_name.clone(), + id: sc_name.into(), + matches: sc_m.into_inner(), + }); + + return Validator::new(self).validate( + parse_state, + subcmd_name.is_some(), + matcher, + trailing_values, + ); + } else { + // Start error processing + 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 + .app + .find_subcommand(pos_sc_name) + .expect(INTERNAL_ERROR_MSG) + .name + .clone(); + self.parse_subcommand(&sc_name, matcher, it, keep_state)?; + } else if self.is_set(AS::SubcommandRequired) { + let bn = self.app.bin_name.as_ref().unwrap_or(&self.app.name); + return Err(ClapError::missing_subcommand( + self.app, + bn.to_string(), + Usage::new(self).create_usage_with_title(&[]), + )); + } else if self.is_set(AS::SubcommandRequiredElseHelp) { + debug!("Parser::get_matches_with: SubcommandRequiredElseHelp=true"); + let message = self.write_help_err()?; + return Err(ClapError::new( + message, + ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, + self.app.settings.is_set(AS::WaitOnError), + )); + } + + Validator::new(self).validate(parse_state, subcmd_name.is_some(), matcher, trailing_values) + } + + fn match_arg_error( + &self, + arg_os: &RawOsStr, + 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, valid_arg_found).is_some() { + return ClapError::unnecessary_double_dash( + self.app, + arg_os.to_str_lossy().into_owned(), + Usage::new(self).create_usage_with_title(&[]), + ); + } + } + let candidates = + suggestions::did_you_mean(&arg_os.to_str_lossy(), self.app.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.app, + arg_os.to_str_lossy().into_owned(), + candidates.join(" or "), + self.app + .bin_name + .as_ref() + .unwrap_or(&self.app.name) + .to_string(), + Usage::new(self).create_usage_with_title(&[]), + ); + } + // If the argument must be a subcommand. + if !self.app.has_args() || self.is_set(AS::InferSubcommands) && self.app.has_subcommands() { + return ClapError::unrecognized_subcommand( + self.app, + arg_os.to_str_lossy().into_owned(), + self.app + .bin_name + .as_ref() + .unwrap_or(&self.app.name) + .to_string(), + ); + } + ClapError::unknown_argument( + self.app, + arg_os.to_str_lossy().into_owned(), + None, + Usage::new(self).create_usage_with_title(&[]), + ) + } + + // Checks if the arg matches a subcommand name, or any of its aliases (if defined) + fn possible_subcommand(&self, arg_os: &RawOsStr, valid_arg_found: bool) -> Option<&str> { + debug!("Parser::possible_subcommand: arg={:?}", arg_os); + + if !(self.is_set(AS::ArgsNegateSubcommands) && valid_arg_found) { + if self.is_set(AS::InferSubcommands) { + // For subcommand `test`, we accepts it's prefix: `t`, `te`, + // `tes` and `test`. + let v = self + .app + .all_subcommand_names() + .filter(|s| RawOsStr::from_str(s).starts_with_os(arg_os)) + .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.app.find_subcommand(arg_os) { + return Some(&sc.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_os: &RawOsStr) -> Option<&str> { + debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg_os); + if self.is_set(AS::InferSubcommands) { + let options = self + .app + .get_subcommands() + .fold(Vec::new(), |mut options, sc| { + if let Some(long) = sc.long_flag { + if RawOsStr::from_str(long).starts_with_os(arg_os) { + options.push(long); + } + options.extend( + sc.get_all_aliases() + .filter(|alias| RawOsStr::from_str(alias).starts_with_os(arg_os)), + ) + } + options + }); + if options.len() == 1 { + return Some(options[0]); + } + + for sc in options { + if sc == arg_os { + return Some(sc); + } + } + } else if let Some(sc_name) = self.app.find_long_subcmd(arg_os) { + return Some(sc_name); + } + None + } + + fn parse_help_subcommand(&self, cmds: &[OsString]) -> ClapResult { + debug!("Parser::parse_help_subcommand"); + + let mut bin_name = self.app.bin_name.as_ref().unwrap_or(&self.app.name).clone(); + + let mut sc = { + let mut sc = self.app.clone(); + + for cmd in cmds.iter() { + sc = if let Some(c) = sc.find_subcommand(cmd) { + c + } else if let Some(c) = sc.find_subcommand(&cmd.to_string_lossy()) { + c + } else { + return Err(ClapError::unrecognized_subcommand( + self.app, + cmd.to_string_lossy().into_owned(), + self.app + .bin_name + .as_ref() + .unwrap_or(&self.app.name) + .to_string(), + )); + } + .clone(); + + sc._build(); + bin_name.push(' '); + bin_name.push_str(&sc.name); + } + + sc + }; + sc = sc.bin_name(bin_name); + + let parser = Parser::new(&mut sc); + + Err(parser.help_err(self.app.is_set(AS::UseLongFormatForHelpSubcommand))) + } + + fn is_new_arg(&self, next: &RawOsStr, current_positional: &Arg) -> bool { + debug!( + "Parser::is_new_arg: {:?}:{:?}", + next, current_positional.name + ); + + if self.is_set(AS::AllowHyphenValues) + || self.app[¤t_positional.id].is_set(ArgSettings::AllowHyphenValues) + || (self.is_set(AS::AllowNegativeNumbers) && next.to_str_lossy().parse::().is_ok()) + { + // If allow hyphen, this isn't a new arg. + debug!("Parser::is_new_arg: Allow hyphen"); + false + } else if next.starts_with("--") { + // If this is a long flag, this is a new arg. + debug!("Parser::is_new_arg: -- found"); + true + } else if next.starts_with("-") { + debug!("Parser::is_new_arg: - found"); + // 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. + next.raw_len() != 1 + } else { + debug!("Parser::is_new_arg: value"); + // Nothing special, this is a value. + false + } + } + + fn parse_subcommand( + &mut self, + sc_name: &str, + matcher: &mut ArgMatcher, + it: &mut Input, + keep_state: bool, + ) -> ClapResult<()> { + debug!("Parser::parse_subcommand"); + + let mut mid_string = String::from(" "); + + if !self.is_set(AS::SubcommandsNegateReqs) { + 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 partial_parsing_enabled = self.is_set(AS::IgnoreErrors); + + if let Some(sc) = self.app.subcommands.iter_mut().find(|s| s.name == sc_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 { + sc_names.push_str(&format!(", --{}", l)); + flag_subcmd = true; + } + if let Some(s) = sc.short_flag { + sc_names.push_str(&format!(", -{}", s)); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + sc.usage = Some( + self.app + .bin_name + .as_ref() + .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) + .unwrap_or(sc_names), + ); + + // bin_name should be parent's bin_name + [] + the sc's name separated by + // a space + sc.bin_name = Some(format!( + "{}{}{}", + self.app.bin_name.as_ref().unwrap_or(&String::new()), + if self.app.bin_name.is_some() { " " } else { "" }, + &*sc.name + )); + + // Ensure all args are built and ready to parse + sc._build(); + + let mut sc_matcher = ArgMatcher::new(sc); + + debug!("Parser::parse_subcommand: About to parse sc={}", sc.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, it) { + if partial_parsing_enabled { + debug!( + "Parser::parse_subcommand: ignored error in subcommand {}: {:?}", + sc_name, error + ); + } else { + return Err(error); + } + } + } + matcher.subcommand(SubCommand { + id: sc.id.clone(), + name: sc.name.clone(), + matches: sc_matcher.into_inner(), + }); + } + Ok(()) + } + + // Retrieves the names of all args the user has supplied thus far, except required ones + // because those will be listed in self.required + fn check_for_help_and_version_str(&self, arg: &RawOsStr) -> Option { + debug!("Parser::check_for_help_and_version_str"); + debug!( + "Parser::check_for_help_and_version_str: Checking if --{:?} is help or version...", + arg + ); + + if let Some(help) = self.app.find(&Id::help_hash()) { + if let Some(h) = help.long { + if arg == h && !self.is_set(AS::NoAutoHelp) && !self.is_set(AS::DisableHelpFlag) { + debug!("Help"); + return Some(ParseResult::HelpFlag); + } + } + } + + if let Some(version) = self.app.find(&Id::version_hash()) { + if let Some(v) = version.long { + if arg == v + && !self.is_set(AS::NoAutoVersion) + && !self.is_set(AS::DisableVersionFlag) + { + debug!("Version"); + return Some(ParseResult::VersionFlag); + } + } + } + + debug!("Neither"); + None + } + + fn check_for_help_and_version_char(&self, arg: char) -> Option { + debug!("Parser::check_for_help_and_version_char"); + debug!( + "Parser::check_for_help_and_version_char: Checking if -{} is help or version...", + arg + ); + + if let Some(help) = self.app.find(&Id::help_hash()) { + if let Some(h) = help.short { + if arg == h && !self.is_set(AS::NoAutoHelp) && !self.is_set(AS::DisableHelpFlag) { + debug!("Help"); + return Some(ParseResult::HelpFlag); + } + } + } + + if let Some(version) = self.app.find(&Id::version_hash()) { + if let Some(v) = version.short { + if arg == v + && !self.is_set(AS::NoAutoVersion) + && !self.is_set(AS::DisableVersionFlag) + { + debug!("Version"); + return Some(ParseResult::VersionFlag); + } + } + } + + debug!("Neither"); + None + } + + fn use_long_help(&self) -> bool { + debug!("Parser::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 HiddenShortHelp 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_set(ArgSettings::HiddenLongHelp) + || v.is_set(ArgSettings::HiddenShortHelp) + }; + + // Subcommands aren't checked because we prefer short help for them, deferring to + // `cmd subcmd --help` for more. + self.app.long_about.is_some() + || self.app.before_long_help.is_some() + || self.app.after_long_help.is_some() + || self.app.args.args().any(should_long) + } + + fn parse_long_arg( + &mut self, + matcher: &mut ArgMatcher, + long_arg: &RawOsStr, + parse_state: &ParseState, + valid_arg_found: &mut bool, + trailing_values: bool, + ) -> ParseResult { + // maybe here lifetime should be 'a + debug!("Parser::parse_long_arg"); + + if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if + self.app[opt].is_set(ArgSettings::AllowHyphenValues)) + { + return ParseResult::MaybeHyphenValue; + } + + // Update the current index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::parse_long_arg: cur_idx:={}", self.cur_idx.get()); + + debug!("Parser::parse_long_arg: Does it contain '='..."); + if long_arg.is_empty() { + return ParseResult::NoArg; + } + let (arg, val) = if let Some(index) = long_arg.find("=") { + let (p0, p1) = long_arg.split_at(index); + debug!("Yes '{:?}'", p1); + (p0, Some(p1)) + } else { + debug!("No"); + (long_arg, None) + }; + + let opt = if let Some(opt) = self.app.args.get(&*arg.to_os_str()) { + debug!( + "Parser::parse_long_arg: Found valid opt or flag '{}'", + opt.to_string() + ); + Some(opt) + } else if self.is_set(AS::InferLongArgs) { + let arg_str = arg.to_str_lossy(); + self.app.args.args().find(|a| { + a.long.map_or(false, |long| long.starts_with(&*arg_str)) + || a.aliases + .iter() + .any(|(alias, _)| alias.starts_with(&*arg_str)) + }) + } else { + None + }; + + if let Some(opt) = opt { + *valid_arg_found = true; + self.seen.push(opt.id.clone()); + if opt.is_set(ArgSettings::TakesValue) { + debug!( + "Parser::parse_long_arg: Found an opt with value '{:?}'", + &val + ); + self.parse_opt(val, opt, matcher, trailing_values) + } else if let Some(rest) = val { + debug!("Parser::parse_long_arg: Got invalid literal `{:?}`", rest); + let used: Vec = matcher + .arg_names() + .filter(|&n| { + self.app.find(n).map_or(true, |a| { + !(a.is_set(ArgSettings::Hidden) || self.required.contains(&a.id)) + }) + }) + .cloned() + .collect(); + + ParseResult::UnneededAttachedValue { + rest: rest.to_str_lossy().into_owned(), + used, + arg: opt.to_string(), + } + } else if let Some(parse_result) = self.check_for_help_and_version_str(arg) { + parse_result + } else { + debug!("Parser::parse_long_arg: Presence validated"); + self.parse_flag(opt, matcher) + } + } else if let Some(sc_name) = self.possible_long_flag_subcommand(arg) { + ParseResult::FlagSubCommand(sc_name.to_string()) + } else if self.is_set(AS::AllowHyphenValues) { + ParseResult::MaybeHyphenValue + } else { + ParseResult::NoMatchingArg { + arg: arg.to_str_lossy().into_owned(), + } + } + } + + fn parse_short_arg( + &mut self, + matcher: &mut ArgMatcher, + short_arg: &RawOsStr, + 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, + ) -> ParseResult { + debug!("Parser::parse_short_arg: short_arg={:?}", short_arg); + let arg = short_arg.to_str_lossy(); + + #[allow(clippy::blocks_in_if_conditions)] + if self.is_set(AS::AllowNegativeNumbers) && arg.parse::().is_ok() { + debug!("Parser::parse_short_arg: negative number"); + return ParseResult::MaybeHyphenValue; + } else if self.is_set(AS::AllowHyphenValues) + && arg.chars().any(|c| !self.app.contains_short(c)) + { + debug!("Parser::parse_short_args: contains non-short flag"); + return ParseResult::MaybeHyphenValue; + } else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) + if self.app[opt].is_set(ArgSettings::AllowHyphenValues)) + { + debug!("Parser::parse_short_args: prior arg accepts hyphenated values",); + return ParseResult::MaybeHyphenValue; + } else if self.app.args.get(&pos_counter).map_or(false, |arg| { + arg.is_set(ArgSettings::AllowHyphenValues) && !arg.is_set(ArgSettings::Last) + }) { + debug!( + "Parser::parse_short_args: positional at {} allows hyphens", + pos_counter + ); + return ParseResult::MaybeHyphenValue; + } + + let mut ret = ParseResult::NoArg; + + let skip = self.flag_subcmd_skip; + self.flag_subcmd_skip = 0; + for c in arg.chars().skip(skip) { + debug!("Parser::parse_short_arg:iter:{}", c); + + // update each index because `-abcd` is four indices to clap + self.cur_idx.set(self.cur_idx.get() + 1); + debug!( + "Parser::parse_short_arg:iter:{}: cur_idx:={}", + c, + self.cur_idx.get() + ); + + // Check for matching short options, and return the name if there is no trailing + // concatenated value: -oval + // Option: -o + // Value: val + if let Some(opt) = self.app.args.get(&c) { + debug!( + "Parser::parse_short_arg:iter:{}: Found valid opt or flag", + c + ); + *valid_arg_found = true; + self.seen.push(opt.id.clone()); + if !opt.is_set(ArgSettings::TakesValue) { + if let Some(parse_result) = self.check_for_help_and_version_char(c) { + return parse_result; + } + ret = self.parse_flag(opt, matcher); + continue; + } + + // Check for trailing concatenated value + let val = short_arg.split_once(c).expect(INTERNAL_ERROR_MSG).1; + 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 RequireEquals && x.min_vals == 0, we don't + // consume the `vf`, even if it's provided as value. + match self.parse_opt(val, opt, matcher, trailing_values) { + ParseResult::AttachedValueNotConsumed => continue, + x => return x, + } + } + + return if let Some(sc_name) = self.app.find_short_subcmd(c) { + debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name); + let name = sc_name.to_string(); + let done_short_args = { + let cur_idx = self.cur_idx.get(); + // 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 at = *self.flag_subcmd_at.get_or_insert(cur_idx); + // If we are done, then the difference of indices (cur_idx - at) should be (end - at) which + // should equal to (arg.len() - 1), + // where `end` is the index of the end of the group. + cur_idx - at == arg.len() - 1 + }; + if done_short_args { + self.flag_subcmd_at = None; + } + ParseResult::FlagSubCommand(name) + } else { + ParseResult::NoMatchingArg { + arg: format!("-{}", c), + } + }; + } + ret + } + + fn parse_opt( + &self, + attached_value: Option<&RawOsStr>, + opt: &Arg<'help>, + matcher: &mut ArgMatcher, + trailing_values: bool, + ) -> ParseResult { + debug!( + "Parser::parse_opt; opt={}, val={:?}", + opt.name, attached_value + ); + debug!("Parser::parse_opt; opt.settings={:?}", opt.settings); + // has_eq: --flag=value + let has_eq = matches!(attached_value, Some(fv) if fv.starts_with("=")); + + debug!("Parser::parse_opt; Checking for val..."); + // RequireEquals is set, but no '=' is provided, try throwing error. + if opt.is_set(ArgSettings::RequireEquals) && !has_eq { + if opt.min_vals == Some(0) { + debug!("Requires equals, but min_vals == 0"); + self.inc_occurrence_of_arg(matcher, opt); + // We assume this case is valid: require equals, but min_vals == 0. + if !opt.default_missing_vals.is_empty() { + debug!("Parser::parse_opt: has default_missing_vals"); + self.add_multiple_vals_to_arg( + opt, + opt.default_missing_vals.iter().map(OsString::from), + matcher, + ValueType::CommandLine, + false, + ); + }; + if attached_value.is_some() { + ParseResult::AttachedValueNotConsumed + } else { + ParseResult::ValuesDone + } + } else { + debug!("Requires equals but not provided. Error."); + ParseResult::EqualsNotProvided { + arg: opt.to_string(), + } + } + } else if let Some(fv) = attached_value { + let v = fv.strip_prefix("=").unwrap_or(fv); + debug!("Found - {:?}, len: {}", v, v.raw_len()); + debug!( + "Parser::parse_opt: {:?} contains '='...{:?}", + fv, + fv.starts_with("=") + ); + self.inc_occurrence_of_arg(matcher, opt); + self.add_val_to_arg( + opt, + v, + matcher, + ValueType::CommandLine, + false, + trailing_values, + ); + ParseResult::ValuesDone + } else { + debug!("Parser::parse_opt: More arg vals required..."); + self.inc_occurrence_of_arg(matcher, opt); + matcher.new_val_group(&opt.id); + for group in self.app.groups_for_arg(&opt.id) { + matcher.new_val_group(&group); + } + ParseResult::Opt(opt.id.clone()) + } + } + + fn add_val_to_arg( + &self, + arg: &Arg<'help>, + val: &RawOsStr, + matcher: &mut ArgMatcher, + ty: ValueType, + append: bool, + trailing_values: bool, + ) -> ParseResult { + debug!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name, val); + debug!( + "Parser::add_val_to_arg; trailing_values={:?}, DontDelimTrailingVals={:?}", + trailing_values, + self.is_set(AS::DontDelimitTrailingValues) + ); + if !(trailing_values && self.is_set(AS::DontDelimitTrailingValues)) { + if let Some(delim) = arg.val_delim { + let arg_split = val.split(delim); + let vals = if let Some(t) = arg.terminator { + let mut vals = vec![]; + for val in arg_split { + if t == val { + break; + } + vals.push(val); + } + vals + } else { + arg_split.collect() + }; + self.add_multiple_vals_to_arg( + arg, + vals.into_iter().map(|x| x.to_os_str().into_owned()), + matcher, + ty, + append, + ); + // If there was a delimiter used or we must use the delimiter to + // separate the values or no more vals is needed, we're not + // looking for more values. + return if val.contains(delim) + || arg.is_set(ArgSettings::RequireDelimiter) + || !matcher.needs_more_vals(arg) + { + ParseResult::ValuesDone + } else { + ParseResult::Opt(arg.id.clone()) + }; + } + } + if let Some(t) = arg.terminator { + if t == val { + return ParseResult::ValuesDone; + } + } + self.add_single_val_to_arg(arg, val.to_os_str().into_owned(), matcher, ty, append); + if matcher.needs_more_vals(arg) { + ParseResult::Opt(arg.id.clone()) + } else { + ParseResult::ValuesDone + } + } + + fn add_multiple_vals_to_arg( + &self, + arg: &Arg<'help>, + vals: impl Iterator, + matcher: &mut ArgMatcher, + ty: ValueType, + append: bool, + ) { + // If not appending, create a new val group and then append vals in. + if !append { + matcher.new_val_group(&arg.id); + for group in self.app.groups_for_arg(&arg.id) { + matcher.new_val_group(&group); + } + } + for val in vals { + self.add_single_val_to_arg(arg, val, matcher, ty, true); + } + } + + fn add_single_val_to_arg( + &self, + arg: &Arg<'help>, + val: OsString, + matcher: &mut ArgMatcher, + ty: ValueType, + append: bool, + ) { + debug!("Parser::add_single_val_to_arg: adding val...{:?}", val); + + // 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() + ); + + // Increment or create the group "args" + for group in self.app.groups_for_arg(&arg.id) { + matcher.add_val_to(&group, val.clone(), ty, append); + } + + matcher.add_val_to(&arg.id, val, ty, append); + matcher.add_index_to(&arg.id, self.cur_idx.get(), ty); + } + + fn has_val_groups(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) -> bool { + matcher.has_val_groups(&arg.id) + } + + fn parse_flag(&self, flag: &Arg<'help>, matcher: &mut ArgMatcher) -> ParseResult { + debug!("Parser::parse_flag"); + + self.inc_occurrence_of_arg(matcher, flag); + matcher.add_index_to(&flag.id, self.cur_idx.get(), ValueType::CommandLine); + + ParseResult::ValuesDone + } + + 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); + self.overridden.borrow_mut().push(override_id.clone()); + } + + // Override anything that can override us + let mut transitive = Vec::new(); + for arg_id in matcher.arg_names() { + if let Some(overrider) = self.app.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); + self.overridden.borrow_mut().push(overrider_id.clone()); + } + } + + pub(crate) fn add_defaults(&mut self, matcher: &mut ArgMatcher, trailing_values: bool) { + debug!("Parser::add_defaults"); + + for o in self.app.get_opts() { + debug!("Parser::add_defaults:iter:{}:", o.name); + self.add_value(o, matcher, ValueType::DefaultValue, trailing_values); + } + + for p in self.app.get_positionals() { + debug!("Parser::add_defaults:iter:{}:", p.name); + self.add_value(p, matcher, ValueType::DefaultValue, trailing_values); + } + } + + fn add_value( + &self, + arg: &Arg<'help>, + matcher: &mut ArgMatcher, + ty: ValueType, + trailing_values: bool, + ) { + if !arg.default_vals_ifs.is_empty() { + debug!("Parser::add_value: has conditional defaults"); + if matcher.get(&arg.id).is_none() { + for (id, val, default) in arg.default_vals_ifs.iter() { + let add = if let Some(a) = matcher.get(id) { + if let Some(v) = val { + a.vals_flatten().any(|value| v == value) + } else { + true + } + } else { + false + }; + + if add { + if let Some(default) = default { + self.add_val_to_arg( + arg, + &RawOsStr::new(default), + matcher, + ty, + false, + trailing_values, + ); + } + return; + } + } + } + } else { + debug!("Parser::add_value: doesn't have conditional defaults"); + } + + fn process_default_vals(arg: &Arg<'_>, default_vals: &[&OsStr]) -> Vec { + if let Some(delim) = arg.val_delim { + let mut vals = vec![]; + for val in default_vals { + let val = RawOsStr::new(val); + for val in val.split(delim) { + vals.push(val.to_os_str().into_owned()); + } + } + vals + } else { + default_vals.iter().map(OsString::from).collect() + } + } + + if !arg.default_vals.is_empty() { + debug!("Parser::add_value:iter:{}: has default vals", arg.name); + if matcher.get(&arg.id).is_some() { + debug!("Parser::add_value:iter:{}: was used", arg.name); + // do nothing + } else { + debug!("Parser::add_value:iter:{}: wasn't used", arg.name); + + self.add_multiple_vals_to_arg( + arg, + process_default_vals(arg, &arg.default_vals).into_iter(), + matcher, + ty, + false, + ); + } + } else { + debug!( + "Parser::add_value:iter:{}: doesn't have default vals", + arg.name + ); + + // do nothing + } + + if !arg.default_missing_vals.is_empty() { + debug!( + "Parser::add_value:iter:{}: has default missing vals", + arg.name + ); + match matcher.get(&arg.id) { + Some(ma) if ma.all_val_groups_empty() => { + debug!( + "Parser::add_value:iter:{}: has no user defined vals", + arg.name + ); + self.add_multiple_vals_to_arg( + arg, + process_default_vals(arg, &arg.default_missing_vals).into_iter(), + matcher, + ty, + false, + ); + } + None => { + debug!("Parser::add_value:iter:{}: wasn't used", arg.name); + // do nothing + } + _ => { + debug!("Parser::add_value:iter:{}: has user defined vals", arg.name); + // do nothing + } + } + } else { + debug!( + "Parser::add_value:iter:{}: doesn't have default missing vals", + arg.name + ); + + // do nothing + } + } + + #[cfg(feature = "env")] + pub(crate) fn add_env( + &mut self, + matcher: &mut ArgMatcher, + trailing_values: bool, + ) -> ClapResult<()> { + use crate::util::str_to_bool; + + self.app.args.args().try_for_each(|a| { + // Use env only if the arg was absent among command line args, + // early return if this is not the case. + if matcher.get(&a.id).map_or(false, |a| a.occurs != 0) { + debug!("Parser::add_env: Skipping existing arg `{}`", a); + return Ok(()); + } + + debug!("Parser::add_env: Checking arg `{}`", a); + if let Some((_, Some(ref val))) = a.env { + let val = RawOsStr::new(val); + + if a.is_set(ArgSettings::TakesValue) { + debug!( + "Parser::add_env: Found an opt with value={:?}, trailing={:?}", + val, trailing_values + ); + self.add_val_to_arg( + a, + &val, + matcher, + ValueType::EnvVariable, + false, + trailing_values, + ); + return Ok(()); + } + + debug!("Parser::add_env: Checking for help and version"); + // Early return on `HelpFlag` or `VersionFlag`. + match self.check_for_help_and_version_str(&val) { + Some(ParseResult::HelpFlag) => { + return Err(self.help_err(true)); + } + Some(ParseResult::VersionFlag) => { + return Err(self.version_err(true)); + } + _ => (), + } + + 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 { + matcher.add_index_to(&a.id, self.cur_idx.get(), ValueType::EnvVariable); + } + } + + Ok(()) + }) + } + + /// Increase occurrence of specific argument and the grouped arg it's in. + fn inc_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.inc_occurrence_of_arg(arg); + // Increment or create the group "args" + for group in self.app.groups_for_arg(&arg.id) { + matcher.inc_occurrence_of_group(&group); + } + } +} + +// Error, Help, and Version Methods +impl<'help, 'app> Parser<'help, 'app> { + /// 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 + .app + .args + .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.app.subcommands.as_mut_slice(), + ); + + // Add the arg to the matches to build a proper usage string + if let Some((name, _)) = did_you_mean.as_ref() { + if let Some(opt) = self.app.args.get(&name.as_ref()) { + self.inc_occurrence_of_arg(matcher, opt); + } + } + + let used: Vec = matcher + .arg_names() + .filter(|n| { + self.app.find(n).map_or(true, |a| { + !(self.required.contains(&a.id) || a.is_set(ArgSettings::Hidden)) + }) + }) + .cloned() + .collect(); + + ClapError::unknown_argument( + self.app, + format!("--{}", arg), + did_you_mean, + Usage::new(self).create_usage_with_title(&*used), + ) + } + + pub(crate) fn write_help_err(&self) -> ClapResult { + let mut c = Colorizer::new(true, self.color_help()); + Help::new(HelpWriter::Buffer(&mut c), self, false).write_help()?; + Ok(c) + } + + fn help_err(&self, mut use_long: bool) -> ClapError { + debug!( + "Parser::help_err: use_long={:?}", + use_long && self.use_long_help() + ); + + use_long = use_long && self.use_long_help(); + let mut c = Colorizer::new(false, self.color_help()); + + match Help::new(HelpWriter::Buffer(&mut c), self, use_long).write_help() { + Err(e) => e.into(), + _ => ClapError::new( + c, + ErrorKind::DisplayHelp, + self.app.settings.is_set(AS::WaitOnError), + ), + } + } + + fn version_err(&self, use_long: bool) -> ClapError { + debug!("Parser::version_err"); + + let msg = self.app._render_version(use_long); + let mut c = Colorizer::new(false, self.color_help()); + c.none(msg); + ClapError::new( + c, + ErrorKind::DisplayVersion, + self.app.settings.is_set(AS::WaitOnError), + ) + } +} + +// Query Methods +impl<'help, 'app> Parser<'help, 'app> { + pub(crate) fn is_set(&self, s: AS) -> bool { + self.app.is_set(s) + } +} + +#[derive(Debug)] +pub(crate) struct Input { + items: Vec, + cursor: usize, +} + +impl From for Input +where + I: Iterator, + T: Into + Clone, +{ + fn from(val: I) -> Self { + Self { + items: val.map(|x| x.into()).collect(), + cursor: 0, + } + } +} + +impl Input { + pub(crate) fn next(&mut self) -> Option<(&OsStr, &[OsString])> { + if self.cursor >= self.items.len() { + None + } else { + let current = &self.items[self.cursor]; + self.cursor += 1; + let remaining = &self.items[self.cursor..]; + Some((current, remaining)) + } + } + + /// Insert some items to the Input items just after current parsing cursor. + /// Usually used by replaced items recovering. + pub(crate) fn insert(&mut self, insert_items: &[&str]) { + self.items = insert_items + .iter() + .map(OsString::from) + .chain(self.items.drain(self.cursor..)) + .collect(); + self.cursor = 0; + } +} + +#[derive(Debug)] +pub(crate) enum ParseState { + ValuesDone, + Opt(Id), + Pos(Id), +} + +/// Recoverable Parsing results. +#[derive(Debug, PartialEq, Clone)] +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, + /// This is a Help flag. + HelpFlag, + /// This is a version flag. + VersionFlag, +} diff --git a/third_party/rust/clap/src/parse/validator.rs b/third_party/rust/clap/src/parse/validator.rs new file mode 100644 index 000000000000..7e92ab206fcd --- /dev/null +++ b/third_party/rust/clap/src/parse/validator.rs @@ -0,0 +1,610 @@ +// Internal +use crate::{ + build::{arg::PossibleValue, App, AppSettings as AS, Arg, ArgSettings}, + output::Usage, + parse::{ + errors::{Error, ErrorKind, Result as ClapResult}, + ArgMatcher, MatchedArg, ParseState, Parser, + }, + util::Id, + INTERNAL_ERROR_MSG, INVALID_UTF8, +}; + +pub(crate) struct Validator<'help, 'app, 'parser> { + p: &'parser mut Parser<'help, 'app>, +} + +impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> { + pub(crate) fn new(p: &'parser mut Parser<'help, 'app>) -> Self { + Validator { p } + } + + pub(crate) fn validate( + &mut self, + parse_state: ParseState, + is_subcmd: bool, + matcher: &mut ArgMatcher, + trailing_values: bool, + ) -> ClapResult<()> { + debug!("Validator::validate"); + let mut reqs_validated = false; + + #[cfg(feature = "env")] + self.p.add_env(matcher, trailing_values)?; + + self.p.add_defaults(matcher, trailing_values); + + if let ParseState::Opt(a) = parse_state { + debug!("Validator::validate: needs_val_of={:?}", a); + self.validate_required(matcher)?; + self.validate_required_unless(matcher)?; + + let o = &self.p.app[&a]; + reqs_validated = true; + let should_err = if let Some(v) = matcher.0.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.p.app, + o, + Usage::new(self.p).create_usage_with_title(&[]), + )); + } + } + + if matcher.is_empty() + && matcher.subcommand_name().is_none() + && self.p.is_set(AS::ArgRequiredElseHelp) + { + let message = self.p.write_help_err()?; + return Err(Error::new( + message, + ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, + self.p.is_set(AS::WaitOnError), + )); + } + self.validate_conflicts(matcher)?; + if !(self.p.is_set(AS::SubcommandsNegateReqs) && is_subcmd || reqs_validated) { + self.validate_required(matcher)?; + self.validate_required_unless(matcher)?; + } + self.validate_matched_args(matcher)?; + + Ok(()) + } + + fn validate_arg_values( + &self, + arg: &Arg, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> { + debug!("Validator::validate_arg_values: arg={:?}", arg.name); + for val in ma.vals_flatten() { + if !arg.is_set(ArgSettings::AllowInvalidUtf8) && val.to_str().is_none() { + debug!( + "Validator::validate_arg_values: invalid UTF-8 found in val {:?}", + val + ); + return Err(Error::invalid_utf8( + self.p.app, + Usage::new(self.p).create_usage_with_title(&[]), + )); + } + 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_set(ArgSettings::IgnoreCase))); + if !ok { + let used: Vec = matcher + .arg_names() + .filter(|&n| { + self.p.app.find(n).map_or(true, |a| { + !(a.is_set(ArgSettings::Hidden) || self.p.required.contains(&a.id)) + }) + }) + .cloned() + .collect(); + return Err(Error::invalid_value( + self.p.app, + val_str.into_owned(), + &arg.possible_vals + .iter() + .filter_map(PossibleValue::get_visible_name) + .collect::>(), + arg, + Usage::new(self.p).create_usage_with_title(&used), + )); + } + } + if arg.is_set(ArgSettings::ForbidEmptyValues) + && val.is_empty() + && matcher.contains(&arg.id) + { + debug!("Validator::validate_arg_values: illegal empty val found"); + return Err(Error::empty_value( + self.p.app, + arg, + Usage::new(self.p).create_usage_with_title(&[]), + )); + } + + 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( + self.p.app, + arg.to_string(), + val.to_string_lossy().into_owned(), + e, + )); + } 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( + self.p.app, + arg.to_string(), + val.to_string_lossy().into(), + e, + )); + } else { + debug!("good"); + } + } + } + Ok(()) + } + + fn validate_conflicts(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_conflicts"); + + self.validate_exclusive(matcher)?; + + let mut conflicts = Conflicts::new(); + for arg_id in matcher + .arg_names() + .filter(|arg_id| matcher.contains_explicit(arg_id) && self.p.app.find(arg_id).is_some()) + { + debug!("Validator::validate_conflicts::iter: id={:?}", arg_id); + let conflicts = conflicts.gather_conflicts(self.p.app, 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_names().count(); + matcher + .arg_names() + .filter_map(|name| { + debug!("Validator::validate_exclusive:iter:{:?}", name); + self.p + .app + .find(name) + // Find `arg`s which are exclusive but also appear with other args. + .filter(|&arg| arg.is_set(ArgSettings::Exclusive) && args_count > 1) + }) + // Throw an error for the first conflict found. + .try_for_each(|arg| { + Err(Error::argument_conflict( + self.p.app, + arg, + Vec::new(), + Usage::new(self.p).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.p.app.find_group(c_id).is_some() { + self.p.app.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.p.app.find(&c_id).expect(INTERNAL_ERROR_MSG); + c_arg.to_string() + }) + }) + .collect(); + + let former_arg = self.p.app.find(name).expect(INTERNAL_ERROR_MSG); + let usg = self.build_conflict_err_usage(matcher, conflict_ids); + Err(Error::argument_conflict( + self.p.app, former_arg, conflicts, usg, + )) + } + + fn build_conflict_err_usage(&self, matcher: &ArgMatcher, conflicting_keys: &[Id]) -> String { + let used_filtered: Vec = matcher + .arg_names() + .filter(|key| !conflicting_keys.contains(key)) + .cloned() + .collect(); + let required: Vec = used_filtered + .iter() + .filter_map(|key| self.p.app.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.p).create_usage_with_title(&required) + } + + fn gather_requirements(&mut self, matcher: &ArgMatcher) { + debug!("Validator::gather_requirements"); + for name in matcher.arg_names() { + debug!("Validator::gather_requirements:iter:{:?}", name); + if let Some(arg) = self.p.app.find(name) { + for req in self.p.app.unroll_requirements_for_arg(&arg.id, matcher) { + self.p.required.insert(req); + } + } else if let Some(g) = self.p.app.find_group(name) { + debug!("Validator::gather_requirements:iter:{:?}:group", name); + for r in &g.requires { + self.p.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.p.app.find(name) { + self.validate_arg_num_vals(arg, ma)?; + self.validate_arg_values(arg, ma, matcher)?; + self.validate_arg_num_occurs(arg, ma)?; + } + Ok(()) + }) + } + + fn validate_arg_num_occurs(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { + debug!( + "Validator::validate_arg_num_occurs: {:?}={}", + a.name, ma.occurs + ); + // Occurrence of positional argument equals to number of values rather + // than number of grouped values. + if ma.occurs > 1 && !a.is_set(ArgSettings::MultipleOccurrences) && !a.is_positional() { + // Not the first time, and we don't allow multiples + return Err(Error::unexpected_multiple_usage( + self.p.app, + a, + Usage::new(self.p).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.occurs as usize; + if occurs > max_occurs { + return Err(Error::too_many_occurrences( + self.p.app, + a, + max_occurs, + occurs, + Usage::new(self.p).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); + let should_err = if a.is_set(ArgSettings::MultipleOccurrences) { + 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.p.app, + a, + num, + if a.is_set(ArgSettings::MultipleOccurrences) { + total_num % num + } else { + total_num + }, + Usage::new(self.p).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.p.app, + ma.vals_flatten() + .last() + .expect(INTERNAL_ERROR_MSG) + .to_str() + .expect(INVALID_UTF8) + .to_string(), + a.to_string(), + Usage::new(self.p).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.p.app, + a, + num, + ma.num_vals(), + Usage::new(self.p).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_set(ArgSettings::TakesValue) && !min_vals_zero && ma.all_val_groups_empty() { + return Err(Error::empty_value( + self.p.app, + a, + Usage::new(self.p).create_usage_with_title(&[]), + )); + } + Ok(()) + } + + fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!( + "Validator::validate_required: required={:?}", + self.p.required + ); + self.gather_requirements(matcher); + + for arg_or_group in self.p.required.iter().filter(|r| !matcher.contains(r)) { + debug!("Validator::validate_required:iter:aog={:?}", arg_or_group); + if let Some(arg) = self.p.app.find(arg_or_group) { + debug!("Validator::validate_required:iter: This is an arg"); + if !self.is_missing_required_ok(arg, matcher) { + return self.missing_required_error(matcher, vec![]); + } + } else if let Some(group) = self.p.app.find_group(arg_or_group) { + debug!("Validator::validate_required:iter: This is a group"); + if !self + .p + .app + .unroll_args_in_group(&group.id) + .iter() + .any(|a| matcher.contains(a)) + { + return self.missing_required_error(matcher, vec![]); + } + } + } + + // Validate the conditionally required args + for a in self.p.app.args.args() { + for (other, val) in &a.r_ifs { + if let Some(ma) = matcher.get(other) { + if ma.contains_val(val) && !matcher.contains(&a.id) { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + } + + let match_all = a + .r_ifs_all + .iter() + .all(|(other, val)| matcher.get(other).map_or(false, |ma| ma.contains_val(val))); + if match_all && !a.r_ifs_all.is_empty() && !matcher.contains(&a.id) { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + Ok(()) + } + + fn is_missing_required_ok(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool { + debug!("Validator::is_missing_required_ok: {}", a.name); + self.validate_arg_conflicts(a, matcher) || self.p.overridden.borrow().contains(&a.id) + } + + fn validate_arg_conflicts(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool { + debug!("Validator::validate_arg_conflicts: a={:?}", a.name); + a.blacklist.iter().any(|conf| { + matcher.contains(conf) + || self + .p + .app + .find_group(conf) + .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg))) + }) + } + + fn validate_required_unless(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_required_unless"); + let failed_args: Vec<_> = self + .p + .app + .args + .args() + .filter(|&a| { + (!a.r_unless.is_empty() || !a.r_unless_all.is_empty()) + && !matcher.contains(&a.id) + && 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.contains(id); + + (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.p.required + ); + + let usg = Usage::new(self.p); + + let req_args = usg.get_required_usage_from(&incl, Some(matcher), true); + + debug!( + "Validator::missing_required_error: req_args={:#?}", + req_args + ); + + let used: Vec = matcher + .arg_names() + .filter(|n| { + // Filter out the args we don't want to specify. + self.p.app.find(n).map_or(true, |a| { + !a.is_set(ArgSettings::Hidden) + && a.default_vals.is_empty() + && !self.p.required.contains(&a.id) + }) + }) + .cloned() + .chain(incl) + .collect(); + + Err(Error::missing_required_argument( + self.p.app, + 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, app: &App, matcher: &ArgMatcher, arg_id: &Id) -> Vec { + debug!("Conflicts::gather_conflicts"); + let mut conflicts = Vec::new(); + for other_arg_id in matcher + .arg_names() + .filter(|arg_id| matcher.contains_explicit(arg_id)) + { + if arg_id == other_arg_id { + continue; + } + + if self + .gather_direct_conflicts(app, arg_id) + .contains(other_arg_id) + { + conflicts.push(other_arg_id.clone()); + } + if self + .gather_direct_conflicts(app, other_arg_id) + .contains(arg_id) + { + conflicts.push(other_arg_id.clone()); + } + } + conflicts + } + + fn gather_direct_conflicts(&mut self, app: &App, arg_id: &Id) -> &[Id] { + self.potential.entry(arg_id.clone()).or_insert_with(|| { + let conf = if let Some(arg) = app.find(arg_id) { + let mut conf = arg.blacklist.clone(); + for group_id in app.groups_for_arg(arg_id) { + let group = app.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()); + } + } + } + } + conf + } else if let Some(group) = app.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 + }) + } +} diff --git a/third_party/rust/clap/src/strext.rs b/third_party/rust/clap/src/strext.rs deleted file mode 100644 index 52efab64f145..000000000000 --- a/third_party/rust/clap/src/strext.rs +++ /dev/null @@ -1,16 +0,0 @@ -pub trait _StrExt { - fn _is_char_boundary(&self, index: usize) -> bool; -} - -impl _StrExt for str { - #[inline] - fn _is_char_boundary(&self, index: usize) -> bool { - if index == self.len() { - return true; - } - match self.as_bytes().get(index) { - None => false, - Some(&b) => !(128..192).contains(&b), - } - } -} diff --git a/third_party/rust/clap/src/suggestions.rs b/third_party/rust/clap/src/suggestions.rs deleted file mode 100644 index 5c549888ff8e..000000000000 --- a/third_party/rust/clap/src/suggestions.rs +++ /dev/null @@ -1,141 +0,0 @@ -// Internal -use crate::{app::App, fmt::Format}; - -/// Produces a string from a given list of possible values which is similar to -/// the passed in value `v` with a certain 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")] -#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_lifetimes))] -pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str> -where - T: AsRef + 'a, - I: IntoIterator, -{ - let mut candidate: Option<(f64, &str)> = None; - for pv in possible_values { - let confidence = strsim::jaro_winkler(v, pv.as_ref()); - if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) - { - candidate = Some((confidence, pv.as_ref())); - } - } - match candidate { - None => None, - Some((_, candidate)) => Some(candidate), - } -} - -#[cfg(not(feature = "suggestions"))] -pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str> -where - T: AsRef + 'a, - I: IntoIterator, -{ - None -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -pub fn did_you_mean_flag_suffix<'z, T, I>( - arg: &str, - args_rest: &'z [&str], - longs: I, - subcommands: &'z [App], -) -> (String, Option<&'z str>) -where - T: AsRef + 'z, - I: IntoIterator, -{ - if let Some(candidate) = did_you_mean(arg, longs) { - let suffix = format!( - "\n\tDid you mean {}{}?", - Format::Good("--"), - Format::Good(candidate) - ); - return (suffix, Some(candidate)); - } - - subcommands - .iter() - .filter_map(|subcommand| { - let opts = subcommand - .p - .flags - .iter() - .filter_map(|f| f.s.long) - .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long)); - - let candidate = match did_you_mean(arg, opts) { - Some(candidate) => candidate, - None => return None, - }; - let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) { - Some(score) => score, - None => return None, - }; - - let suffix = format!( - "\n\tDid you mean to put '{}{}' after the subcommand '{}'?", - Format::Good("--"), - Format::Good(candidate), - Format::Good(subcommand.get_name()) - ); - - Some((score, (suffix, Some(candidate)))) - }) - .min_by_key(|&(score, _)| score) - .map(|(_, suggestion)| suggestion) - .unwrap_or_else(|| (String::new(), None)) -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -pub fn did_you_mean_value_suffix<'z, T, I>(arg: &str, values: I) -> (String, Option<&'z str>) -where - T: AsRef + 'z, - I: IntoIterator, -{ - match did_you_mean(arg, values) { - Some(candidate) => { - let suffix = format!("\n\tDid you mean '{}'?", Format::Good(candidate)); - (suffix, Some(candidate)) - } - None => (String::new(), None), - } -} - -#[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_nomatch() { - let p_vals = ["test", "possible", "values"]; - assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); - } - - #[test] - fn suffix_long() { - let p_vals = ["test", "possible", "values"]; - let suffix = "\n\tDid you mean \'--test\'?"; - assert_eq!( - did_you_mean_flag_suffix("tst", p_vals.iter(), []), - (suffix, Some("test")) - ); - } - - #[test] - fn suffix_enum() { - let p_vals = ["test", "possible", "values"]; - let suffix = "\n\tDid you mean \'test\'?"; - assert_eq!( - did_you_mean_value_suffix("tst", p_vals.iter()), - (suffix, Some("test")) - ); - } -} diff --git a/third_party/rust/clap/src/usage_parser.rs b/third_party/rust/clap/src/usage_parser.rs deleted file mode 100644 index d3c1921d6dcc..000000000000 --- a/third_party/rust/clap/src/usage_parser.rs +++ /dev/null @@ -1,1356 +0,0 @@ -// Internal -use crate::{ - args::{settings::ArgSettings, Arg}, - map::VecMap, - INTERNAL_ERROR_MSG, -}; - -#[derive(PartialEq, Debug)] -enum UsageToken { - Name, - ValName, - Short, - Long, - Help, - Multiple, - Unknown, -} - -#[doc(hidden)] -#[derive(Debug)] -pub struct UsageParser<'a> { - usage: &'a str, - pos: usize, - start: usize, - prev: UsageToken, - explicit_name_set: bool, -} - -impl<'a> UsageParser<'a> { - fn new(usage: &'a str) -> Self { - debugln!("UsageParser::new: usage={:?}", usage); - UsageParser { - usage, - pos: 0, - start: 0, - prev: UsageToken::Unknown, - explicit_name_set: false, - } - } - - pub fn from_usage(usage: &'a str) -> Self { - debugln!("UsageParser::from_usage;"); - UsageParser::new(usage) - } - - pub fn parse(mut self) -> Arg<'a, 'a> { - debugln!("UsageParser::parse;"); - let mut arg = Arg::default(); - loop { - debugln!("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.help(&mut arg), - _ => self.name(&mut arg), - } - } else { - break; - } - } - debug_assert!( - !arg.b.name.is_empty(), - "No name found for Arg when parsing usage string: {}", - self.usage - ); - arg.v.num_vals = match arg.v.val_names { - Some(ref v) if v.len() >= 2 => Some(v.len() as u64), - _ => None, - }; - debugln!("UsageParser::parse: vals...{:?}", arg.v.val_names); - arg - } - - fn name(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::name;"); - if *self - .usage - .as_bytes() - .get(self.pos) - .expect(INTERNAL_ERROR_MSG) - == b'<' - && !self.explicit_name_set - { - arg.setb(ArgSettings::Required); - } - self.pos += 1; - self.stop_at(name_end); - let name = &self.usage[self.start..self.pos]; - if self.prev == UsageToken::Unknown { - debugln!("UsageParser::name: setting name...{}", name); - arg.b.name = name; - if arg.s.long.is_none() && arg.s.short.is_none() { - debugln!("UsageParser::name: explicit name set..."); - self.explicit_name_set = true; - self.prev = UsageToken::Name; - } - } else { - debugln!("UsageParser::name: setting val name...{}", name); - if let Some(ref mut v) = arg.v.val_names { - let len = v.len(); - v.insert(len, name); - } else { - let mut v = VecMap::new(); - v.insert(0, name); - arg.v.val_names = Some(v); - arg.setb(ArgSettings::TakesValue); - } - self.prev = UsageToken::ValName; - } - } - - fn stop_at(&mut self, f: F) - where - F: Fn(u8) -> bool, - { - debugln!("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<'a, 'a>) { - debugln!("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<'a, 'a>) { - debugln!("UsageParser::long;"); - self.stop_at(long_end); - let name = &self.usage[self.start..self.pos]; - if !self.explicit_name_set { - debugln!("UsageParser::long: setting name...{}", name); - arg.b.name = name; - } - debugln!("UsageParser::long: setting long...{}", name); - arg.s.long = Some(name); - self.prev = UsageToken::Long; - } - - fn short(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::short;"); - let start = &self.usage[self.pos..]; - let short = start.chars().next().expect(INTERNAL_ERROR_MSG); - debugln!("UsageParser::short: setting short...{}", short); - arg.s.short = Some(short); - if arg.b.name.is_empty() { - // --long takes precedence but doesn't set self.explicit_name_set - let name = &start[..short.len_utf8()]; - debugln!("UsageParser::short: setting name...{}", name); - arg.b.name = name; - } - self.prev = UsageToken::Short; - } - - // "something..." - fn multiple(&mut self, arg: &mut Arg) { - debugln!("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 { - debugln!("UsageParser::multiple: setting multiple"); - arg.setb(ArgSettings::Multiple); - if arg.is_set(ArgSettings::TakesValue) { - arg.setb(ArgSettings::UseValueDelimiter); - arg.unsetb(ArgSettings::ValueDelimiterNotSet); - if arg.v.val_delim.is_none() { - arg.v.val_delim = Some(','); - } - } - self.prev = UsageToken::Multiple; - self.pos += 1; - break; - } - } - } - - fn help(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::help;"); - self.stop_at(help_start); - self.start = self.pos + 1; - self.pos = self.usage.len() - 1; - debugln!( - "UsageParser::help: setting help...{}", - &self.usage[self.start..self.pos] - ); - arg.b.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; - } -} - -#[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'-' -} - -#[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'\'' -} - -#[cfg(test)] -mod test { - use crate::args::{Arg, ArgSettings}; - - #[test] - fn create_flag_usage() { - let a = Arg::from_usage("[flag] -f 'some help info'"); - assert_eq!(a.b.name, "flag"); - assert_eq!(a.s.short.unwrap(), 'f'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let b = Arg::from_usage("[flag] --flag 'some help info'"); - assert_eq!(b.b.name, "flag"); - assert_eq!(b.s.long.unwrap(), "flag"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let b = Arg::from_usage("--flag 'some help info'"); - assert_eq!(b.b.name, "flag"); - assert_eq!(b.s.long.unwrap(), "flag"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.v.val_names.is_none()); - assert!(b.v.num_vals.is_none()); - - let c = Arg::from_usage("[flag] -f --flag 'some help info'"); - assert_eq!(c.b.name, "flag"); - assert_eq!(c.s.short.unwrap(), 'f'); - assert_eq!(c.s.long.unwrap(), "flag"); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - - let d = Arg::from_usage("[flag] -f... 'some help info'"); - assert_eq!(d.b.name, "flag"); - assert_eq!(d.s.short.unwrap(), 'f'); - assert!(d.s.long.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.v.val_names.is_none()); - assert!(d.v.num_vals.is_none()); - - let e = Arg::from_usage("[flag] -f --flag... 'some help info'"); - assert_eq!(e.b.name, "flag"); - assert_eq!(e.s.long.unwrap(), "flag"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert_eq!(e.b.help.unwrap(), "some help info"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("-f --flag... 'some help info'"); - assert_eq!(e.b.name, "flag"); - assert_eq!(e.s.long.unwrap(), "flag"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert_eq!(e.b.help.unwrap(), "some help info"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("--flags"); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.long.unwrap(), "flags"); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("--flags..."); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.long.unwrap(), "flags"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("[flags] -f"); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("[flags] -f..."); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let a = Arg::from_usage("-f 'some help info'"); - assert_eq!(a.b.name, "f"); - assert_eq!(a.s.short.unwrap(), 'f'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let e = Arg::from_usage("-f"); - assert_eq!(e.b.name, "f"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("-f..."); - assert_eq!(e.b.name, "f"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage0() { - // Short only - let a = Arg::from_usage("[option] -o [opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage1() { - let b = Arg::from_usage("-o [opt] 'some help info'"); - assert_eq!(b.b.name, "o"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert!(b.s.long.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::>(), - [&"opt"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage2() { - let c = Arg::from_usage("

(&self, pat: P) -> &Self + where + P: Pattern, + { + impl_trim_matches!(self, pat, strip_prefix) + } +} + +impl AsRef for RawOsStr { + #[inline] + fn as_ref(&self) -> &Self { + self + } +} + +impl AsRef for str { + #[inline] + fn as_ref(&self) -> &RawOsStr { + RawOsStr::from_str(self) + } +} + +impl AsRef for String { + #[inline] + fn as_ref(&self) -> &RawOsStr { + (**self).as_ref() + } +} + +impl Default for &RawOsStr { + #[inline] + fn default() -> Self { + RawOsStr::from_str("") + } +} + +impl<'a> From<&'a RawOsStr> for Cow<'a, RawOsStr> { + #[inline] + fn from(other: &'a RawOsStr) -> Self { + Cow::Borrowed(other) + } +} + +macro_rules! r#impl { + ( + $index_type:ty + $(, $index_var:ident , $first_bound:expr $(, $second_bound:expr)?)? + ) => { + impl Index<$index_type> for RawOsStr { + type Output = Self; + + #[inline] + fn index(&self, idx: $index_type) -> &Self::Output { + $( + let $index_var = &idx; + self.check_bound($first_bound); + $(self.check_bound($second_bound);)? + )? + + Self::from_raw_bytes_unchecked(&self.0[idx]) + } + } + }; +} +r#impl!(Range, x, x.start, x.end); +r#impl!(RangeFrom, x, x.start); +r#impl!(RangeFull); +// [usize::MAX] will always be a valid inclusive end index. +#[rustfmt::skip] +r#impl!(RangeInclusive, x, *x.start(), x.end().wrapping_add(1)); +r#impl!(RangeTo, x, x.end); +r#impl!(RangeToInclusive, x, x.end.wrapping_add(1)); + +impl ToOwned for RawOsStr { + type Owned = RawOsString; + + #[inline] + fn to_owned(&self) -> Self::Owned { + RawOsString(self.0.to_owned()) + } +} + +/// A container for the byte strings converted by [`OsStringBytes`]. +/// +/// For more information, see [`RawOsStr`]. +/// +/// [unspecified encoding]: super#encoding +#[derive(Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] +pub struct RawOsString(Vec); + +impl RawOsString { + /// Converts a platform-native string into a representation that can be + /// more easily manipulated. + /// + /// For more information, see [`RawOsStr::new`]. + /// + /// # Examples + /// + /// ``` + /// use std::env; + /// # use std::io; + /// + /// use os_str_bytes::RawOsString; + /// + /// let os_string = env::current_exe()?.into_os_string(); + /// println!("{:?}", RawOsString::new(os_string)); + /// # + /// # Ok::<_, io::Error>(()) + /// ``` + #[inline] + #[must_use] + pub fn new(string: OsString) -> Self { + Self(string.into_raw_vec()) + } + + /// Wraps a string, without copying or encoding conversion. + /// + /// This method is much more efficient than [`RawOsString::new`], since the + /// [encoding] used by this crate is compatible with UTF-8. + /// + /// # Examples + /// + /// ``` + /// use os_str_bytes::RawOsString; + /// + /// let string = "foobar".to_owned(); + /// let raw = RawOsString::from_string(string.clone()); + /// assert_eq!(string, raw); + /// ``` + /// + /// [encoding]: super#encoding + #[inline] + #[must_use] + pub fn from_string(string: String) -> Self { + Self(string.into_bytes()) + } + + /// Converts this representation back to a platform-native string. + /// + /// # Examples + /// + /// ``` + /// use std::env; + /// # use std::io; + /// + /// use os_str_bytes::RawOsString; + /// + /// let os_string = env::current_exe()?.into_os_string(); + /// let raw = RawOsString::new(os_string.clone()); + /// assert_eq!(os_string, raw.into_os_string()); + /// # + /// # Ok::<_, io::Error>(()) + /// ``` + #[inline] + #[must_use] + pub fn into_os_string(self) -> OsString { + OsString::from_raw_vec(self.0).expect("invalid raw bytes") + } + + /// Returns the byte string stored by this container. + /// + /// The result will match what would be returned by + /// [`OsStringBytes::into_raw_vec`] for the same string. + /// + /// # Examples + /// + /// ``` + /// use std::env; + /// # use std::io; + /// + /// use os_str_bytes::OsStringBytes; + /// use os_str_bytes::RawOsString; + /// + /// let os_string = env::current_exe()?.into_os_string(); + /// let raw = RawOsString::new(os_string.clone()); + /// assert_eq!(os_string.into_raw_vec(), raw.into_raw_vec()); + /// # + /// # Ok::<_, io::Error>(()) + /// ``` + #[inline] + #[must_use] + pub fn into_raw_vec(self) -> Vec { + self.0 + } + + /// Equivalent to [`OsString::into_string`]. + /// + /// # Examples + /// + /// ``` + /// use os_str_bytes::RawOsString; + /// + /// let string = "foobar".to_owned(); + /// let raw = RawOsString::from_string(string.clone()); + /// assert_eq!(Ok(string), raw.into_string()); + /// ``` + #[inline] + pub fn into_string(self) -> Result { + String::from_utf8(self.0).map_err(|x| Self(x.into_bytes())) + } +} + +impl AsRef for RawOsString { + #[inline] + fn as_ref(&self) -> &RawOsStr { + self + } +} + +impl Borrow for RawOsString { + #[inline] + fn borrow(&self) -> &RawOsStr { + self + } +} + +impl Deref for RawOsString { + type Target = RawOsStr; + + #[inline] + fn deref(&self) -> &Self::Target { + RawOsStr::from_raw_bytes_unchecked(&self.0) + } +} + +impl From for RawOsString { + #[inline] + fn from(other: String) -> Self { + Self::from_string(other) + } +} + +impl From for Cow<'_, RawOsStr> { + #[inline] + fn from(other: RawOsString) -> Self { + Cow::Owned(other) + } +} + +macro_rules! r#impl { + ( $index_type:ty ) => { + impl Index<$index_type> for RawOsString { + type Output = RawOsStr; + + #[inline] + fn index(&self, idx: $index_type) -> &Self::Output { + &(**self)[idx] + } + } + }; +} +r#impl!(Range); +r#impl!(RangeFrom); +r#impl!(RangeFull); +r#impl!(RangeInclusive); +r#impl!(RangeTo); +r#impl!(RangeToInclusive); + +struct Buffer<'a>(&'a [u8]); + +impl Debug for Buffer<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str("\"")?; + + let mut string = self.0; + let mut invalid_length = 0; + while !string.is_empty() { + let (invalid, substring) = string.split_at(invalid_length); + + let valid = match str::from_utf8(substring) { + Ok(valid) => { + string = &[]; + valid + } + Err(error) => { + let (valid, substring) = + substring.split_at(error.valid_up_to()); + + let invalid_char_length = + error.error_len().unwrap_or_else(|| substring.len()); + if valid.is_empty() { + invalid_length += invalid_char_length; + continue; + } + string = substring; + invalid_length = invalid_char_length; + + // SAFETY: This slice was validated to be UTF-8. + unsafe { str::from_utf8_unchecked(valid) } + } + }; + + raw::debug(invalid, f)?; + Display::fmt(&valid.escape_debug(), f)?; + } + + f.write_str("\"") + } +} + +macro_rules! r#impl { + ( $type:ty ) => { + impl Debug for $type { + #[inline] + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_tuple(stringify!($type)) + .field(&Buffer(&self.0)) + .finish() + } + } + }; +} +r#impl!(RawOsStr); +r#impl!(RawOsString); + +macro_rules! r#impl { + ( $type:ty , $other_type:ty ) => { + impl PartialEq<$other_type> for $type { + #[inline] + fn eq(&self, other: &$other_type) -> bool { + let raw: &RawOsStr = self; + let other: &RawOsStr = other.as_ref(); + raw == other + } + } + + impl PartialEq<$type> for $other_type { + #[inline] + fn eq(&self, other: &$type) -> bool { + other == self + } + } + }; +} +r#impl!(RawOsStr, RawOsString); +r#impl!(&RawOsStr, RawOsString); +r#impl!(RawOsStr, str); +r#impl!(RawOsStr, String); +r#impl!(&RawOsStr, String); +r#impl!(RawOsString, str); +r#impl!(RawOsString, &str); +r#impl!(RawOsString, String); + +#[cfg(feature = "print_bytes")] +#[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "print_bytes")))] +mod print_bytes { + use print_bytes::ByteStr; + use print_bytes::ToBytes; + #[cfg(windows)] + use print_bytes::WideStr; + + #[cfg(windows)] + use crate::imp::raw; + + use super::RawOsStr; + use super::RawOsString; + + impl ToBytes for RawOsStr { + #[inline] + fn to_bytes(&self) -> ByteStr<'_> { + self.0.to_bytes() + } + + #[cfg(windows)] + #[inline] + fn to_wide(&self) -> Option { + Some(WideStr::new(raw::encode_wide_unchecked(&self.0).collect())) + } + } + + impl ToBytes for RawOsString { + #[inline] + fn to_bytes(&self) -> ByteStr<'_> { + (**self).to_bytes() + } + + #[cfg(windows)] + #[inline] + fn to_wide(&self) -> Option { + (**self).to_wide() + } + } +} + +#[cfg(feature = "uniquote")] +#[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "uniquote")))] +mod uniquote { + use uniquote::Formatter; + use uniquote::Quote; + use uniquote::Result; + + use crate::imp::raw; + + use super::RawOsStr; + use super::RawOsString; + + impl Quote for RawOsStr { + #[inline] + fn escape(&self, f: &mut Formatter<'_>) -> Result { + raw::uniquote::escape(&self.0, f) + } + } + + impl Quote for RawOsString { + #[inline] + fn escape(&self, f: &mut Formatter<'_>) -> Result { + (**self).escape(f) + } + } +} diff --git a/third_party/rust/os_str_bytes/src/util.rs b/third_party/rust/os_str_bytes/src/util.rs new file mode 100644 index 000000000000..bd28b7be154b --- /dev/null +++ b/third_party/rust/os_str_bytes/src/util.rs @@ -0,0 +1,10 @@ +pub(super) const BYTE_SHIFT: u8 = 6; + +pub(super) const CONT_MASK: u8 = (1 << BYTE_SHIFT) - 1; + +pub(super) const CONT_TAG: u8 = 0b1000_0000; + +#[cfg_attr(not(windows), allow(dead_code))] +pub(super) const fn is_continuation(byte: u8) -> bool { + byte & !CONT_MASK == CONT_TAG +} diff --git a/third_party/rust/os_str_bytes/src/wasm32/mod.rs b/third_party/rust/os_str_bytes/src/wasm32/mod.rs new file mode 100644 index 000000000000..f8ae36861c19 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/wasm32/mod.rs @@ -0,0 +1,56 @@ +use std::borrow::Cow; +use std::error::Error; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; +use std::result; +use std::str; +use std::str::Utf8Error; + +if_raw_str! { + pub(super) mod raw; +} + +#[derive(Debug, Eq, PartialEq)] +pub(super) struct EncodingError(Utf8Error); + +impl Display for EncodingError { + fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + write!(formatter, "os_str_bytes: {}", self.0) + } +} + +impl Error for EncodingError {} + +type Result = result::Result; + +macro_rules! expect_utf8 { + ( $result:expr ) => { + $result.expect( + "platform string contains invalid UTF-8, which should not be \ + possible", + ) + }; +} + +pub(super) fn os_str_from_bytes(string: &[u8]) -> Result> { + str::from_utf8(string) + .map(|x| Cow::Borrowed(OsStr::new(x))) + .map_err(EncodingError) +} + +pub(super) fn os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]> { + Cow::Borrowed(expect_utf8!(os_string.to_str()).as_bytes()) +} + +pub(super) fn os_string_from_vec(string: Vec) -> Result { + String::from_utf8(string) + .map(Into::into) + .map_err(|x| EncodingError(x.utf8_error())) +} + +pub(super) fn os_string_into_vec(os_string: OsString) -> Vec { + expect_utf8!(os_string.into_string()).into_bytes() +} diff --git a/third_party/rust/os_str_bytes/src/wasm32/raw.rs b/third_party/rust/os_str_bytes/src/wasm32/raw.rs new file mode 100644 index 000000000000..5645900576c2 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/wasm32/raw.rs @@ -0,0 +1,39 @@ +use std::fmt; +use std::fmt::Formatter; +use std::str; + +pub(crate) use crate::util::is_continuation; + +pub(crate) fn decode_code_point(string: &[u8]) -> u32 { + let string = str::from_utf8(string).expect("invalid string"); + let mut chars = string.chars(); + let ch = chars + .next() + .expect("cannot parse code point from empty string"); + assert_eq!(None, chars.next(), "multiple code points found"); + ch.into() +} + +pub(crate) fn ends_with(string: &[u8], suffix: &[u8]) -> bool { + string.ends_with(suffix) +} + +pub(crate) fn starts_with(string: &[u8], prefix: &[u8]) -> bool { + string.starts_with(prefix) +} + +pub(crate) fn debug(string: &[u8], _: &mut Formatter<'_>) -> fmt::Result { + assert!(string.is_empty()); + Ok(()) +} + +#[cfg(feature = "uniquote")] +pub(crate) mod uniquote { + use uniquote::Formatter; + use uniquote::Quote; + use uniquote::Result; + + pub(crate) fn escape(string: &[u8], f: &mut Formatter<'_>) -> Result { + string.escape(f) + } +} diff --git a/third_party/rust/os_str_bytes/src/windows/mod.rs b/third_party/rust/os_str_bytes/src/windows/mod.rs new file mode 100644 index 000000000000..3b6105b27508 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/mod.rs @@ -0,0 +1,152 @@ +// These functions are necessarily inefficient, because they must revert +// encoding conversions performed by the standard library. However, there is +// currently no better alternative. + +use std::borrow::Cow; +use std::error::Error; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::ffi::OsStringExt; +use std::result; +use std::str; + +if_raw_str! { + pub(super) mod raw; +} + +mod wtf8; +use wtf8::encode_wide; +use wtf8::DecodeWide; + +#[derive(Debug, Eq, PartialEq)] +pub(super) enum EncodingError { + Byte(u8), + CodePoint(u32), + End(), +} + +impl EncodingError { + fn position(&self) -> Cow<'_, str> { + match self { + Self::Byte(byte) => Cow::Owned(format!("byte b'\\x{:02X}'", byte)), + Self::CodePoint(code_point) => { + Cow::Owned(format!("code point U+{:04X}", code_point)) + } + Self::End() => Cow::Borrowed("end of string"), + } + } +} + +impl Display for EncodingError { + fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result { + write!( + formatter, + "byte sequence is not representable in the platform encoding; \ + error at {}", + self.position(), + ) + } +} + +impl Error for EncodingError {} + +type Result = result::Result; + +fn from_bytes(string: &[u8]) -> Result { + let encoder = encode_wide(string); + + // Collecting an iterator into a result ignores the size hint: + // https://github.com/rust-lang/rust/issues/48994 + let mut encoded_string = Vec::with_capacity(encoder.size_hint().0); + for wchar in encoder { + encoded_string.push(wchar?); + } + Ok(OsStringExt::from_wide(&encoded_string)) +} + +fn to_bytes(os_string: &OsStr) -> Vec { + let encoder = OsStrExt::encode_wide(os_string); + + let mut string = Vec::with_capacity(encoder.size_hint().0); + string.extend(DecodeWide::new(encoder)); + string +} + +pub(super) fn os_str_from_bytes(string: &[u8]) -> Result> { + from_bytes(string).map(Cow::Owned) +} + +pub(super) fn os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]> { + Cow::Owned(to_bytes(os_string)) +} + +pub(super) fn os_string_from_vec(string: Vec) -> Result { + from_bytes(&string) +} + +pub(super) fn os_string_into_vec(os_string: OsString) -> Vec { + to_bytes(&os_string) +} + +#[cfg(test)] +mod tests { + use std::ffi::OsStr; + + use crate::OsStrBytes; + + use super::EncodingError; + + #[test] + fn test_invalid() { + use EncodingError::Byte; + use EncodingError::CodePoint; + use EncodingError::End; + + test_error(Byte(b'\x83'), b"\x0C\x83\xD7\x3E"); + test_error(Byte(b'\x52'), b"\x19\xF7\x52\x84"); + test_error(Byte(b'\xB8'), b"\x70\xB8\x1F\x66"); + test_error(CodePoint(0x34_0388), b"\x70\xFD\x80\x8E\x88"); + test_error(Byte(b'\x80'), b"\x80"); + test_error(Byte(b'\x80'), b"\x80\x80"); + test_error(Byte(b'\x80'), b"\x80\x80\x80"); + test_error(Byte(b'\x81'), b"\x81"); + test_error(Byte(b'\x88'), b"\x88\xB4\xC7\x46"); + test_error(Byte(b'\x97'), b"\x97\xCE\x06"); + test_error(Byte(b'\x00'), b"\xC2\x00"); + test_error(Byte(b'\x7F'), b"\xC2\x7F"); + test_error(Byte(b'\x09'), b"\xCD\x09\x95"); + test_error(Byte(b'\x43'), b"\xCD\x43\x5F\xA0"); + test_error(Byte(b'\x69'), b"\xD7\x69\xB2"); + test_error(CodePoint(0x528), b"\xE0\x94\xA8"); + test_error(CodePoint(0x766), b"\xE0\x9D\xA6\x12\xAE"); + test_error(Byte(b'\xFD'), b"\xE2\xAB\xFD\x51"); + test_error(Byte(b'\xC4'), b"\xE3\xC4"); + test_error(CodePoint(0xDC00), b"\xED\xA0\x80\xED\xB0\x80"); + test_error(End(), b"\xF1"); + test_error(End(), b"\xF1\x80"); + test_error(End(), b"\xF1\x80\x80"); + test_error(Byte(b'\xF1'), b"\xF1\x80\x80\xF1"); + test_error(CodePoint(0x11_09CC), b"\xF4\x90\xA7\x8C"); + test_error(CodePoint(0x15_EC46), b"\xF5\x9E\xB1\x86"); + test_error(End(), b"\xFB"); + test_error(End(), b"\xFB\x80"); + test_error(End(), b"\xFB\x80\x80"); + test_error(CodePoint(0x2C_0000), b"\xFB\x80\x80\x80"); + test_error(End(), b"\xFF"); + test_error(End(), b"\xFF\x80"); + test_error(End(), b"\xFF\x80\x80"); + test_error(CodePoint(0x3C_0000), b"\xFF\x80\x80\x80"); + test_error(CodePoint(0x3C_6143), b"\xFF\x86\x85\x83"); + + fn test_error(error: EncodingError, string: &[u8]) { + assert_eq!( + Err(error), + OsStr::from_raw_bytes(string).map_err(|x| x.0), + ); + } + } +} diff --git a/third_party/rust/os_str_bytes/src/windows/raw.rs b/third_party/rust/os_str_bytes/src/windows/raw.rs new file mode 100644 index 000000000000..630eb01ea691 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/raw.rs @@ -0,0 +1,42 @@ +use std::fmt; +use std::fmt::Formatter; + +pub(crate) use crate::util::is_continuation; + +use super::wtf8; +pub(crate) use super::wtf8::ends_with; +pub(crate) use super::wtf8::starts_with; +use super::wtf8::CodePoints; + +pub(crate) fn encode_wide_unchecked( + string: &[u8], +) -> impl '_ + Iterator { + wtf8::encode_wide(string).map(|x| x.expect("invalid string")) +} + +pub(crate) fn decode_code_point(string: &[u8]) -> u32 { + let mut code_points = CodePoints::new(string.iter().copied()); + let code_point = code_points + .next() + .expect("cannot parse code point from empty string") + .expect("invalid string"); + assert_eq!(None, code_points.next(), "multiple code points found"); + code_point +} + +pub(crate) fn debug(string: &[u8], f: &mut Formatter<'_>) -> fmt::Result { + for wchar in encode_wide_unchecked(string) { + write!(f, "\\u{{{:X}}}", wchar)?; + } + Ok(()) +} + +#[cfg(feature = "uniquote")] +pub(crate) mod uniquote { + use uniquote::Formatter; + use uniquote::Result; + + pub(crate) fn escape(string: &[u8], f: &mut Formatter<'_>) -> Result { + f.escape_utf16(super::encode_wide_unchecked(string)) + } +} diff --git a/third_party/rust/os_str_bytes/src/windows/wtf8/code_points.rs b/third_party/rust/os_str_bytes/src/windows/wtf8/code_points.rs new file mode 100644 index 000000000000..b265db332412 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/wtf8/code_points.rs @@ -0,0 +1,117 @@ +use std::iter::Peekable; +use std::mem; + +use crate::util::is_continuation; +use crate::util::BYTE_SHIFT; +use crate::util::CONT_MASK; + +use super::EncodingError; +use super::Result; + +pub(in super::super) struct CodePoints +where + I: Iterator, +{ + iter: Peekable, + surrogate: bool, +} + +impl CodePoints +where + I: Iterator, +{ + pub(in super::super) fn new(string: S) -> Self + where + S: IntoIterator, + { + Self { + iter: string.into_iter().peekable(), + surrogate: false, + } + } + + fn consume_next(&mut self, code_point: &mut u32) -> Result<()> { + if let Some(&byte) = self.iter.peek() { + if !is_continuation(byte) { + self.surrogate = false; + // Not consuming this byte will be useful if this crate ever + // offers a way to encode lossily. + return Err(EncodingError::Byte(byte)); + } + *code_point = + (*code_point << BYTE_SHIFT) | u32::from(byte & CONT_MASK); + + let removed = self.iter.next(); + debug_assert_eq!(Some(byte), removed); + } else { + return Err(EncodingError::End()); + } + Ok(()) + } + + pub(super) fn inner_size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl Iterator for CodePoints +where + I: Iterator, +{ + type Item = Result; + + fn next(&mut self) -> Option { + let byte = self.iter.next()?; + let mut code_point: u32 = byte.into(); + + macro_rules! consume_next { + () => {{ + if let Err(error) = self.consume_next(&mut code_point) { + return Some(Err(error)); + } + }}; + } + + let prev_surrogate = mem::replace(&mut self.surrogate, false); + + let mut invalid = false; + if !byte.is_ascii() { + if byte < 0xC2 { + return Some(Err(EncodingError::Byte(byte))); + } + + if byte < 0xE0 { + code_point &= 0x1F; + } else { + code_point &= 0x0F; + consume_next!(); + + if byte >= 0xF0 { + if code_point.wrapping_sub(0x10) >= 0x100 { + invalid = true; + } + consume_next!(); + + // This condition is optimized to detect surrogate code points. + } else if code_point & 0xFE0 == 0x360 { + if code_point & 0x10 == 0 { + self.surrogate = true; + } else if prev_surrogate { + // Decoding a broken surrogate pair would be lossy. + invalid = true; + } + } + + if code_point < 0x20 { + invalid = true; + } + } + consume_next!(); + } + if invalid { + return Some(Err(EncodingError::CodePoint(code_point))); + } + + Some(Ok(code_point)) + } +} diff --git a/third_party/rust/os_str_bytes/src/windows/wtf8/convert.rs b/third_party/rust/os_str_bytes/src/windows/wtf8/convert.rs new file mode 100644 index 000000000000..75843f5b3100 --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/wtf8/convert.rs @@ -0,0 +1,166 @@ +use std::char; +use std::char::DecodeUtf16; +use std::num::NonZeroU16; + +use crate::util::BYTE_SHIFT; +use crate::util::CONT_MASK; +use crate::util::CONT_TAG; + +use super::CodePoints; +use super::Result; + +const MIN_HIGH_SURROGATE: u16 = 0xD800; + +const MIN_LOW_SURROGATE: u16 = 0xDC00; + +const MIN_SURROGATE_CODE: u32 = (u16::MAX as u32) + 1; + +macro_rules! static_assert { + ( $condition:expr ) => { + const _: () = [()][if $condition { 0 } else { 1 }]; + }; +} + +pub(in super::super) struct DecodeWide +where + I: Iterator, +{ + iter: DecodeUtf16, + code_point: u32, + shift: u8, +} + +impl DecodeWide +where + I: Iterator, +{ + pub(in super::super) fn new(string: S) -> Self + where + S: IntoIterator, + { + Self { + iter: char::decode_utf16(string), + code_point: 0, + shift: 0, + } + } +} + +impl Iterator for DecodeWide +where + I: Iterator, +{ + type Item = u8; + + fn next(&mut self) -> Option { + if let Some(shift) = self.shift.checked_sub(BYTE_SHIFT) { + self.shift = shift; + return Some( + ((self.code_point >> self.shift) as u8 & CONT_MASK) | CONT_TAG, + ); + } + + self.code_point = self + .iter + .next()? + .map(Into::into) + .unwrap_or_else(|x| x.unpaired_surrogate().into()); + + macro_rules! decode { + ( $tag:expr ) => { + Some((self.code_point >> self.shift) as u8 | $tag) + }; + } + macro_rules! try_decode { + ( $tag:expr , $upper_bound:expr ) => { + if self.code_point < $upper_bound { + return decode!($tag); + } + self.shift += BYTE_SHIFT; + }; + } + try_decode!(0, 0x80); + try_decode!(0xC0, 0x800); + try_decode!(0xE0, MIN_SURROGATE_CODE); + decode!(0xF0) + } + + fn size_hint(&self) -> (usize, Option) { + let (low, high) = self.iter.size_hint(); + let shift = self.shift.into(); + ( + low.saturating_add(shift), + high.and_then(|x| x.checked_mul(4)) + .and_then(|x| x.checked_add(shift)), + ) + } +} + +struct EncodeWide +where + I: Iterator, +{ + iter: CodePoints, + surrogate: Option, +} + +impl EncodeWide +where + I: Iterator, +{ + pub(in super::super) fn new(string: S) -> Self + where + S: IntoIterator, + { + Self { + iter: CodePoints::new(string), + surrogate: None, + } + } +} + +impl Iterator for EncodeWide +where + I: Iterator, +{ + type Item = Result; + + fn next(&mut self) -> Option { + if let Some(surrogate) = self.surrogate.take() { + return Some(Ok(surrogate.get())); + } + + self.iter.next().map(|code_point| { + code_point.map(|code_point| { + code_point + .checked_sub(MIN_SURROGATE_CODE) + .map(|offset| { + static_assert!(MIN_LOW_SURROGATE != 0); + + self.surrogate = Some(unsafe { + NonZeroU16::new_unchecked( + (offset & 0x3FF) as u16 | MIN_LOW_SURROGATE, + ) + }); + (offset >> 10) as u16 | MIN_HIGH_SURROGATE + }) + .unwrap_or(code_point as u16) + }) + }) + } + + fn size_hint(&self) -> (usize, Option) { + let (low, high) = self.iter.inner_size_hint(); + let additional = self.surrogate.is_some().into(); + ( + (low.saturating_add(2) / 3).saturating_add(additional), + high.and_then(|x| x.checked_add(additional)), + ) + } +} + +pub(in super::super) fn encode_wide( + string: &[u8], +) -> impl '_ + Iterator> { + EncodeWide::new(string.iter().copied()) +} diff --git a/third_party/rust/os_str_bytes/src/windows/wtf8/mod.rs b/third_party/rust/os_str_bytes/src/windows/wtf8/mod.rs new file mode 100644 index 000000000000..d8b0dc4a7fbf --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/wtf8/mod.rs @@ -0,0 +1,18 @@ +// This module implements the WTF-8 encoding specification: +// https://simonsapin.github.io/wtf-8/ + +use super::EncodingError; +use super::Result; + +mod code_points; +pub(super) use code_points::CodePoints; + +mod convert; +pub(super) use convert::encode_wide; +pub(super) use convert::DecodeWide; + +if_raw_str! { + mod string; + pub(crate) use string::ends_with; + pub(crate) use string::starts_with; +} diff --git a/third_party/rust/os_str_bytes/src/windows/wtf8/string.rs b/third_party/rust/os_str_bytes/src/windows/wtf8/string.rs new file mode 100644 index 000000000000..10b8fafb649c --- /dev/null +++ b/third_party/rust/os_str_bytes/src/windows/wtf8/string.rs @@ -0,0 +1,63 @@ +use crate::util::is_continuation; + +use super::encode_wide; + +const SURROGATE_LENGTH: usize = 3; + +pub(crate) fn ends_with(string: &[u8], mut suffix: &[u8]) -> bool { + let index = match string.len().checked_sub(suffix.len()) { + Some(index) => index, + None => return false, + }; + if let Some(&byte) = string.get(index) { + if is_continuation(byte) { + let index = index.checked_sub(1).expect("invalid string"); + let mut wide_surrogate = match suffix.get(..SURROGATE_LENGTH) { + Some(surrogate) => encode_wide(surrogate), + None => return false, + }; + let surrogate_wchar = wide_surrogate + .next() + .expect("failed decoding non-empty suffix"); + + if wide_surrogate.next().is_some() + || encode_wide(&string[index..]) + .take_while(Result::is_ok) + .nth(1) + != Some(surrogate_wchar) + { + return false; + } + suffix = &suffix[SURROGATE_LENGTH..]; + } + } + string.ends_with(suffix) +} + +pub(crate) fn starts_with(string: &[u8], mut prefix: &[u8]) -> bool { + if let Some(&byte) = string.get(prefix.len()) { + if is_continuation(byte) { + let index = match prefix.len().checked_sub(SURROGATE_LENGTH) { + Some(index) => index, + None => return false, + }; + let (substring, surrogate) = prefix.split_at(index); + let mut wide_surrogate = encode_wide(surrogate); + let surrogate_wchar = wide_surrogate + .next() + .expect("failed decoding non-empty prefix"); + + if surrogate_wchar.is_err() + || wide_surrogate.next().is_some() + || encode_wide(&string[index..]) + .next() + .expect("failed decoding non-empty substring") + != surrogate_wchar + { + return false; + } + prefix = substring; + } + } + string.starts_with(prefix) +} diff --git a/third_party/rust/strsim/.cargo-checksum.json b/third_party/rust/strsim/.cargo-checksum.json index 6b073e9bdfdb..245ef42f911c 100644 --- a/third_party/rust/strsim/.cargo-checksum.json +++ b/third_party/rust/strsim/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"CHANGELOG.md":"18e89ab18be7d22dd835924a38b1198651e870dfd0a2904a344120d341c4bc0e","Cargo.toml":"dd189fa732c00b7d1b036b43220253ef6ff2a0b1ff5ca7cf13f0669113a2055e","LICENSE":"1738b51502ae831fb59ffbeb22ebdd90bf17e5c72fe57c00b47552415f133fd8","README.md":"cfb01477df60cd0780ba59cbbc388f3f71d83bf51bab77e004fc7b811aff0efd","appveyor.yml":"b41eae9798a9bb250f6046509d9bbd6e63bac9ad2655d342b3d9c8975584f0c0","benches/benches.rs":"e277857c44afdc08b2acf35fc05be6226529c588eb9da397382b0a74c58615ab","dev":"5bd26dc2c86f777627abe96c5992b6c45e6b5dea52f42b7107fa5c106abe2ab4","src/lib.rs":"26a960216567e5dea46033b3383a69e7da498095c092e195e92c05faef52f915","tests/lib.rs":"de2b1181c379a0f55de7b86021a9afb77dbe81053a6acf99623bec3663f9b7c4"},"package":"8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"} \ No newline at end of file +{"files":{"CHANGELOG.md":"96553d0de79bf911b5ca66c999195f7f4ea6061564e4698d1adcb567060e1bcd","Cargo.toml":"3f0f1737ecbf9c7595b52585d54507f217e66b2b8dfa337934ca427022d810c8","LICENSE":"1e697ce8d21401fbf1bddd9b5c3fd4c4c79ae1e3bdf51f81761c85e11d5a89cd","README.md":"b9fc7a1ac69abed8055b824713bf9ebfb4a07e2b7a356b50d8ed55e7a9accd18","benches/benches.rs":"62c83a5a0948c06ffb54d0bf75a31ee5d9e5acde9e079c3b5cfb755bc634b72c","src/lib.rs":"1300ad81d4b682476e30d361a01a248a93e96426303ffde8bbd585258fa0b02f","tests/lib.rs":"de2b1181c379a0f55de7b86021a9afb77dbe81053a6acf99623bec3663f9b7c4"},"package":"73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"} \ No newline at end of file diff --git a/third_party/rust/strsim/CHANGELOG.md b/third_party/rust/strsim/CHANGELOG.md index 48d6359eaf11..5b029ffb9b91 100644 --- a/third_party/rust/strsim/CHANGELOG.md +++ b/third_party/rust/strsim/CHANGELOG.md @@ -1,17 +1,58 @@ # Change Log + This project attempts to adhere to [Semantic Versioning](http://semver.org). ## [Unreleased] -## [0.8.0] - (2018-08-19) +## [0.10.0] - (2020-01-31) + ### Added + +- Sørensen-Dice implementation (thanks [@robjtede](https://github.com/robjtede)) + +## [0.9.3] - (2019-12-12) + +### Fixed + +- Fix Jaro and Jaro-Winkler when the arguments have lengths of 1 and are equal. + Previously, the functions would erroneously return 0 instead of 1. Thanks to + [@vvrably](https://github.com/vvrably) for pointing out the issue. + +## [0.9.2] - (2019-05-09) + +### Changed + +- Revert back to the standard library hashmap because it will use hashbrown very + soon +- Remove ndarray in favor of using a single vector to represent the 2d grid in + Damerau-Levenshtein + +## [0.9.1] - (2019-04-08) + +### Changed + +- Faster Damerau-Levenshtein implementation (thanks [@lovasoa](https://github.com/lovasoa)) + +## [0.9.0] - (2019-04-06) + +### Added + +- Generic distance functions (thanks [@lovasoa](https://github.com/lovasoa)) + +## [0.8.0] - (2018-08-19) + +### Added + - Normalized versions of Levenshtein and Damerau-Levenshtein (thanks [@gentoid](https://github.com/gentoid)) ## [0.7.0] - (2018-01-17) + ### Changed + - Faster Levenshtein implementation (thanks [@wdv4758h](https://github.com/wdv4758h)) ### Removed + - Remove the "against_vec" functions. They are one-liners now, so they don't seem to add enough value to justify making the API larger. I didn't find anybody using them when I skimmed through a GitHub search. If you do use them, @@ -21,86 +62,125 @@ let distances = strings.iter().map(|a| jaro(target, a)).collect(); ``` ## [0.6.0] - (2016-12-26) + ### Added + - Add optimal string alignment distance ### Fixed + - Fix Damerau-Levenshtein implementation (previous implementation was actually optimal string alignment; see this [Damerau-Levenshtein explanation]) ## [0.5.2] - (2016-11-21) + ### Changed + - Remove Cargo generated documentation in favor of a [docs.rs] link ## [0.5.1] - (2016-08-23) + ### Added + - Add Cargo generated documentation ### Fixed + - Fix panic when Jaro or Jaro-Winkler are given strings both with a length of one ## [0.5.0] - (2016-08-11) + ### Changed + - Make Hamming faster (thanks @IBUzPE9) when the two strings have the same length but slower when they have different lengths ## [0.4.1] - (2016-04-18) + ### Added + - Add Vagrant setup for development - Add AppVeyor configuration for Windows CI ### Fixed + - Fix metrics when given strings with multibyte characters (thanks @WanzenBug) ## [0.4.0] - (2015-06-10) + ### Added + - For each metric, add a function that takes a vector of strings and returns a vector of results (thanks @ovarene) ## [0.3.0] - (2015-04-30) + ### Changed + - Remove usage of unstable Rust features ## [0.2.5] - (2015-04-24) + ### Fixed + - Remove unnecessary `Float` import from doc tests ## [0.2.4] - (2015-04-15) + ### Fixed + - Remove unused `core` feature flag ## [0.2.3] - (2015-04-01) + ### Fixed + - Remove now unnecessary `Float` import ## [0.2.2] - (2015-03-29) + ### Fixed + - Remove usage of `char_at` (marked as unstable) ## [0.2.1] - (2015-02-20) + ### Fixed + - Update bit vector import to match Rust update ## [0.2.0] - (2015-02-19) + ### Added + - Implement Damerau-Levenshtein - Add tests in docs ## [0.1.1] - (2015-02-10) + ### Added + - Configure Travis for CI - Add rustdoc comments ### Fixed + - Limit Jaro-Winkler return value to a maximum of 1.0 - Fix float comparisons in tests ## [0.1.0] - (2015-02-09) + ### Added + - Implement Hamming, Jaro, Jaro-Winkler, and Levenshtein -[Unreleased]: https://github.com/dguo/strsim-rs/compare/0.8.0...HEAD +[Unreleased]: https://github.com/dguo/strsim-rs/compare/0.10.0...HEAD +[0.10.0]: https://github.com/dguo/strsim-rs/compare/0.9.3...0.10.0 +[0.9.3]: https://github.com/dguo/strsim-rs/compare/0.9.2...0.9.3 +[0.9.2]: https://github.com/dguo/strsim-rs/compare/0.9.1...0.9.2 +[0.9.1]: https://github.com/dguo/strsim-rs/compare/0.9.0...0.9.1 +[0.9.0]: https://github.com/dguo/strsim-rs/compare/0.8.0...0.9.0 [0.8.0]: https://github.com/dguo/strsim-rs/compare/0.7.0...0.8.0 [0.7.0]: https://github.com/dguo/strsim-rs/compare/0.6.0...0.7.0 [0.6.0]: https://github.com/dguo/strsim-rs/compare/0.5.2...0.6.0 diff --git a/third_party/rust/strsim/Cargo.toml b/third_party/rust/strsim/Cargo.toml index 38d37aee5b3e..aca741a86a3e 100644 --- a/third_party/rust/strsim/Cargo.toml +++ b/third_party/rust/strsim/Cargo.toml @@ -12,17 +12,13 @@ [package] name = "strsim" -version = "0.8.0" -authors = ["Danny Guo "] -description = "Implementations of string similarity metrics.\nIncludes Hamming, Levenshtein, OSA, Damerau-Levenshtein, Jaro, and Jaro-Winkler.\n" +version = "0.10.0" +authors = ["Danny Guo "] +exclude = ["/.github", "/dev"] +description = "Implementations of string similarity metrics. Includes Hamming, Levenshtein,\nOSA, Damerau-Levenshtein, Jaro, Jaro-Winkler, and Sørensen-Dice.\n" homepage = "https://github.com/dguo/strsim-rs" documentation = "https://docs.rs/strsim/" readme = "README.md" keywords = ["string", "similarity", "Hamming", "Levenshtein", "Jaro"] license = "MIT" repository = "https://github.com/dguo/strsim-rs" -[badges.appveyor] -repository = "dguo/strsim-rs" - -[badges.travis-ci] -repository = "dguo/strsim-rs" diff --git a/third_party/rust/strsim/LICENSE b/third_party/rust/strsim/LICENSE index 1aacdb8642b5..8d1fbe1dce99 100644 --- a/third_party/rust/strsim/LICENSE +++ b/third_party/rust/strsim/LICENSE @@ -2,6 +2,7 @@ The MIT License (MIT) Copyright (c) 2015 Danny Guo Copyright (c) 2016 Titus Wormer +Copyright (c) 2018 Akash Kurdekar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -20,4 +21,3 @@ 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/third_party/rust/strsim/README.md b/third_party/rust/strsim/README.md index 8765ea85f990..d8c9780d4860 100644 --- a/third_party/rust/strsim/README.md +++ b/third_party/rust/strsim/README.md @@ -1,4 +1,9 @@ -# strsim-rs [![Crates.io](https://img.shields.io/crates/v/strsim.svg)](https://crates.io/crates/strsim) [![Crates.io](https://img.shields.io/crates/l/strsim.svg?maxAge=2592000)](https://github.com/dguo/strsim-rs/blob/master/LICENSE) [![Linux build status](https://travis-ci.org/dguo/strsim-rs.svg?branch=master)](https://travis-ci.org/dguo/strsim-rs) [![Windows build status](https://ci.appveyor.com/api/projects/status/ggue6i785618a39w?svg=true)](https://ci.appveyor.com/project/dguo/strsim-rs) +# strsim-rs + +[![Crates.io](https://img.shields.io/crates/v/strsim.svg)](https://crates.io/crates/strsim) +[![Crates.io](https://img.shields.io/crates/l/strsim.svg?maxAge=2592000)](https://github.com/dguo/strsim-rs/blob/master/LICENSE) +[![CI status](https://github.com/dguo/strsim-rs/workflows/CI/badge.svg)](https://github.com/dguo/strsim-rs/actions?query=branch%3Amaster) +[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/) [Rust](https://www.rust-lang.org) implementations of [string similarity metrics]: - [Hamming] @@ -6,26 +11,35 @@ - [Optimal string alignment] - [Damerau-Levenshtein] - distance & normalized - [Jaro and Jaro-Winkler] - this implementation of Jaro-Winkler does not limit the common prefix length + - [Sørensen-Dice] -### Installation +The normalized versions return values between `0.0` and `1.0`, where `1.0` means +an exact match. + +There are also generic versions of the functions for non-string inputs. + +## Installation + +`strsim` is available on [crates.io](https://crates.io/crates/strsim). Add it to +your `Cargo.toml`: ```toml -# Cargo.toml [dependencies] -strsim = "0.8.0" +strsim = "0.10.0" ``` -### [Documentation](https://docs.rs/strsim/) -You can change the version in the url to see the documentation for an older -version in the -[changelog](https://github.com/dguo/strsim-rs/blob/master/CHANGELOG.md). +## Usage + +Go to [Docs.rs](https://docs.rs/strsim/) for the full documentation. You can +also clone the repo, and run `$ cargo doc --open`. + +### Examples -### Usage ```rust extern crate strsim; use strsim::{hamming, levenshtein, normalized_levenshtein, osa_distance, damerau_levenshtein, normalized_damerau_levenshtein, jaro, - jaro_winkler}; + jaro_winkler, sorensen_dice}; fn main() { match hamming("hamming", "hammers") { @@ -33,31 +47,49 @@ fn main() { Err(why) => panic!("{:?}", why) } - assert_eq!(3, levenshtein("kitten", "sitting")); + assert_eq!(levenshtein("kitten", "sitting"), 3); - assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001); + assert!((normalized_levenshtein("kitten", "sitting") - 0.571).abs() < 0.001); - assert_eq!(3, osa_distance("ac", "cba")); + assert_eq!(osa_distance("ac", "cba"), 3); - assert_eq!(2, damerau_levenshtein("ac", "cba")); + assert_eq!(damerau_levenshtein("ac", "cba"), 2); - assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001) - - assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < + assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.272).abs() < 0.001); - assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < + assert!((jaro("Friedrich Nietzsche", "Jean-Paul Sartre") - 0.392).abs() < 0.001); + + assert!((jaro_winkler("cheeseburger", "cheese fries") - 0.911).abs() < + 0.001); + + assert_eq!(sorensen_dice("web applications", "applications of the web"), + 0.7878787878787878); } ``` -### Development +Using the generic versions of the functions: + +```rust +extern crate strsim; + +use strsim::generic_levenshtein; + +fn main() { + assert_eq!(2, generic_levenshtein(&[1, 2, 3], &[0, 2, 5])); +} +``` + +## Contributing + If you don't want to install Rust itself, you can run `$ ./dev` for a development CLI if you have [Docker] installed. -Benchmarks require a Nightly toolchain. They are run by `cargo +nightly bench`. +Benchmarks require a Nightly toolchain. Run `$ cargo +nightly bench`. + +## License -### License [MIT](https://github.com/dguo/strsim-rs/blob/master/LICENSE) [string similarity metrics]:http://en.wikipedia.org/wiki/String_metric @@ -66,4 +98,5 @@ Benchmarks require a Nightly toolchain. They are run by `cargo +nightly bench`. [Levenshtein]:http://en.wikipedia.org/wiki/Levenshtein_distance [Hamming]:http://en.wikipedia.org/wiki/Hamming_distance [Optimal string alignment]:https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance +[Sørensen-Dice]:http://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient [Docker]:https://docs.docker.com/engine/installation/ diff --git a/third_party/rust/strsim/appveyor.yml b/third_party/rust/strsim/appveyor.yml deleted file mode 100644 index fb992db82b66..000000000000 --- a/third_party/rust/strsim/appveyor.yml +++ /dev/null @@ -1,13 +0,0 @@ -install: - - ps: Start-FileDownload 'https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-gnu.exe' - - rust-beta-x86_64-pc-windows-gnu.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo build - - cargo test --verbose - diff --git a/third_party/rust/strsim/benches/benches.rs b/third_party/rust/strsim/benches/benches.rs index a6d5372e845a..b7ba829f7436 100644 --- a/third_party/rust/strsim/benches/benches.rs +++ b/third_party/rust/strsim/benches/benches.rs @@ -5,17 +5,17 @@ extern crate strsim; mod benches { + use self::test::Bencher; use super::*; extern crate test; - use self::test::Bencher; #[bench] fn bench_hamming(bencher: &mut Bencher) { let a = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGG"; let b = "CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGC"; bencher.iter(|| { - strsim::hamming(&a, &b).unwrap(); + strsim::hamming(a, b).unwrap(); }) } @@ -46,6 +46,13 @@ mod benches { }) } + #[bench] + fn bench_levenshtein_on_u8(bencher: &mut Bencher) { + bencher.iter(|| { + strsim::generic_levenshtein(&vec![0u8; 30], &vec![7u8; 31]); + }) + } + #[bench] fn bench_normalized_levenshtein(bencher: &mut Bencher) { let a = "Philosopher Friedrich Nietzsche"; @@ -81,4 +88,13 @@ mod benches { strsim::normalized_damerau_levenshtein(&a, &b); }) } + + #[bench] + fn bench_sorensen_dice(bencher: &mut Bencher) { + let a = "Philosopher Friedrich Nietzsche"; + let b = "Philosopher Jean-Paul Sartre"; + bencher.iter(|| { + strsim::sorensen_dice(&a, &b); + }) + } } diff --git a/third_party/rust/strsim/dev b/third_party/rust/strsim/dev deleted file mode 100755 index 4c85a494b778..000000000000 --- a/third_party/rust/strsim/dev +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python3 -# ./dev --help - -import argparse -import os -from subprocess import run -import sys - -parser = argparse.ArgumentParser(prog='./dev') -subparsers = parser.add_subparsers(metavar='', title='commands') -command = [ - 'docker', 'run', '-it', '--rm', '-v', os.getcwd() + ':/src:cached', - '-w=/src', 'rust:1.21.0' -] - -def cargo(args, remaining): - sys.exit(run(command + ['cargo'] + remaining or []).returncode) - -parser_cargo = subparsers.add_parser('cargo', help='run a cargo command') -parser_cargo.set_defaults(func=cargo) - -def sh(args, remaining): - sys.exit(run(command + ['bash']).returncode) - -parser_sh = subparsers.add_parser('sh', help='bring up a shell') -parser_sh.set_defaults(func=sh) - -def test(args, remaining): - sys.exit(run(command + ['cargo', 'test']).returncode) - -parser_test = subparsers.add_parser('test', help='run tests') -parser_test.set_defaults(func=test) - -if len(sys.argv) > 1: - args, remaining = parser.parse_known_args() - try: - args.func(args, remaining) - except FileNotFoundError: - sys.exit('Please install Docker.') -else: - parser.print_help() diff --git a/third_party/rust/strsim/src/lib.rs b/third_party/rust/strsim/src/lib.rs index 8c56843b3c31..480a64243ba5 100644 --- a/third_party/rust/strsim/src/lib.rs +++ b/third_party/rust/strsim/src/lib.rs @@ -1,29 +1,42 @@ //! This library implements string similarity metrics. +#![forbid(unsafe_code)] + use std::char; use std::cmp::{max, min}; use std::collections::HashMap; +use std::error::Error; +use std::fmt::{self, Display, Formatter}; +use std::hash::Hash; +use std::str::Chars; #[derive(Debug, PartialEq)] pub enum StrSimError { - DifferentLengthArgs + DifferentLengthArgs, } +impl Display for StrSimError { + fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { + let text = match self { + StrSimError::DifferentLengthArgs => "Differing length arguments provided", + }; + + write!(fmt, "{}", text) + } +} + +impl Error for StrSimError {} + pub type HammingResult = Result; -/// Calculates the number of positions in the two strings where the characters -/// differ. Returns an error if the strings have different lengths. -/// -/// ``` -/// use strsim::hamming; -/// -/// match hamming("hamming", "hammers") { -/// Ok(distance) => assert_eq!(3, distance), -/// Err(why) => panic!("{:?}", why) -/// } -/// ``` -pub fn hamming(a: &str, b: &str) -> HammingResult { - let (mut ita, mut itb, mut count) = (a.chars(), b.chars(), 0); +/// Calculates the number of positions in the two sequences where the elements +/// differ. Returns an error if the sequences have different lengths. +pub fn generic_hamming(a: Iter1, b: Iter2) -> HammingResult + where Iter1: IntoIterator, + Iter2: IntoIterator, + Elem1: PartialEq { + let (mut ita, mut itb) = (a.into_iter(), b.into_iter()); + let mut count = 0; loop { match (ita.next(), itb.next()){ (Some(x), Some(y)) => if x != y { count += 1 }, @@ -33,25 +46,37 @@ pub fn hamming(a: &str, b: &str) -> HammingResult { } } -/// Calculates the Jaro similarity between two strings. The returned value -/// is between 0.0 and 1.0 (higher value means more similar). +/// Calculates the number of positions in the two strings where the characters +/// differ. Returns an error if the strings have different lengths. /// /// ``` -/// use strsim::jaro; +/// use strsim::{hamming, StrSimError::DifferentLengthArgs}; /// -/// assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < -/// 0.001); +/// assert_eq!(Ok(3), hamming("hamming", "hammers")); +/// +/// assert_eq!(Err(DifferentLengthArgs), hamming("hamming", "ham")); /// ``` -pub fn jaro(a: &str, b: &str) -> f64 { - if a == b { return 1.0; } +pub fn hamming(a: &str, b: &str) -> HammingResult { + generic_hamming(a.chars(), b.chars()) +} - let a_len = a.chars().count(); - let b_len = b.chars().count(); +/// Calculates the Jaro similarity between two sequences. The returned value +/// is between 0.0 and 1.0 (higher value means more similar). +pub fn generic_jaro<'a, 'b, Iter1, Iter2, Elem1, Elem2>(a: &'a Iter1, b: &'b Iter2) -> f64 + where &'a Iter1: IntoIterator, + &'b Iter2: IntoIterator, + Elem1: PartialEq { + let a_len = a.into_iter().count(); + let b_len = b.into_iter().count(); // The check for lengths of one here is to prevent integer overflow when // calculating the search range. - if a_len == 0 || b_len == 0 || (a_len == 1 && b_len == 1) { + if a_len == 0 && b_len == 0 { + return 1.0; + } else if a_len == 0 || b_len == 0 { return 0.0; + } else if a_len == 1 && b_len == 1 { + return if a.into_iter().eq(b.into_iter()) { 1.0} else { 0.0 }; } let search_range = (max(a_len, b_len) / 2) - 1; @@ -65,7 +90,7 @@ pub fn jaro(a: &str, b: &str) -> f64 { let mut transpositions = 0.0; let mut b_match_index = 0; - for (i, a_char) in a.chars().enumerate() { + for (i, a_elem) in a.into_iter().enumerate() { let min_bound = // prevent integer wrapping if i > search_range { @@ -80,9 +105,9 @@ pub fn jaro(a: &str, b: &str) -> f64 { continue; } - for (j, b_char) in b.chars().enumerate() { - if min_bound <= j && j <= max_bound && a_char == b_char && - !b_consumed[j] { + for (j, b_elem) in b.into_iter().enumerate() { + if min_bound <= j && j <= max_bound && a_elem == b_elem && + !b_consumed[j] { b_consumed[j] = true; matches += 1.0; @@ -100,8 +125,55 @@ pub fn jaro(a: &str, b: &str) -> f64 { 0.0 } else { (1.0 / 3.0) * ((matches / a_len as f64) + - (matches / b_len as f64) + - ((matches - transpositions) / matches)) + (matches / b_len as f64) + + ((matches - transpositions) / matches)) + } +} + +struct StringWrapper<'a>(&'a str); + +impl<'a, 'b> IntoIterator for &'a StringWrapper<'b> { + type Item = char; + type IntoIter = Chars<'b>; + + fn into_iter(self) -> Self::IntoIter { + self.0.chars() + } +} + +/// Calculates the Jaro similarity between two strings. The returned value +/// is between 0.0 and 1.0 (higher value means more similar). +/// +/// ``` +/// use strsim::jaro; +/// +/// assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() < +/// 0.001); +/// ``` +pub fn jaro(a: &str, b: &str) -> f64 { + generic_jaro(&StringWrapper(a), &StringWrapper(b)) +} + +/// Like Jaro but gives a boost to sequences that have a common prefix. +pub fn generic_jaro_winkler<'a, 'b, Iter1, Iter2, Elem1, Elem2>(a: &'a Iter1, b: &'b Iter2) -> f64 + where &'a Iter1: IntoIterator, + &'b Iter2: IntoIterator, + Elem1: PartialEq { + let jaro_distance = generic_jaro(a, b); + + // Don't limit the length of the common prefix + let prefix_length = a.into_iter() + .zip(b.into_iter()) + .take_while(|&(ref a_elem, ref b_elem)| a_elem == b_elem) + .count(); + + let jaro_winkler_distance = + jaro_distance + (0.1 * prefix_length as f64 * (1.0 - jaro_distance)); + + if jaro_winkler_distance <= 1.0 { + jaro_winkler_distance + } else { + 1.0 } } @@ -114,22 +186,43 @@ pub fn jaro(a: &str, b: &str) -> f64 { /// 0.001); /// ``` pub fn jaro_winkler(a: &str, b: &str) -> f64 { - let jaro_distance = jaro(a, b); + generic_jaro_winkler(&StringWrapper(a), &StringWrapper(b)) +} - // Don't limit the length of the common prefix - let prefix_length = a.chars() - .zip(b.chars()) - .take_while(|&(a_char, b_char)| a_char == b_char) - .count(); +/// Calculates the minimum number of insertions, deletions, and substitutions +/// required to change one sequence into the other. +/// +/// ``` +/// use strsim::generic_levenshtein; +/// +/// assert_eq!(3, generic_levenshtein(&[1,2,3], &[1,2,3,4,5,6])); +/// ``` +pub fn generic_levenshtein<'a, 'b, Iter1, Iter2, Elem1, Elem2>(a: &'a Iter1, b: &'b Iter2) -> usize + where &'a Iter1: IntoIterator, + &'b Iter2: IntoIterator, + Elem1: PartialEq { + let b_len = b.into_iter().count(); - let jaro_winkler_distance = - jaro_distance + (0.1 * prefix_length as f64 * (1.0 - jaro_distance)); + if a.into_iter().next().is_none() { return b_len; } - if jaro_winkler_distance <= 1.0 { - jaro_winkler_distance - } else { - 1.0 + let mut cache: Vec = (1..b_len+1).collect(); + + let mut result = 0; + + for (i, a_elem) in a.into_iter().enumerate() { + result = i + 1; + let mut distance_b = i; + + for (j, b_elem) in b.into_iter().enumerate() { + let cost = if a_elem == b_elem { 0usize } else { 1usize }; + let distance_a = distance_b + cost; + distance_b = cache[j]; + result = min(result + 1, min(distance_a, distance_b + 1)); + cache[j] = result; + } } + + result } /// Calculates the minimum number of insertions, deletions, and substitutions @@ -141,34 +234,7 @@ pub fn jaro_winkler(a: &str, b: &str) -> f64 { /// assert_eq!(3, levenshtein("kitten", "sitting")); /// ``` pub fn levenshtein(a: &str, b: &str) -> usize { - if a == b { return 0; } - - let a_len = a.chars().count(); - let b_len = b.chars().count(); - - if a_len == 0 { return b_len; } - if b_len == 0 { return a_len; } - - let mut cache: Vec = (1..b_len+1).collect(); - - let mut result = 0; - let mut distance_a; - let mut distance_b; - - for (i, a_char) in a.chars().enumerate() { - result = i; - distance_b = i; - - for (j, b_char) in b.chars().enumerate() { - let cost = if a_char == b_char { 0 } else { 1 }; - distance_a = distance_b + cost; - distance_b = cache[j]; - result = min(result + 1, min(distance_a, distance_b + 1)); - cache[j] = result; - } - } - - result + generic_levenshtein(&StringWrapper(a), &StringWrapper(b)) } /// Calculates a normalized score of the Levenshtein algorithm between 0.0 and @@ -227,7 +293,7 @@ pub fn osa_distance(a: &str, b: &str) -> usize { min(prev_distances[j + 1] + 1, prev_distances[j] + cost)); if i > 0 && j > 0 && a_char != b_char && - a_char == prev_b_char && b_char == prev_a_char { + a_char == prev_b_char && b_char == prev_a_char { curr_distances[j + 1] = min(curr_distances[j + 1], prev_two_distances[j - 1] + 1); } @@ -244,6 +310,75 @@ pub fn osa_distance(a: &str, b: &str) -> usize { } +/* Returns the final index for a value in a single vector that represents a fixed + 2d grid */ +fn flat_index(i: usize, j: usize, width: usize) -> usize { + j * width + i +} + +/// Like optimal string alignment, but substrings can be edited an unlimited +/// number of times, and the triangle inequality holds. +/// +/// ``` +/// use strsim::generic_damerau_levenshtein; +/// +/// assert_eq!(2, generic_damerau_levenshtein(&[1,2], &[2,3,1])); +/// ``` +pub fn generic_damerau_levenshtein(a_elems: &[Elem], b_elems: &[Elem]) -> usize + where Elem: Eq + Hash + Clone { + let a_len = a_elems.len(); + let b_len = b_elems.len(); + + if a_len == 0 { return b_len; } + if b_len == 0 { return a_len; } + + let width = a_len + 2; + let mut distances = vec![0; (a_len + 2) * (b_len + 2)]; + let max_distance = a_len + b_len; + distances[0] = max_distance; + + for i in 0..(a_len + 1) { + distances[flat_index(i + 1, 0, width)] = max_distance; + distances[flat_index(i + 1, 1, width)] = i; + } + + for j in 0..(b_len + 1) { + distances[flat_index(0, j + 1, width)] = max_distance; + distances[flat_index(1, j + 1, width)] = j; + } + + let mut elems: HashMap = HashMap::with_capacity(64); + + for i in 1..(a_len + 1) { + let mut db = 0; + + for j in 1..(b_len + 1) { + let k = match elems.get(&b_elems[j - 1]) { + Some(&value) => value, + None => 0 + }; + + let insertion_cost = distances[flat_index(i, j + 1, width)] + 1; + let deletion_cost = distances[flat_index(i + 1, j, width)] + 1; + let transposition_cost = distances[flat_index(k, db, width)] + + (i - k - 1) + 1 + (j - db - 1); + + let mut substitution_cost = distances[flat_index(i, j, width)] + 1; + if a_elems[i - 1] == b_elems[j - 1] { + db = j; + substitution_cost -= 1; + } + + distances[flat_index(i + 1, j + 1, width)] = min(substitution_cost, + min(insertion_cost, min(deletion_cost, transposition_cost))); + } + + elems.insert(a_elems[i - 1].clone(), i); + } + + distances[flat_index(a_len + 1, b_len + 1, width)] +} + /// Like optimal string alignment, but substrings can be edited an unlimited /// number of times, and the triangle inequality holds. /// @@ -253,65 +388,8 @@ pub fn osa_distance(a: &str, b: &str) -> usize { /// assert_eq!(2, damerau_levenshtein("ab", "bca")); /// ``` pub fn damerau_levenshtein(a: &str, b: &str) -> usize { - if a == b { return 0; } - - let a_chars: Vec = a.chars().collect(); - let b_chars: Vec = b.chars().collect(); - let a_len = a_chars.len(); - let b_len = b_chars.len(); - - if a_len == 0 { return b_len; } - if b_len == 0 { return a_len; } - - let mut distances = vec![vec![0; b_len + 2]; a_len + 2]; - let max_distance = a_len + b_len; - distances[0][0] = max_distance; - - for i in 0..(a_len + 1) { - distances[i + 1][0] = max_distance; - distances[i + 1][1] = i; - } - - for j in 0..(b_len + 1) { - distances[0][j + 1] = max_distance; - distances[1][j + 1] = j; - } - - let mut chars: HashMap = HashMap::new(); - - for i in 1..(a_len + 1) { - let mut db = 0; - - for j in 1..(b_len + 1) { - let k = match chars.get(&b_chars[j - 1]) { - Some(value) => value.clone(), - None => 0 - }; - - let l = db; - - let mut cost = 1; - if a_chars[i - 1] == b_chars[j - 1] { - cost = 0; - db = j; - } - - let substitution_cost = distances[i][j] + cost; - let insertion_cost = distances[i][j + 1] + 1; - let deletion_cost = distances[i + 1][j] + 1; - let transposition_cost = distances[k][l] + (i - k - 1) + 1 + - (j - l - 1); - - distances[i + 1][j + 1] = min(substitution_cost, - min(insertion_cost, - min(deletion_cost, - transposition_cost))); - } - - chars.insert(a_chars[i - 1], i); - } - - distances[a_len + 1][b_len + 1] + let (x, y): (Vec<_>, Vec<_>) = (a.chars().collect(), b.chars().collect()); + generic_damerau_levenshtein(x.as_slice(), y.as_slice()) } /// Calculates a normalized score of the Damerau–Levenshtein algorithm between @@ -333,61 +411,133 @@ pub fn normalized_damerau_levenshtein(a: &str, b: &str) -> f64 { 1.0 - (damerau_levenshtein(a, b) as f64) / (a.chars().count().max(b.chars().count()) as f64) } +/// Returns an Iterator of char tuples. +fn bigrams(s: &str) -> impl Iterator + '_ { + s.chars().zip(s.chars().skip(1)) +} + + +/// Calculates a Sørensen-Dice similarity distance using bigrams. +/// See http://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient. +/// +/// ``` +/// use strsim::sorensen_dice; +/// +/// assert_eq!(1.0, sorensen_dice("", "")); +/// assert_eq!(0.0, sorensen_dice("", "a")); +/// assert_eq!(0.0, sorensen_dice("french", "quebec")); +/// assert_eq!(1.0, sorensen_dice("ferris", "ferris")); +/// assert_eq!(1.0, sorensen_dice("ferris", "ferris")); +/// assert_eq!(0.8888888888888888, sorensen_dice("feris", "ferris")); +/// ``` +pub fn sorensen_dice(a: &str, b: &str) -> f64 { + // implementation guided by + // https://github.com/aceakash/string-similarity/blob/f83ba3cd7bae874c20c429774e911ae8cff8bced/src/index.js#L6 + + let a: String = a.chars().filter(|&x| !char::is_whitespace(x)).collect(); + let b: String = b.chars().filter(|&x| !char::is_whitespace(x)).collect(); + + if a.len() == 0 && b.len() == 0 { + return 1.0; + } + + if a.len() == 0 || b.len() == 0 { + return 0.0; + } + + if a == b { + return 1.0; + } + + if a.len() == 1 && b.len() == 1 { + return 0.0; + } + + if a.len() < 2 || b.len() < 2 { + return 0.0; + } + + let mut a_bigrams: HashMap<(char, char), usize> = HashMap::new(); + + for bigram in bigrams(&a) { + *a_bigrams.entry(bigram).or_insert(0) += 1; + } + + let mut intersection_size = 0; + + for bigram in bigrams(&b) { + a_bigrams.entry(bigram).and_modify(|bi| { + if *bi > 0 { + *bi -= 1; + intersection_size += 1; + } + }); + } + + (2 * intersection_size) as f64 / (a.len() + b.len() - 2) as f64 +} + + #[cfg(test)] mod tests { use super::*; + #[test] + fn bigrams_iterator() { + let mut bi = bigrams("abcde"); + + assert_eq!(Some(('a', 'b')), bi.next()); + assert_eq!(Some(('b', 'c')), bi.next()); + assert_eq!(Some(('c', 'd')), bi.next()); + assert_eq!(Some(('d', 'e')), bi.next()); + assert_eq!(None, bi.next()); + } + + fn assert_hamming_dist(dist: usize, str1: &str, str2: &str) { + assert_eq!(Ok(dist), hamming(str1, str2)); + } + #[test] fn hamming_empty() { - match hamming("", "") { - Ok(distance) => { assert_eq!(0, distance); }, - Err(why) => { panic!("{:?}", why); } - } + assert_hamming_dist(0, "", "") } #[test] fn hamming_same() { - match hamming("hamming", "hamming") { - Ok(distance) => { assert_eq!(0, distance); }, - Err(why) => { panic!("{:?}", why); } - } + assert_hamming_dist(0, "hamming", "hamming") + } + + #[test] + fn hamming_numbers() { + assert_eq!(Ok(1), generic_hamming(&[1, 2, 4], &[1, 2, 3])); } #[test] fn hamming_diff() { - match hamming("hamming", "hammers") { - Ok(distance) => { assert_eq!(3, distance); }, - Err(why) => { panic!("{:?}", why); } - } + assert_hamming_dist(3, "hamming", "hammers") } #[test] fn hamming_diff_multibyte() { - match hamming("hamming", "h香mmüng") { - Ok(distance) => { assert_eq!(2, distance); }, - Err(why) => { panic!("{:?}", why); } - } + assert_hamming_dist(2, "hamming", "h香mmüng"); } #[test] fn hamming_unequal_length() { - match hamming("ham", "hamming") { - Ok(_) => { panic!(); }, - Err(why) => { assert_eq!(why, StrSimError::DifferentLengthArgs); } - } + assert_eq!( + Err(StrSimError::DifferentLengthArgs), + generic_hamming("ham".chars(), "hamming".chars()) + ); } #[test] fn hamming_names() { - match hamming("Friedrich Nietzs", "Jean-Paul Sartre") { - Ok(distance) => { assert_eq!(14, distance); }, - Err(why) => { panic!("{:?}", why); } - } + assert_hamming_dist(14, "Friedrich Nietzs", "Jean-Paul Sartre") } #[test] fn jaro_both_empty() { - assert_eq!(1.0, jaro("", "")); + assert_eq!(1.0, jaro("", "")); } #[test] @@ -421,6 +571,16 @@ mod tests { assert_eq!(0.0, jaro("a", "b")); } + #[test] + fn jaro_same_one_character() { + assert_eq!(1.0, jaro("a", "a")); + } + + #[test] + fn generic_jaro_diff() { + assert_eq!(0.0, generic_jaro(&[1, 2], &[3, 4])); + } + #[test] fn jaro_diff_one_and_two() { assert!((0.83 - jaro("a", "ab")).abs() < 0.01); @@ -470,9 +630,9 @@ mod tests { #[test] fn jaro_winkler_multibyte() { assert!((0.89 - jaro_winkler("testabctest", "testöঙ香test")).abs() < - 0.001); + 0.001); assert!((0.89 - jaro_winkler("testöঙ香test", "testabctest")).abs() < - 0.001); + 0.001); } #[test] @@ -486,6 +646,11 @@ mod tests { assert_eq!(0.0, jaro_winkler("a", "b")); } + #[test] + fn jaro_winkler_same_one_character() { + assert_eq!(1.0, jaro_winkler("a", "a")); + } + #[test] fn jaro_winkler_diff_no_transposition() { assert!((0.840 - jaro_winkler("dwayne", "duane")).abs() < 0.001); @@ -505,7 +670,7 @@ mod tests { #[test] fn jaro_winkler_long_prefix() { assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() < - 0.001); + 0.001); } #[test] @@ -522,7 +687,7 @@ mod tests { fn jaro_winkler_very_long_prefix() { assert!((1.0 - jaro_winkler("thequickbrownfoxjumpedoverx", "thequickbrownfoxjumpedovery")).abs() < - 0.001); + 0.001); } #[test] @@ -783,4 +948,58 @@ mod tests { fn normalized_damerau_levenshtein_identical_strings() { assert!((normalized_damerau_levenshtein("sunglasses", "sunglasses") - 1.0).abs() < 0.00001); } + + #[test] + fn sorensen_dice_all() { + // test cases taken from + // https://github.com/aceakash/string-similarity/blob/f83ba3cd7bae874c20c429774e911ae8cff8bced/src/spec/index.spec.js#L11 + + assert_eq!(1.0, sorensen_dice("a", "a")); + assert_eq!(0.0, sorensen_dice("a", "b")); + assert_eq!(1.0, sorensen_dice("", "")); + assert_eq!(0.0, sorensen_dice("a", "")); + assert_eq!(0.0, sorensen_dice("", "a")); + assert_eq!(1.0, sorensen_dice("apple event", "apple event")); + assert_eq!(0.9090909090909091, sorensen_dice("iphone", "iphone x")); + assert_eq!(0.0, sorensen_dice("french", "quebec")); + assert_eq!(1.0, sorensen_dice("france", "france")); + assert_eq!(0.2, sorensen_dice("fRaNce", "france")); + assert_eq!(0.8, sorensen_dice("healed", "sealed")); + assert_eq!( + 0.7878787878787878, + sorensen_dice("web applications", "applications of the web") + ); + assert_eq!( + 0.92, + sorensen_dice( + "this will have a typo somewhere", + "this will huve a typo somewhere" + ) + ); + assert_eq!( + 0.6060606060606061, + sorensen_dice( + "Olive-green table for sale, in extremely good condition.", + "For sale: table in very good condition, olive green in colour." + ) + ); + assert_eq!( + 0.2558139534883721, + sorensen_dice( + "Olive-green table for sale, in extremely good condition.", + "For sale: green Subaru Impreza, 210,000 miles" + ) + ); + assert_eq!( + 0.1411764705882353, + sorensen_dice( + "Olive-green table for sale, in extremely good condition.", + "Wanted: mountain bike with at least 21 gears." + ) + ); + assert_eq!( + 0.7741935483870968, + sorensen_dice("this has one extra word", "this has one word") + ); + } } diff --git a/third_party/rust/term_size/.cargo-checksum.json b/third_party/rust/term_size/.cargo-checksum.json deleted file mode 100644 index 09c0e2ba21de..000000000000 --- a/third_party/rust/term_size/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"2e79b4ec647d88e4a6e217f522c490b2aea05e0b86b150d9e2e3635b52eab017","CONTRIBUTORS.md":"fec990280aad6c99316b11a69f7f560fbdf722b5e83d9743449127e8f3d5499b","Cargo.toml":"f4d49e94f37eb7ef4b47037f672264609476d9853fcf2570789a0d0179734e64","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"a11941d4b2711fb88f456896e97dc5a0178325e9c3248219f05906aeb8272c96","rustfmt.toml":"8fd2d63119df515fd5f44e530c709b19d66b09fbc2e22a640bf4b64c57e7d6b3","src/lib.rs":"71fc49a192cd5217acc479f04764fcafaf9e8b5ad99fe1ab00344695dede06e1","src/platform/mod.rs":"028ee9592f11bed14baef659f095dd2cc274070c614a15c17dc11a2991e647f5","src/platform/unix.rs":"70ade01444b8f9b669cb05e8db4517f592056f15714a1dddde47d28c8e479da0","src/platform/unsupported.rs":"805ed15a9cdfe50c608795764b217e1cf7bfd26a35faa229bbbb7fdada1c252c","src/platform/windows.rs":"1a067603df6e06479bafd1c938b2d2147094767149769b16a57a3f637d33fc31"},"package":"1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"} \ No newline at end of file diff --git a/third_party/rust/term_size/CHANGELOG.md b/third_party/rust/term_size/CHANGELOG.md deleted file mode 100644 index a2ada87b1532..000000000000 --- a/third_party/rust/term_size/CHANGELOG.md +++ /dev/null @@ -1,78 +0,0 @@ - -## v1.0.0-beta1 (2017-12-07) - - -#### Documentation - -* updates the docs and copyright notices for 1.0 by adding examples sections ([86819dc5](https://github.com/kbknapp/term_size-rs/commit/86819dc5f1f80f3d9172bf3fa70781294762252e)) -* adds a CONTRIBUTORS.md file and just target to update it ([36d82b7a](https://github.com/kbknapp/term_size-rs/commit/36d82b7a094e02eb76d26bb987a53ac85f3dc407)) -* **README.md:** updates the docs location to point to docs.rs ([0f4160fc](https://github.com/kbknapp/term_size-rs/commit/0f4160fc37c2311ff2e02f97cb252b2d09a87629)) - -#### Features - -* allows getting the terminal size of all standard streams, or just particular ones ([19f5b91e](https://github.com/kbknapp/term_size-rs/commit/19f5b91eed0b6486983b80fe713ad18e34afb70a)) - - -## (2020-05-02) - - -#### Features - -* allows getting the terminal size of all standard streams, or just particular ones ([19f5b91e](https://github.com/kbknapp/term_size-rs/commit/19f5b91eed0b6486983b80fe713ad18e34afb70a)) - -#### Documentation - -* updates the docs and copyright notices for 1.0 by adding examples sections ([86819dc5](https://github.com/kbknapp/term_size-rs/commit/86819dc5f1f80f3d9172bf3fa70781294762252e)) -* adds a CONTRIBUTORS.md file and just target to update it ([36d82b7a](https://github.com/kbknapp/term_size-rs/commit/36d82b7a094e02eb76d26bb987a53ac85f3dc407)) -* **README.md:** - * updates the readme with minimum version of Rust and Breaking Changes policies ([e99990e8](https://github.com/kbknapp/term_size-rs/commit/e99990e89622e988865f16b308571e35f7b39d01)) - * updates the docs location to point to docs.rs ([0f4160fc](https://github.com/kbknapp/term_size-rs/commit/0f4160fc37c2311ff2e02f97cb252b2d09a87629)) - - -## v0.3.0 (2017-04-09) - - -#### Features - -* allows getting the terminal size of all standard streams, or just particular ones ([c7095c95](https://github.com/kbknapp/term_size-rs/commit/c7095c95d633e0a36ea78434bc83349a9711a187)) - - - - -### v0.2.3 (2017-02-21) - -#### Bug Fixes - -* Moves the code into distinct modules and adds dummy functions for unsupported platforms - - - -### v0.2.2 (2017-01-29) - -* Updates deps `libc` and `clippy` - - -### v0.2.1 (2016-09-05) - - -#### Bug Fixes - -* uses libc::winsize instead of homegrown ([216986ec](https://github.com/kbknapp/term_size-rs/commit/216986ecdbe528523953a1cde4cf6c329a0f4fbc), closes [#6](https://github.com/kbknapp/term_size-rs/issues/6)) - - - - -v0.2.0 -## v0.2.0 (2016-09-05) - -#### Features - -* adds support for Windows ([f181c99](https://github.com/kbknapp/term_size-rs/commit/f181c99c0c306b711952a2a4053df904e851413f)) - -#### Documentation - -* **README.md:** - * fixes documentation link ([ca06bf13](https://github.com/kbknapp/term_size-rs/commit/ca06bf132948559032853addd9aa0af022a126e9)) - * minor fixups ([1c269046](https://github.com/kbknapp/term_size-rs/commit/1c2690462b1b1db58d46395c6f1cf098dd769e18)) - - diff --git a/third_party/rust/term_size/CONTRIBUTORS.md b/third_party/rust/term_size/CONTRIBUTORS.md deleted file mode 100644 index 43d92f4248cb..000000000000 --- a/third_party/rust/term_size/CONTRIBUTORS.md +++ /dev/null @@ -1,11 +0,0 @@ -the following is a list of contributors: - - -[kbknapp](https://github.com/kbknapp) |[nabijaczleweli](https://github.com/nabijaczleweli) |[vorner](https://github.com/vorner) |[nbaksalyar](https://github.com/nbaksalyar) |[kaegi](https://github.com/kaegi) | -:---: |:---: |:---: |:---: |:---: | -[kbknapp](https://github.com/kbknapp) |[nabijaczleweli](https://github.com/nabijaczleweli) |[vorner](https://github.com/vorner) |[nbaksalyar](https://github.com/nbaksalyar) |[kaegi](https://github.com/kaegi) | - - - - -This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list) diff --git a/third_party/rust/term_size/Cargo.toml b/third_party/rust/term_size/Cargo.toml deleted file mode 100644 index 549f5d67cbea..000000000000 --- a/third_party/rust/term_size/Cargo.toml +++ /dev/null @@ -1,72 +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 = "term_size" -version = "0.3.2" -authors = ["Kevin K. ", "Benjamin Sago "] -exclude = ["/.clog.toml", "/.travis.yml", "/appveyor.yml", "/index.html", "/justfile"] -description = "functions for determining terminal sizes and dimensions" -documentation = "https://docs.rs/term_size/" -readme = "README.md" -keywords = ["term", "terminal", "size", "width", "dimension"] -categories = ["command-line-interface"] -license = "MIT/Apache-2.0" -repository = "https://github.com/kbknapp/term_size-rs.git" -[profile.bench] -opt-level = 3 -lto = true -debug = false -debug-assertions = false -rpath = false - -[profile.dev] -opt-level = 0 -lto = false -codegen-units = 4 -debug = true -debug-assertions = true -rpath = false - -[profile.release] -opt-level = 3 -lto = true -debug = false -debug-assertions = false -rpath = false - -[profile.test] -opt-level = 1 -lto = false -codegen-units = 2 -debug = true -debug-assertions = true -rpath = false - -[dependencies] - -[features] -debug = [] -default = [] -nightly = [] -travis = ["nightly"] -unstable = [] -[target."cfg(not(target_os = \"windows\"))".dependencies.libc] -version = "0.2.20" -[target."cfg(target_os = \"windows\")".dependencies.winapi] -version = "0.3" -features = ["wincon", "processenv", "winbase"] -[badges.appveyor] -repository = "kbknapp/term_size-rs" - -[badges.travis-ci] -repository = "kbknapp/term_size-rs" diff --git a/third_party/rust/term_size/LICENSE-APACHE b/third_party/rust/term_size/LICENSE-APACHE deleted file mode 100644 index 16fe87b06e80..000000000000 --- a/third_party/rust/term_size/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/third_party/rust/term_size/README.md b/third_party/rust/term_size/README.md deleted file mode 100644 index 1208832f932c..000000000000 --- a/third_party/rust/term_size/README.md +++ /dev/null @@ -1,77 +0,0 @@ -term_size -==== - -[![Crates.io](https://img.shields.io/crates/v/term_size.svg)](https://crates.io/crates/term_size) [![Crates.io](https://img.shields.io/crates/d/term_size.svg)](https://crates.io/crates/term_size) [![license](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kbknapp/term_size-rs/blob/master/LICENSE-MIT) [![license](http://img.shields.io/badge/license-Apache2.0-blue.svg)](https://github.com/kbknapp/term_size-rs/blob/master/LICENSE-APACHE) [![Coverage Status](https://coveralls.io/repos/kbknapp/term_size-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/kbknapp/term_size-rs?branch=master) [![Join the chat at https://gitter.im/kbknapp/term_size-rs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kbknapp/term_size-rs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -Linux: [![Build Status](https://travis-ci.org/clap-rs/term_size-rs.svg?branch=master)](https://travis-ci.org/clap-rs/term_size-rs) -Windows: [![Build status](https://ci.appveyor.com/api/projects/status/6q0x4h6i0e3ypbm5?svg=true -)](https://ci.appveyor.com/project/kbknapp/term_size-rs/branch/master) - -A Rust library to enable getting terminal sizes and dimensions - -[Documentation](https://docs.rs/term_size) - -## Usage - -First, add the following to your `Cargo.toml`: - -```toml -[dependencies] -term_size = "1" -``` - -Next, add this to your crate root: - -```rust -extern crate term_size; -``` - -To get the dimensions of your terminal window, simply use the following: - -```rust -fn main() { - if let Some((w, h)) = term_size::dimensions() { - println!("Width: {}\nHeight: {}", w, h); - } else { - println!("Unable to get term size :(") - } -} -``` - -## License - -Copyright Benjamin Sago, Kevin Knapp, and `term_size` contributors. - -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. 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. - -## Contributing - -1. Fork it! -2. Create your feature branch: `git checkout -b my-new-feature` -3. Commit your changes: `git commit -am 'Add some feature'` -4. Push to the branch: `git push origin my-new-feature` -5. Submit a pull request :D - -## Minimum Version of Rust - -`term_size` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.22.1, meaning `term_size` is guaranteed to compile with 1.20.0 and newer. - -At the 1.23.0 stable release, `term_size` will be guaranteed to compile with 1.21.0 and newer, etc. - -Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it must be clearly annotated in the [`CHANGELOG.md`](./CHANGELOG.md) - -## Breaking Changes - -`term_size` takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions: - -* The breaking change is to fix a security concern -* The breaking change is to be fixing a bug (i.e. relying on a bug as a feature) -* The breaking change is a feature isn't used in the wild, or all users of said feature have given approval prior to the change diff --git a/third_party/rust/term_size/rustfmt.toml b/third_party/rust/term_size/rustfmt.toml deleted file mode 100644 index 0136d86e3137..000000000000 --- a/third_party/rust/term_size/rustfmt.toml +++ /dev/null @@ -1,4 +0,0 @@ -format_strings = false -chain_overflow_last = false -same_line_if_else = true -fn_single_line = true diff --git a/third_party/rust/term_size/src/lib.rs b/third_party/rust/term_size/src/lib.rs deleted file mode 100644 index faa2bcd0e148..000000000000 --- a/third_party/rust/term_size/src/lib.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright ⓒ 2015-2017 Benjamin Sago, Kevin Knapp, and [`term_size` contributors.](https://github.com/kbknapp/term_size-rs/blob/master/CONTRIBUTORS.md). -// -// 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. Unless specifically stated otherwise, all contributions will be licensed in the same manner. - -// The following was originally taken and adapated from exa source -// repo: https://github.com/ogham/exa -// commit: b9eb364823d0d4f9085eb220233c704a13d0f611 -// license: MIT - Copyright (c) 2014 Benjamin Sago - -//! System calls for getting the terminal size. -//! -//! Getting the terminal size is performed using an ioctl command that takes -//! the file handle to the terminal -- which in this case, is stdout -- and -//! populates a structure containing the values. -//! -//! The size is needed when the user wants the output formatted into columns: -//! the default grid view, or the hybrid grid-details view. -//! -//! # Example -//! -//! To get the dimensions of your terminal window, simply use the following: -//! -//! ```no_run -//! # use term_size; -//! if let Some((w, h)) = term_size::dimensions() { -//! println!("Width: {}\nHeight: {}", w, h); -//! } else { -//! println!("Unable to get term size :(") -//! } -//! ``` -#![doc(html_root_url = "https://docs.rs/term_size/1.0.0-beta1")] -#![deny( - missing_docs, - missing_debug_implementations, - missing_copy_implementations, - trivial_casts, - unused_import_braces, - unused_allocation, - unused_qualifications, - trivial_numeric_casts -)] -#![cfg_attr(not(feature = "nightly"), forbid(unstable_features))] - -#[cfg(not(target_os = "windows"))] -extern crate libc; -#[cfg(target_os = "windows")] -extern crate winapi; - -// A facade to allow exposing functions depending on the platform -mod platform; -pub use platform::{dimensions, dimensions_stderr, dimensions_stdin, dimensions_stdout}; diff --git a/third_party/rust/term_size/src/platform/mod.rs b/third_party/rust/term_size/src/platform/mod.rs deleted file mode 100644 index d5f06d838069..000000000000 --- a/third_party/rust/term_size/src/platform/mod.rs +++ /dev/null @@ -1,54 +0,0 @@ - -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios", - target_os = "bitrig", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] -mod unix; -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios", - target_os = "bitrig", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] -pub use self::unix::{dimensions, dimensions_stdout, dimensions_stdin, dimensions_stderr}; - -#[cfg(target_os = "windows")] -mod windows; -#[cfg(target_os = "windows")] -pub use self::windows::{dimensions, dimensions_stdout, dimensions_stdin, dimensions_stderr}; - -// makes project compilable on unsupported platforms -#[cfg(not(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios", - target_os = "bitrig", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris", - target_os = "windows")))] -mod unsupported; -#[cfg(not(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios", - target_os = "bitrig", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris", - target_os = "windows")))] -pub use self::unsupported::{dimensions, dimensions_stdout, dimensions_stdin, dimensions_stderr}; \ No newline at end of file diff --git a/third_party/rust/term_size/src/platform/unix.rs b/third_party/rust/term_size/src/platform/unix.rs deleted file mode 100644 index e3a9f2dcca80..000000000000 --- a/third_party/rust/term_size/src/platform/unix.rs +++ /dev/null @@ -1,203 +0,0 @@ - -use libc::{STDOUT_FILENO, STDIN_FILENO, STDERR_FILENO, c_int, c_ulong, winsize}; -use std::mem::zeroed; - -// Unfortunately the actual command is not standardised... -#[cfg(any(target_os = "linux", target_os = "android"))] -static TIOCGWINSZ: c_ulong = 0x5413; - -#[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "bitrig", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd"))] -static TIOCGWINSZ: c_ulong = 0x40087468; - -#[cfg(target_os = "solaris")] -static TIOCGWINSZ: c_ulong = 0x5468; - -extern "C" { - fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int; -} - -/// Runs the ioctl command. Returns (0, 0) if all of the streams are not to a terminal, or -/// there is an error. (0, 0) is an invalid size to have anyway, which is why -/// it can be used as a nil value. -unsafe fn get_dimensions_any() -> winsize { - let mut window: winsize = zeroed(); - let mut result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window); - - if result == -1 { - window = zeroed(); - result = ioctl(STDIN_FILENO, TIOCGWINSZ, &mut window); - if result == -1 { - window = zeroed(); - result = ioctl(STDERR_FILENO, TIOCGWINSZ, &mut window); - if result == -1 { - return zeroed(); - } - } - } - window -} - -/// Runs the ioctl command. Returns (0, 0) if the output is not to a terminal, or -/// there is an error. (0, 0) is an invalid size to have anyway, which is why -/// it can be used as a nil value. -unsafe fn get_dimensions_out() -> winsize { - let mut window: winsize = zeroed(); - let result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window); - - if result != -1 { - return window; - } - zeroed() -} - -/// Runs the ioctl command. Returns (0, 0) if the input is not to a terminal, or -/// there is an error. (0, 0) is an invalid size to have anyway, which is why -/// it can be used as a nil value. -unsafe fn get_dimensions_in() -> winsize { - let mut window: winsize = zeroed(); - let result = ioctl(STDIN_FILENO, TIOCGWINSZ, &mut window); - - if result != -1 { - return window; - } - zeroed() -} - -/// Runs the ioctl command. Returns (0, 0) if the error is not to a terminal, or -/// there is an error. (0, 0) is an invalid size to have anyway, which is why -/// it can be used as a nil value. -unsafe fn get_dimensions_err() -> winsize { - let mut window: winsize = zeroed(); - let result = ioctl(STDERR_FILENO, TIOCGWINSZ, &mut window); - - if result != -1 { - return window; - } - zeroed() -} - -/// Query the current processes's output (`stdout`), input (`stdin`), and error (`stderr`) in -/// that order, in the attempt to determine terminal width. If one of those streams is actually -/// a tty, this function returns its width and height as a number of characters. -/// -/// # Errors -/// -/// If *all* of the streams are not ttys or return any errors this function will return `None`. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions() -> Option<(usize, usize)> { - let w = unsafe { get_dimensions_any() }; - - if w.ws_col == 0 || w.ws_row == 0 { - None - } else { - Some((w.ws_col as usize, w.ws_row as usize)) - } -} - -/// Query the current processes's output (`stdout`) *only*, in the attempt to determine -/// terminal width. If that stream is actually a tty, this function returns its width -/// and height as a number of characters. -/// -/// # Errors -/// -/// If the stream is not a tty or return any errors this function will return `None`. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions_stdout() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions_stdout() -> Option<(usize, usize)> { - let w = unsafe { get_dimensions_out() }; - - if w.ws_col == 0 || w.ws_row == 0 { - None - } else { - Some((w.ws_col as usize, w.ws_row as usize)) - } -} - -/// Query the current processes's input (`stdin`) *only*, in the attempt to determine -/// terminal width. If that stream is actually a tty, this function returns its width -/// and height as a number of characters. -/// -/// # Errors -/// -/// If the stream is not a tty or return any errors this function will return `None`. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions_stdin() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions_stdin() -> Option<(usize, usize)> { - let w = unsafe { get_dimensions_in() }; - - if w.ws_col == 0 || w.ws_row == 0 { - None - } else { - Some((w.ws_col as usize, w.ws_row as usize)) - } -} - -/// Query the current processes's error output (`stderr`) *only*, in the attempt to determine -/// terminal width. If that stream is actually a tty, this function returns its width -/// and height as a number of characters. -/// -/// # Errors -/// -/// If the stream is not a tty or return any errors this function will return `None`. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions_stderr() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions_stderr() -> Option<(usize, usize)> { - let w = unsafe { get_dimensions_err() }; - - if w.ws_col == 0 || w.ws_row == 0 { - None - } else { - Some((w.ws_col as usize, w.ws_row as usize)) - } -} \ No newline at end of file diff --git a/third_party/rust/term_size/src/platform/unsupported.rs b/third_party/rust/term_size/src/platform/unsupported.rs deleted file mode 100644 index de998e968d68..000000000000 --- a/third_party/rust/term_size/src/platform/unsupported.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub fn dimensions() -> Option<(usize, usize)> { None } -pub fn dimensions_stdout() -> Option<(usize, usize)> { None } -pub fn dimensions_stdin() -> Option<(usize, usize)> { None } -pub fn dimensions_stderr() -> Option<(usize, usize)> { None } diff --git a/third_party/rust/term_size/src/platform/windows.rs b/third_party/rust/term_size/src/platform/windows.rs deleted file mode 100644 index 0efdb283c3dc..000000000000 --- a/third_party/rust/term_size/src/platform/windows.rs +++ /dev/null @@ -1,86 +0,0 @@ -use winapi::um::processenv::GetStdHandle; -use winapi::um::winbase::STD_OUTPUT_HANDLE; -use winapi::um::wincon::GetConsoleScreenBufferInfo; -use winapi::um::wincon::{CONSOLE_SCREEN_BUFFER_INFO, COORD, SMALL_RECT}; - -/// Query the current processes's output, returning its width and height as a -/// number of characters. -/// -/// # Errors -/// -/// Returns `None` if the output isn't to a terminal. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions() -> Option<(usize, usize)> { - let null_coord = COORD { X: 0, Y: 0 }; - let null_smallrect = SMALL_RECT { - Left: 0, - Top: 0, - Right: 0, - Bottom: 0, - }; - - let stdout_h = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }; - let mut console_data = CONSOLE_SCREEN_BUFFER_INFO { - dwSize: null_coord, - dwCursorPosition: null_coord, - wAttributes: 0, - srWindow: null_smallrect, - dwMaximumWindowSize: null_coord, - }; - - if unsafe { GetConsoleScreenBufferInfo(stdout_h, &mut console_data) } != 0 { - Some(((console_data.srWindow.Right - console_data.srWindow.Left + 1) as usize, - (console_data.srWindow.Bottom - console_data.srWindow.Top + 1) as usize)) - } else { - None - } -} - -/// Query the current processes's output, returning its width and height as a -/// number of characters. Returns `None` if the output isn't to a terminal. -/// -/// # Errors -/// -/// Returns `None` if the output isn't to a terminal. -/// -/// # Example -/// -/// To get the dimensions of your terminal window, simply use the following: -/// -/// ```no_run -/// # use term_size; -/// if let Some((w, h)) = term_size::dimensions() { -/// println!("Width: {}\nHeight: {}", w, h); -/// } else { -/// println!("Unable to get term size :(") -/// } -/// ``` -pub fn dimensions_stdout() -> Option<(usize, usize)> { dimensions() } - -/// This isn't implemented for Windows -/// -/// # Panics -/// -/// This function `panic!`s unconditionally with the `unimplemented!` -/// macro -pub fn dimensions_stdin() -> Option<(usize, usize)> { unimplemented!() } - -/// This isn't implemented for Windows -/// -/// # Panics -/// -/// This function `panic!`s unconditionally with the `unimplemented!` -/// macro -pub fn dimensions_stderr() -> Option<(usize, usize)> { unimplemented!() } diff --git a/third_party/rust/terminal_size/.cargo-checksum.json b/third_party/rust/terminal_size/.cargo-checksum.json new file mode 100644 index 000000000000..1f23934120fd --- /dev/null +++ b/third_party/rust/terminal_size/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"8d2028e8eb1b95d30a7809bf1aebfc474f13aee76f2a505fc7d9e32b97da9fe1","Cargo.toml":"26630191b28b81be8e6d692f032c8e8e62c4d4c977e7a4df1473d7477f39f02c","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"bc8dcbbd559a61b8a8c0c89d5c3e15d0dc47c6fae94e78ac428d6a7b7da3c4f9","README.md":"d9b142c504cd57f8c93575baab35e4ec63520597adb1bbaedcc14840b3e8e63b","examples/get_size.rs":"11527a87b817e8e7f1c3920497920869e049660f6f89bb786f2758571c07c491","src/lib.rs":"2d43d3f8bee8ef9694bf1033b1a1522bce03485176ffd4d2f7e61e94ba2efe76","src/unix.rs":"0cbfff1bac23daea7432961d443cf788b50e2f03683b1bc75381595d72903e0b","src/windows.rs":"930729ab4cccd97f8e4932a10c6ade43dce43a5838d57a4ee6067f316e56e1d8"},"package":"633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df"} \ No newline at end of file diff --git a/third_party/rust/terminal_size/Cargo.lock b/third_party/rust/terminal_size/Cargo.lock new file mode 100644 index 000000000000..2665711e6b7c --- /dev/null +++ b/third_party/rust/terminal_size/Cargo.lock @@ -0,0 +1,39 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "libc" +version = "0.2.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18794a8ad5b29321f790b55d93dfba91e125cb1a9edbd4f8e3150acc771c1a5e" + +[[package]] +name = "terminal_size" +version = "0.1.17" +dependencies = [ + "libc", + "winapi", +] + +[[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/third_party/rust/terminal_size/Cargo.toml b/third_party/rust/terminal_size/Cargo.toml new file mode 100644 index 000000000000..d8921879d503 --- /dev/null +++ b/third_party/rust/terminal_size/Cargo.toml @@ -0,0 +1,27 @@ +# 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 = "terminal_size" +version = "0.1.17" +authors = ["Andrew Chin "] +description = "Gets the size of your Linux or Windows terminal" +documentation = "http://eminence.github.io/terminal-size/doc/terminal_size/index.html" +keywords = ["terminal", "console", "term", "size", "dimensions"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/eminence/terminal-size" +[target."cfg(not(windows))".dependencies.libc] +version = "0.2" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["handleapi", "processenv", "winbase", "wincon", "winnt"] diff --git a/third_party/rust/terminal_size/LICENSE-APACHE b/third_party/rust/terminal_size/LICENSE-APACHE new file mode 100644 index 000000000000..8f71f43fee3f --- /dev/null +++ b/third_party/rust/terminal_size/LICENSE-APACHE @@ -0,0 +1,202 @@ + 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/third_party/rust/terminal_size/LICENSE-MIT b/third_party/rust/terminal_size/LICENSE-MIT new file mode 100644 index 000000000000..a05bf276d154 --- /dev/null +++ b/third_party/rust/terminal_size/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2015 The terminal-size 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/third_party/rust/terminal_size/README.md b/third_party/rust/terminal_size/README.md new file mode 100644 index 000000000000..bcaee60a36d7 --- /dev/null +++ b/third_party/rust/terminal_size/README.md @@ -0,0 +1,41 @@ +terminal-size +============= + + +[Documention](https://docs.rs/crate/terminal_size) + + +Rust library to getting the size of your terminal. + +Works on Linux, MacOS, Windows, and illumos. + +```rust +use terminal_size::{Width, Height, terminal_size}; + +let size = terminal_size(); +if let Some((Width(w), Height(h))) = size { + println!("Your terminal is {} cols wide and {} lines tall", w, h); +} else { + println!("Unable to get terminal size"); +} +``` + +## Minimum Rust Version + +This crate requires a minimum rust version of 1.31.0 (2018-12-06) + +## 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/third_party/rust/terminal_size/examples/get_size.rs b/third_party/rust/terminal_size/examples/get_size.rs new file mode 100644 index 000000000000..155784d98ef0 --- /dev/null +++ b/third_party/rust/terminal_size/examples/get_size.rs @@ -0,0 +1,49 @@ +#[cfg(windows)] +fn run() { + use std::os::windows::io::RawHandle; + use winapi::um::processenv::GetStdHandle; + use winapi::um::winbase::{STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE}; + + let stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) } as RawHandle; + println!( + "Size from terminal_size_using_handle(stdout): {:?}", + terminal_size::terminal_size_using_handle(stdout) + ); + + let stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) } as RawHandle; + println!( + "Size from terminal_size_using_handle(stderr): {:?}", + terminal_size::terminal_size_using_handle(stderr) + ); + + let stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) } as RawHandle; + println!( + "Size from terminal_size_using_handle(stdin): {:?}", + terminal_size::terminal_size_using_handle(stdin) + ); +} + +#[cfg(not(windows))] +fn run() { + println!( + "Size from terminal_size_using_fd(stdout): {:?}", + terminal_size::terminal_size_using_fd(libc::STDOUT_FILENO) + ); + println!( + "Size from terminal_size_using_fd(stderr): {:?}", + terminal_size::terminal_size_using_fd(libc::STDERR_FILENO) + ); + println!( + "Size from terminal_size_using_fd(stdin): {:?}", + terminal_size::terminal_size_using_fd(libc::STDIN_FILENO) + ); +} + +fn main() { + println!( + "Size from terminal_size(): {:?}", + terminal_size::terminal_size() + ); + + run(); +} diff --git a/third_party/rust/terminal_size/src/lib.rs b/third_party/rust/terminal_size/src/lib.rs new file mode 100644 index 000000000000..6ef79be4a8e2 --- /dev/null +++ b/third_party/rust/terminal_size/src/lib.rs @@ -0,0 +1,37 @@ +//! A simple utility for getting the size of a terminal. +//! +//! Supports both Linux, MacOS, and Windows. +//! +//! This crate requires a minimum rust version of 1.31.0 (2018-12-06) +//! +//! # Example +//! +//! ``` +//! use terminal_size::{Width, Height, terminal_size}; +//! +//! let size = terminal_size(); +//! if let Some((Width(w), Height(h))) = size { +//! println!("Your terminal is {} cols wide and {} lines tall", w, h); +//! } else { +//! println!("Unable to get terminal size"); +//! } +//! ``` +//! + +#[derive(Debug)] +pub struct Width(pub u16); +#[derive(Debug)] +pub struct Height(pub u16); + +#[cfg(unix)] +mod unix; +#[cfg(unix)] +pub use crate::unix::{terminal_size, terminal_size_using_fd}; + +#[cfg(windows)] +mod windows; +#[cfg(windows)] +pub use crate::windows::{terminal_size, terminal_size_using_handle}; + +#[cfg(not(any(unix, windows)))] +pub fn terminal_size() -> Option<(Width, Height)> { None } diff --git a/third_party/rust/terminal_size/src/unix.rs b/third_party/rust/terminal_size/src/unix.rs new file mode 100644 index 000000000000..59ac2768c8da --- /dev/null +++ b/third_party/rust/terminal_size/src/unix.rs @@ -0,0 +1,117 @@ +use super::{Height, Width}; +use std::os::unix::io::RawFd; + +/// Returns the size of the terminal defaulting to STDOUT, if available. +/// +/// If STDOUT is not a tty, returns `None` +pub fn terminal_size() -> Option<(Width, Height)> { + terminal_size_using_fd(libc::STDOUT_FILENO) +} + +/// Returns the size of the terminal using the given file descriptor, if available. +/// +/// If the given file descriptor is not a tty, returns `None` +pub fn terminal_size_using_fd(fd: RawFd) -> Option<(Width, Height)> { + use libc::ioctl; + use libc::isatty; + use libc::{winsize as WinSize, TIOCGWINSZ}; + let is_tty: bool = unsafe { isatty(fd) == 1 }; + + if !is_tty { + return None; + } + + let mut winsize = WinSize { + ws_row: 0, + ws_col: 0, + ws_xpixel: 0, + ws_ypixel: 0, + }; + + if unsafe { ioctl(fd, TIOCGWINSZ.into(), &mut winsize) } == -1 { + return None; + } + + let rows = winsize.ws_row; + let cols = winsize.ws_col; + + if rows > 0 && cols > 0 { + Some((Width(cols), Height(rows))) + } else { + None + } +} + +#[test] +/// Compare with the output of `stty size` +fn compare_with_stty() { + use std::process::Command; + use std::process::Stdio; + + let (rows, cols) = if cfg!(target_os = "illumos") { + // illumos stty(1) does not accept a device argument, instead using + // stdin unconditionally: + let output = Command::new("stty") + .stdin(Stdio::inherit()) + .output() + .unwrap(); + assert!(output.status.success()); + + // stdout includes the row and columns thus: "rows = 80; columns = 24;" + let vals = String::from_utf8(output.stdout) + .unwrap() + .lines() + .map(|line| { + // Split each line on semicolons to get "k = v" strings: + line.split(';') + .map(str::trim) + .map(str::to_string) + .collect::>() + }) + .flatten() + .filter_map(|term| { + // split each "k = v" string and look for rows/columns: + match term.splitn(2, " = ").collect::>().as_slice() { + ["rows", n] | ["columns", n] => Some(n.parse().unwrap()), + _ => None, + } + }) + .collect::>(); + (vals[0], vals[1]) + } else { + let output = if cfg!(target_os = "linux") { + Command::new("stty") + .arg("size") + .arg("-F") + .arg("/dev/stderr") + .stderr(Stdio::inherit()) + .output() + .unwrap() + } else { + Command::new("stty") + .arg("-f") + .arg("/dev/stderr") + .arg("size") + .stderr(Stdio::inherit()) + .output() + .unwrap() + }; + + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + // stdout is "rows cols" + let mut data = stdout.split_whitespace(); + println!("{}", stdout); + let rows = u16::from_str_radix(data.next().unwrap(), 10).unwrap(); + let cols = u16::from_str_radix(data.next().unwrap(), 10).unwrap(); + (rows, cols) + }; + println!("{} {}", rows, cols); + + if let Some((Width(w), Height(h))) = terminal_size() { + assert_eq!(rows, h); + assert_eq!(cols, w); + } else { + panic!("terminal_size() return None"); + } +} diff --git a/third_party/rust/terminal_size/src/windows.rs b/third_party/rust/terminal_size/src/windows.rs new file mode 100644 index 000000000000..14f487f114c5 --- /dev/null +++ b/third_party/rust/terminal_size/src/windows.rs @@ -0,0 +1,53 @@ +use super::{Height, Width}; +use std::os::windows::io::RawHandle; + +/// Returns the size of the terminal defaulting to STDOUT, if available. +/// +/// Note that this returns the size of the actual command window, and +/// not the overall size of the command window buffer +pub fn terminal_size() -> Option<(Width, Height)> { + use winapi::um::processenv::GetStdHandle; + use winapi::um::winbase::STD_OUTPUT_HANDLE; + + let handle = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) as RawHandle }; + + terminal_size_using_handle(handle) +} + +/// Returns the size of the terminal using the given handle, if available. +/// +/// If the given handle is not a tty, returns `None` +pub fn terminal_size_using_handle(handle: RawHandle) -> Option<(Width, Height)> { + use winapi::um::handleapi::INVALID_HANDLE_VALUE; + use winapi::um::wincon::{ + GetConsoleScreenBufferInfo, CONSOLE_SCREEN_BUFFER_INFO, COORD, SMALL_RECT, + }; + + // convert between winapi::um::winnt::HANDLE and std::os::windows::raw::HANDLE + let hand = handle as winapi::um::winnt::HANDLE; + + if hand == INVALID_HANDLE_VALUE { + return None; + } + + let zc = COORD { X: 0, Y: 0 }; + let mut csbi = CONSOLE_SCREEN_BUFFER_INFO { + dwSize: zc, + dwCursorPosition: zc, + wAttributes: 0, + srWindow: SMALL_RECT { + Left: 0, + Top: 0, + Right: 0, + Bottom: 0, + }, + dwMaximumWindowSize: zc, + }; + if unsafe { GetConsoleScreenBufferInfo(hand, &mut csbi) } == 0 { + return None; + } + + let w: Width = Width((csbi.srWindow.Right - csbi.srWindow.Left + 1) as u16); + let h: Height = Height((csbi.srWindow.Bottom - csbi.srWindow.Top + 1) as u16); + Some((w, h)) +} diff --git a/third_party/rust/textwrap/.cargo-checksum.json b/third_party/rust/textwrap/.cargo-checksum.json index 02794aab85c0..969ca7a12652 100644 --- a/third_party/rust/textwrap/.cargo-checksum.json +++ b/third_party/rust/textwrap/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"a0e3c783725beb480b666d52d49da0ec69865c82e8bd5c8a76ba330158e954c1","LICENSE":"ce93600c49fbb3e14df32efe752264644f6a2f8e08a735ba981725799e5309ef","README.md":"9af1f6627e8c2e19c7383c99462ca028b235b2f8dadbb33f13e2d1663c8c20e3","benches/linear.rs":"ec084063923bafc6e80c2cd78deb0f7ad18ae19a7e66005e991e00dac1ff3ce4","examples/layout.rs":"38cf4d316d28e0b99925bef604b68aad05489c06ec77e6105575cd26ce994631","examples/termwidth.rs":"67d95b60feb52cfd59fe5b17c37c53e51fb7f2a8e5e483d75aec8d0044dbcbd7","src/indentation.rs":"04f8479286fd87f2d75b0f02ce8309a815a5ffd1e79a7323132e34dc0e107aef","src/lib.rs":"115bf6ec566b8241d52cff83977146f03df3460d6f94ad897f2221cb56100118","src/splitting.rs":"071ef8ce0ea6c3f33230889a3426fd645276a6de626f45223ae7b873394df662","tests/version-numbers.rs":"e0e9316073d6d410440a6ee33c2f3bdfd0faa48895f6f9d05a220a91b7afcc99"},"package":"d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"} \ No newline at end of file +{"files":{"CHANGELOG.md":"02783800b8187cfd90e09a1362be4381748f29a96adc0157c06833d2c7f4ac4e","Cargo.toml":"5d55b1e1537d331df5ab2ffb81385544ffc1194ddb7243024284225a76fa9395","LICENSE":"ce93600c49fbb3e14df32efe752264644f6a2f8e08a735ba981725799e5309ef","README.md":"36c2030accc46c6df69c2254925d27e66b2b3c34c8ab263fd3d5daf14bfeb219","src/core.rs":"db8263e64a1b606343c7cc45d09b77d65f0a0442e17f0d14b45d612fc04a7946","src/indentation.rs":"49896f6e166f08a6f57f71a5d1bf706342c25e8410aa301fad590e001eb49799","src/lib.rs":"71f0a7d010cdb808179279c5dd6df3492eeeb7fca3132e60ca73139016ff343e","src/word_separators.rs":"99b5dddff8a89b850f002ebc4f8fb6d431c38d2ec10d3ee580393b5fe853c663","src/word_splitters.rs":"1f5b6faaa0a8f58edad5b65850b5d1c908f10af700af1bbb1f313d0fee33452d","src/wrap_algorithms.rs":"1bf0617704b24c0125e03a2032c816fff7b37ca2b80eaba00d80285d9b88b6fb","src/wrap_algorithms/optimal_fit.rs":"f27c5fd2f2360774bbf2d0d2e43036e61a995fddbceea578c0d9e110258023e2","tests/indent.rs":"51f977db11632a32fafecf86af88413d51238fe6efcf18ec52fac89133714278","tests/traits.rs":"ae5f7a6d5dc0ebc6ec41d5d933fc7ee3180af568248f495f072f3f73c43440b0","tests/version-numbers.rs":"9e964f58dbdf051fc6fe0d6542ab312d3e95f26c3fd14bce84449bb625e45761"},"package":"0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80"} \ No newline at end of file diff --git a/third_party/rust/textwrap/CHANGELOG.md b/third_party/rust/textwrap/CHANGELOG.md new file mode 100644 index 000000000000..cdc703efcf5b --- /dev/null +++ b/third_party/rust/textwrap/CHANGELOG.md @@ -0,0 +1,510 @@ +# Changelog + +This file lists the most important changes made in each release of +`textwrap`. + +## Version 0.14.2 (2021-06-27) + +The 0.14.1 release included more changes than intended and has been +yanked. The change intended for 0.14.1 is now included in 0.14.2. + +## Version 0.14.1 (2021-06-26) + +This release fixes a panic reported by @Makoto, thanks! + +* [#391](https://github.com/mgeisler/textwrap/pull/391): Fix panic in + `find_words` due to string access outside of a character boundary. + +## Version 0.14.0 (2021-06-05) + +This is a major feature release which makes Textwrap more configurable +and flexible. The high-level API of `textwrap::wrap` and +`textwrap::fill` remains unchanged, but low-level structs have moved +around. + +The biggest change is the introduction of new generic type parameters +to the `Options` struct. These parameters lets you statically +configure the wrapping algorithm, the word separator, and the word +splitter. If you previously spelled out the full type for `Options`, +you now need to take the extra type parameters into account. This +means that + +```rust +let options: Options = Options::new(80); +``` + +changes to + +```rust +let options: Options< + wrap_algorithms::FirstFit, + word_separators::AsciiSpace, + word_splitters::HyphenSplitter, +> = Options::new(80); +``` + +This is quite a mouthful, so we suggest using type inferrence where +possible. You won’t see any chance if you call `wrap` directly with a +width or with an `Options` value constructed on the fly. Please open +an issue if this causes problems for you! + +### New `WordSeparator` Trait + +* [#332](https://github.com/mgeisler/textwrap/pull/332): Add + `WordSeparator` trait to allow customizing how words are found in a + line of text. Until now, Textwrap would always assume that words are + separated by ASCII space characters. You can now customize this as + needed. + +* [#313](https://github.com/mgeisler/textwrap/pull/313): Add support + for using the Unicode line breaking algorithm to find words. This is + done by adding a second implementation of the new `WordSeparator` + trait. The implementation uses the unicode-linebreak crate, which is + a new optional dependency. + + With this, Textwrap can be used with East-Asian languages such as + Chinese or Japanese where there are no spaces between words. + Breaking a long sequence of emojis is another example where line + breaks might be wanted even if there are no whitespace to be found. + Feedback would be appreciated for this feature. + + +### Indent + +* [#353](https://github.com/mgeisler/textwrap/pull/353): Trim trailing + whitespace from `prefix` in `indent`. + + Before, empty lines would get no prefix added. Now, empty lines have + a trimmed prefix added. This little trick makes `indent` much more + useful since you can now safely indent with `"# "` without creating + trailing whitespace in the output due to the trailing whitespace in + your prefix. + +* [#354](https://github.com/mgeisler/textwrap/pull/354): Make `indent` + about 20% faster by preallocating the output string. + + +### Documentation + +* [#308](https://github.com/mgeisler/textwrap/pull/308): Document + handling of leading and trailing whitespace when wrapping text. + +### WebAssembly Demo + +* [#310](https://github.com/mgeisler/textwrap/pull/310): Thanks to + WebAssembly, you can now try out Textwrap directly in your browser. + Please try it out: https://mgeisler.github.io/textwrap/. + +### New Generic Parameters + +* [#331](https://github.com/mgeisler/textwrap/pull/331): Remove outer + boxing from `Options`. + +* [#357](https://github.com/mgeisler/textwrap/pull/357): Replace + `core::WrapAlgorithm` enum with a `wrap_algorithms::WrapAlgorithm` + trait. This allows for arbitrary wrapping algorithms to be plugged + into the library. + +* [#358](https://github.com/mgeisler/textwrap/pull/358): Switch + wrapping functions to use a slice for `line_widths`. + +* [#368](https://github.com/mgeisler/textwrap/pull/368): Move + `WordSeparator` and `WordSplitter` traits to separate modules. + Before, Textwrap had several top-level structs such as + `NoHyphenation` and `HyphenSplitter`. These implementations of + `WordSplitter` now lives in a dedicated `word_splitters` module. + Similarly, we have a new `word_separators` module for + implementations of `WordSeparator`. + +* [#369](https://github.com/mgeisler/textwrap/pull/369): Rename + `Options::splitter` to `Options::word_splitter` for consistency with + the other fields backed by traits. + +## Version 0.13.4 (2021-02-23) + +This release removes `println!` statements which was left behind in +`unfill` by mistake. + +* [#296](https://github.com/mgeisler/textwrap/pull/296): Improve house + building example with more comments. +* [#297](https://github.com/mgeisler/textwrap/pull/297): Remove debug + prints in the new `unfill` function. + +## Version 0.13.3 (2021-02-20) + +This release contains a bugfix for `indent` and improved handling of +emojis. We’ve also added a new function for formatting text in columns +and functions for reformatting already wrapped text. + +* [#276](https://github.com/mgeisler/textwrap/pull/276): Extend + `core::display_width` to handle emojis when the unicode-width Cargo + feature is disabled. +* [#279](https://github.com/mgeisler/textwrap/pull/279): Make `indent` + preserve existing newlines in the input string. Before, + `indent("foo", "")` would return `"foo\n"` by mistake. It now + returns `"foo"` instead. +* [#281](https://github.com/mgeisler/textwrap/pull/281): Ensure all + `Options` fields have examples. +* [#282](https://github.com/mgeisler/textwrap/pull/282): Add a + `wrap_columns` function. +* [#294](https://github.com/mgeisler/textwrap/pull/294): Add new + `unfill` and `refill` functions. + +## Version 0.13.2 (2020-12-30) + +This release primarily makes all dependencies optional. This makes it +possible to slim down textwrap as needed. + +* [#254](https://github.com/mgeisler/textwrap/pull/254): `impl + WordSplitter` for `Box where T: WordSplitter`. +* [#255](https://github.com/mgeisler/textwrap/pull/255): Use command + line arguments as initial text in interactive example. +* [#256](https://github.com/mgeisler/textwrap/pull/256): Introduce + fuzz tests for `wrap_optimal_fit` and `wrap_first_fit`. +* [#260](https://github.com/mgeisler/textwrap/pull/260): Make the + unicode-width dependency optional. +* [#261](https://github.com/mgeisler/textwrap/pull/261): Make the + smawk dependency optional. + +## Version 0.13.1 (2020-12-10) + +This is a bugfix release which fixes a regression in 0.13.0. The bug +meant that colored text was wrapped incorrectly. + +* [#245](https://github.com/mgeisler/textwrap/pull/245): Support + deleting a word with Ctrl-Backspace in the interactive demo. +* [#246](https://github.com/mgeisler/textwrap/pull/246): Show build + type (debug/release) in interactive demo. +* [#249](https://github.com/mgeisler/textwrap/pull/249): Correctly + compute width while skipping over ANSI escape sequences. + +## Version 0.13.0 (2020-12-05) + +This is a major release which rewrites the core logic, adds many new +features, and fixes a couple of bugs. Most programs which use +`textwrap` stays the same, incompatibilities and upgrade notes are +given below. + +Clone the repository and run the following to explore the new features +in an interactive demo (Linux only): + +```sh +$ cargo run --example interactive --all-features +``` + +### Bug Fixes + +#### Rewritten core wrapping algorithm + +* [#221](https://github.com/mgeisler/textwrap/pull/221): Reformulate + wrapping in terms of words with whitespace and penalties. + +The core wrapping algorithm has been completely rewritten. This fixed +bugs and simplified the code, while also making it possible to use +`textwrap` outside the context of the terminal. + +As part of this, trailing whitespace is now discarded consistently +from wrapped lines. Before we would inconsistently remove whitespace +at the end of wrapped lines, except for the last. Leading whitespace +is still preserved. + +### New Features + +#### Optimal-fit wrapping + +* [#234](https://github.com/mgeisler/textwrap/pull/234): Introduce + wrapping using an optimal-fit algorithm. + +This release adds support for new wrapping algorithm which finds a +globally optimal set of line breaks, taking certain penalties into +account. As an example, the old algorithm would produce + + "To be, or" + "not to be:" + "that is" + "the" + "question" + +Notice how the fourth line with “the” is very short. The new algorithm +shortens the previous lines slightly to produce fewer short lines: + + "To be," + "or not to" + "be: that" + "is the" + "question" + +Use the new `textwrap::core::WrapAlgorithm` enum to select between the +new and old algorithm. By default, the new algorithm is used. + +The optimal-fit algorithm is inspired by the line breaking algorithm +used in TeX, described in the 1981 article [_Breaking Paragraphs into +Lines_](http://www.eprg.org/G53DOC/pdfs/knuth-plass-breaking.pdf) by +Knuth and Plass. + +#### In-place wrapping + +* [#226](https://github.com/mgeisler/textwrap/pull/226): Add a + `fill_inplace` function. + +When the text you want to fill is already a temporary `String`, you +can now mutate it in-place with `fill_inplace`: + +```rust +let mut greeting = format!("Greetings {}, welcome to the game! You have {} lives left.", + player.name, player.lives); +fill_inplace(&mut greeting, line_width); +``` + +This is faster than calling `fill` and it will reuse the memory +already allocated for the string. + +### Changed Features + +#### `Wrapper` is replaced with `Options` + +* [#213](https://github.com/mgeisler/textwrap/pull/213): Simplify API + with only top-level functions. +* [#215](https://github.com/mgeisler/textwrap/pull/215): Reintroducing + the type parameter on `Options` (previously known as `Wrapper`). +* [#219](https://github.com/mgeisler/textwrap/pull/219): Allow using + trait objects with `fill` & `wrap`. +* [#227](https://github.com/mgeisler/textwrap/pull/227): Replace + `WrapOptions` with `Into`. + +The `Wrapper` struct held the options (line width, indentation, etc) +for wrapping text. It was also the entry point for actually wrapping +the text via its methods such as `wrap`, `wrap_iter`, +`into_wrap_iter`, and `fill` methods. + +The struct has been replaced by a simpler `Options` struct which only +holds options. The `Wrapper` methods are gone, their job has been +taken over by the top-level `wrap` and `fill` functions. The signature +of these functions have changed from + +```rust +fn fill(s: &str, width: usize) -> String; + +fn wrap(s: &str, width: usize) -> Vec>; +``` + +to the more general + +```rust +fn fill<'a, S, Opt>(text: &str, options: Opt) -> String +where + S: WordSplitter, + Opt: Into>; + +fn wrap<'a, S, Opt>(text: &str, options: Opt) -> Vec> +where + S: WordSplitter, + Opt: Into>; +``` + +The `Into` bound allows you to pass an `usize` (which +is interpreted as the line width) *and* a full `Options` object. This +allows the new functions to work like the old, plus you can now fully +customize the behavior of the wrapping via `Options` when needed. + +Code that call `textwrap::wrap` or `textwrap::fill` can remain +unchanged. Code that calls into `Wrapper::wrap` or `Wrapper::fill` +will need to be update. This is a mechanical change, please see +[#213](https://github.com/mgeisler/textwrap/pull/213) for examples. + +Thanks to @CryptJar and @Koxiat for their support in the PRs above! + +### Removed Features + +* The `wrap_iter` and `into_wrap_iter` methods are gone. This means + that lazy iteration is no longer supported: you always get all + wrapped lines back as a `Vec`. This was done to simplify the code + and to support the optimal-fit algorithm. + + The first-fit algorithm could still be implemented in an incremental + fashion. Please let us know if this is important to you. + +### Other Changes + +* [#206](https://github.com/mgeisler/textwrap/pull/206): Change + `Wrapper.splitter` from `T: WordSplitter` to `Box`. +* [#216](https://github.com/mgeisler/textwrap/pull/216): Forbid the + use of unsafe code. + +## Version 0.12.1 (2020-07-03) + +This is a bugfix release. + +* Fixed [#176][issue-176]: Mention compile-time wrapping by linking to + the [`textwrap-macros` crate]. +* Fixed [#193][issue-193]: Wrapping with `break_words(false)` was + broken and would cause extra whitespace to be inserted when words + were longer than the line width. + +## Version 0.12.0 (2020-06-26) + +The code has been updated to the [Rust 2018 edition][rust-2018] and +each new release of `textwrap` will only support the latest stable +version of Rust. Trying to support older Rust versions is a fool's +errand: our dependencies keep releasing new patch versions that +require newer and newer versions of Rust. + +The `term_size` feature has been replaced by `terminal_size`. The API +is unchanged, it is just the name of the Cargo feature that changed. + +The `hyphenation` feature now only embeds the hyphenation patterns for +US-English. This slims down the dependency. + +* Fixed [#140][issue-140]: Ignore ANSI escape sequences. +* Fixed [#158][issue-158]: Unintended wrapping when using external splitter. +* Fixed [#177][issue-177]: Update examples to the 2018 edition. + +## Version 0.11.0 (2018-12-09) + +Due to our dependencies bumping their minimum supported version of +Rust, the minimum version of Rust we test against is now 1.22.0. + +* Merged [#141][issue-141]: Fix `dedent` handling of empty lines and + trailing newlines. Thanks @bbqsrc! +* Fixed [#151][issue-151]: Release of version with hyphenation 0.7. + +## Version 0.10.0 (2018-04-28) + +Due to our dependencies bumping their minimum supported version of +Rust, the minimum version of Rust we test against is now 1.17.0. + +* Fixed [#99][issue-99]: Word broken even though it would fit on line. +* Fixed [#107][issue-107]: Automatic hyphenation is off by one. +* Fixed [#122][issue-122]: Take newlines into account when wrapping. +* Fixed [#129][issue-129]: Panic on string with em-dash. + +## Version 0.9.0 (2017-10-05) + +The dependency on `term_size` is now optional, and by default this +feature is not enabled. This is a *breaking change* for users of +`Wrapper::with_termwidth`. Enable the `term_size` feature to restore +the old functionality. + +Added a regression test for the case where `width` is set to +`usize::MAX`, thanks @Fraser999! All public structs now implement +`Debug`, thanks @hcpl! + +* Fixed [#101][issue-101]: Make `term_size` an optional dependency. + +## Version 0.8.0 (2017-09-04) + +The `Wrapper` stuct is now generic over the type of word splitter +being used. This means less boxing and a nicer API. The +`Wrapper::word_splitter` method has been removed. This is a *breaking +API change* if you used the method to change the word splitter. + +The `Wrapper` struct has two new methods that will wrap the input text +lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those +if you will be iterating over the wrapped lines one by one. + +* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks + @hcpl! +* Fixed [#81][issue-81]: Set `html_root_url`. + +## Version 0.7.0 (2017-07-20) + +Version 0.7.0 changes the return type of `Wrapper::wrap` from +`Vec` to `Vec>`. This means that the output lines +borrow data from the input string. This is a *breaking API change* if +you relied on the exact return type of `Wrapper::wrap`. Callers of the +`textwrap::fill` convenience function will see no breakage. + +The above change and other optimizations makes version 0.7.0 roughly +15-30% faster than version 0.6.0. + +The `squeeze_whitespace` option has been removed since it was +complicating the above optimization. Let us know if this option is +important for you so we can provide a work around. + +* Fixed [#58][issue-58]: Add a "fast_wrap" function. +* Fixed [#61][issue-61]: Documentation errors. + +## Version 0.6.0 (2017-05-22) + +Version 0.6.0 adds builder methods to `Wrapper` for easy one-line +initialization and configuration: + +```rust +let wrapper = Wrapper::new(60).break_words(false); +``` + +It also add a new `NoHyphenation` word splitter that will never split +words, not even at existing hyphens. + +* Fixed [#28][issue-28]: Support not squeezing whitespace. + +## Version 0.5.0 (2017-05-15) + +Version 0.5.0 has *breaking API changes*. However, this only affects +code using the hyphenation feature. The feature is now optional, so +you will first need to enable the `hyphenation` feature as described +above. Afterwards, please change your code from +```rust +wrapper.corpus = Some(&corpus); +``` +to +```rust +wrapper.splitter = Box::new(corpus); +``` + +Other changes include optimizations, so version 0.5.0 is roughly +10-15% faster than version 0.4.0. + +* Fixed [#19][issue-19]: Add support for finding terminal size. +* Fixed [#25][issue-25]: Handle words longer than `self.width`. +* Fixed [#26][issue-26]: Support custom indentation. +* Fixed [#36][issue-36]: Support building without `hyphenation`. +* Fixed [#39][issue-39]: Respect non-breaking spaces. + +## Version 0.4.0 (2017-01-24) + +Documented complexities and tested these via `cargo bench`. + +* Fixed [#13][issue-13]: Immediatedly add word if it fits. +* Fixed [#14][issue-14]: Avoid splitting on initial hyphens. + +## Version 0.3.0 (2017-01-07) + +Added support for automatic hyphenation. + +## Version 0.2.0 (2016-12-28) + +Introduced `Wrapper` struct. Added support for wrapping on hyphens. + +## Version 0.1.0 (2016-12-17) + +First public release with support for wrapping strings on whitespace. + +[rust-2018]: https://doc.rust-lang.org/edition-guide/rust-2018/ +[`textwrap-macros` crate]: https://crates.io/crates/textwrap-macros + +[issue-13]: https://github.com/mgeisler/textwrap/issues/13 +[issue-14]: https://github.com/mgeisler/textwrap/issues/14 +[issue-19]: https://github.com/mgeisler/textwrap/issues/19 +[issue-25]: https://github.com/mgeisler/textwrap/issues/25 +[issue-26]: https://github.com/mgeisler/textwrap/issues/26 +[issue-28]: https://github.com/mgeisler/textwrap/issues/28 +[issue-36]: https://github.com/mgeisler/textwrap/issues/36 +[issue-39]: https://github.com/mgeisler/textwrap/issues/39 +[issue-58]: https://github.com/mgeisler/textwrap/issues/58 +[issue-59]: https://github.com/mgeisler/textwrap/issues/59 +[issue-61]: https://github.com/mgeisler/textwrap/issues/61 +[issue-81]: https://github.com/mgeisler/textwrap/issues/81 +[issue-99]: https://github.com/mgeisler/textwrap/issues/99 +[issue-101]: https://github.com/mgeisler/textwrap/issues/101 +[issue-107]: https://github.com/mgeisler/textwrap/issues/107 +[issue-122]: https://github.com/mgeisler/textwrap/issues/122 +[issue-129]: https://github.com/mgeisler/textwrap/issues/129 +[issue-140]: https://github.com/mgeisler/textwrap/issues/140 +[issue-141]: https://github.com/mgeisler/textwrap/issues/141 +[issue-151]: https://github.com/mgeisler/textwrap/issues/151 +[issue-158]: https://github.com/mgeisler/textwrap/issues/158 +[issue-176]: https://github.com/mgeisler/textwrap/issues/176 +[issue-177]: https://github.com/mgeisler/textwrap/issues/177 +[issue-193]: https://github.com/mgeisler/textwrap/issues/193 diff --git a/third_party/rust/textwrap/Cargo.toml b/third_party/rust/textwrap/Cargo.toml index 4ec570f10c3e..69acb0f1a0d5 100644 --- a/third_party/rust/textwrap/Cargo.toml +++ b/third_party/rust/textwrap/Cargo.toml @@ -3,7 +3,7 @@ # 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 @@ -11,11 +11,12 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "textwrap" -version = "0.11.0" +version = "0.14.2" authors = ["Martin Geisler "] -exclude = [".dir-locals.el"] -description = "Textwrap is a small library for word wrapping, indenting, and\ndedenting strings.\n\nYou can use it to format strings (such as help and error messages) for\ndisplay in commandline applications. It is designed to be efficient\nand handle Unicode characters correctly.\n" +exclude = [".github/", ".gitignore", "benches/", "examples/", "fuzz/", "images/"] +description = "Powerful library for word wrapping, indenting, and dedenting strings" documentation = "https://docs.rs/textwrap/" readme = "README.md" keywords = ["text", "formatting", "wrap", "typesetting", "hyphenation"] @@ -24,33 +25,49 @@ license = "MIT" repository = "https://github.com/mgeisler/textwrap" [package.metadata.docs.rs] all-features = true + +[[bench]] +name = "linear" +path = "benches/linear.rs" +harness = false + +[[bench]] +name = "indent" +path = "benches/indent.rs" +harness = false [dependencies.hyphenation] -version = "0.7.1" -features = ["embed_all"] +version = "0.8.2" +features = ["embed_en-us"] optional = true -[dependencies.term_size] -version = "0.3.0" +[dependencies.smawk] +version = "0.3" +optional = true + +[dependencies.terminal_size] +version = "0.1" +optional = true + +[dependencies.unicode-linebreak] +version = "0.1" optional = true [dependencies.unicode-width] -version = "0.1.3" -[dev-dependencies.lipsum] -version = "0.6" - -[dev-dependencies.rand] -version = "0.6" - -[dev-dependencies.rand_xorshift] version = "0.1" +optional = true +[dev-dependencies.criterion] +version = "0.3" + +[dev-dependencies.lipsum] +version = "0.8" + +[dev-dependencies.unic-emoji-char] +version = "0.9.0" [dev-dependencies.version-sync] -version = "0.6" -[badges.appveyor] -repository = "mgeisler/textwrap" +version = "0.9" -[badges.codecov] -repository = "mgeisler/textwrap" - -[badges.travis-ci] -repository = "mgeisler/textwrap" +[features] +default = ["unicode-linebreak", "unicode-width", "smawk"] +[target."cfg(unix)".dev-dependencies.termion] +version = "1.5" diff --git a/third_party/rust/textwrap/README.md b/third_party/rust/textwrap/README.md index 23a54390438e..b32924c6ec02 100644 --- a/third_party/rust/textwrap/README.md +++ b/third_party/rust/textwrap/README.md @@ -1,43 +1,31 @@ # Textwrap +[![](https://github.com/mgeisler/textwrap/workflows/build/badge.svg)][build-status] +[![](https://codecov.io/gh/mgeisler/textwrap/branch/master/graph/badge.svg)][codecov] [![](https://img.shields.io/crates/v/textwrap.svg)][crates-io] [![](https://docs.rs/textwrap/badge.svg)][api-docs] -[![](https://travis-ci.org/mgeisler/textwrap.svg?branch=master)][travis-ci] -[![](https://ci.appveyor.com/api/projects/status/github/mgeisler/textwrap?branch=master&svg=true)][appveyor] -[![](https://codecov.io/gh/mgeisler/textwrap/branch/master/graph/badge.svg)][codecov] -Textwrap is a small Rust crate for word wrapping text. You can use it -to format strings for display in commandline applications. The crate -name and interface is inspired by -the [Python textwrap module][py-textwrap]. +Textwrap is a library for wrapping and indenting text. It is most +often used by command-line programs to format dynamic output nicely so +it looks good in a terminal. You can also use Textwrap to wrap text +set in a proportional font—such as text used to generate PDF files, or +drawn on a [HTML5 canvas using WebAssembly][wasm-demo]. ## Usage -Add this to your `Cargo.toml`: +To use the textwrap crate, add this to your `Cargo.toml` file: ```toml [dependencies] -textwrap = "0.11" +textwrap = "0.14" ``` -and this to your crate root: -```rust -extern crate textwrap; -``` - -If you would like to have automatic hyphenation, specify the -dependency as: -```toml -[dependencies] -textwrap = { version = "0.11", features = ["hyphenation"] } -``` - -To conveniently wrap text at the current terminal width, enable the -`term_size` feature: - -```toml -[dependencies] -textwrap = { version = "0.11", features = ["term_size"] } -``` +By default, this enables word wrapping with support for Unicode +strings. Extra features can be enabled with Cargo features—and the +Unicode support can be disabled if needed. This allows you slim down +the library and so you will only pay for the features you actually +use. Please see the [_Cargo Features_ in the crate +documentation](https://docs.rs/textwrap/#cargo-features) for a full +list of the available features. ## Documentation @@ -45,263 +33,112 @@ textwrap = { version = "0.11", features = ["term_size"] } ## Getting Started -Word wrapping single strings is easy using the `fill` function: -```rust -extern crate textwrap; -use textwrap::fill; +Word wrapping is easy using the `fill` function: +```rust fn main() { - let text = "textwrap: a small library for wrapping text."; - println!("{}", fill(text, 18)); + let text = "textwrap: an efficient and powerful library for wrapping text."; + println!("{}", textwrap::fill(text, 28)); } ``` -The output is + +The output is wrapped within 28 columns: + ``` -textwrap: a small -library for +textwrap: an efficient +and powerful library for wrapping text. ``` -With the `hyphenation` feature, you can get automatic hyphenation -for [about 70 languages][patterns]. Your program must load and -configure the hyphenation patterns to use: -```rust -extern crate hyphenation; -extern crate textwrap; +Sharp-eyed readers will notice that the first line is 22 columns wide. +So why is the word “and” put in the second line when there is space +for it in the first line? +The explanation is that textwrap does not just wrap text one line at a +time. Instead, it uses an optimal-fit algorithm which looks ahead and +chooses line breaks which minimize the gaps left at ends of lines. + +Without look-ahead, the first line would be longer and the text would +look like this: + +``` +textwrap: an efficient and +powerful library for +wrapping text. +``` + +The second line is now shorter and the text is more ragged. The kind +of wrapping can be configured via `Options::wrap_algorithm`. + +If you enable the `hyphenation` Cargo feature, you get support for +automatic hyphenation for [about 70 languages][patterns] via +high-quality TeX hyphenation patterns. + +Your program must load the hyphenation pattern and configure +`Options::word_splitter` to use it: + +```rust use hyphenation::{Language, Load, Standard}; -use textwrap::Wrapper; +use textwrap::Options; fn main() { let hyphenator = Standard::from_embedded(Language::EnglishUS).unwrap(); - let wrapper = Wrapper::with_splitter(18, hyphenator); - let text = "textwrap: a small library for wrapping text."; - println!("{}", wrapper.fill(text)) + let options = Options::new(28).word_splitter(hyphenator); + let text = "textwrap: an efficient and powerful library for wrapping text."; + println!("{}", fill(text, &options); } ``` The output now looks like this: ``` -textwrap: a small -library for wrap- +textwrap: an efficient and +powerful library for wrap- ping text. ``` -The hyphenation uses high-quality TeX hyphenation patterns. +The US-English hyphenation patterns are embedded when you enable the +`hyphenation` feature. They are licensed under a [permissive +license][en-us license] and take up about 88 KB in your binary. If you +need hyphenation for other languages, you need to download a +[precompiled `.bincode` file][bincode] and load it yourself. Please +see the [`hyphenation` documentation] for details. + +## Wrapping Strings at Compile Time + +If your strings are known at compile time, please take a look at the +procedural macros from the [`textwrap-macros` crate]. ## Examples -The library comes with some small example programs that shows various -features. +The library comes with [a +collection](https://github.com/mgeisler/textwrap/tree/master/examples) +of small example programs that shows various features. -### Layout Example +If you want to see Textwrap in action right away, then take a look at +[`examples/wasm/`], which shows how to wrap sans-serif, serif, and +monospace text. It uses WebAssembly and is automatically deployed to +https://mgeisler.github.io/textwrap/. -The `layout` example shows how a fixed example string is wrapped at -different widths. Run the example with: +For the command-line examples, you’re invited to clone the repository +and try them out for yourself! Of special note is +[`examples/interactive.rs`]. This is a demo program which demonstrates +most of the available features: you can enter text and adjust the +width at which it is wrapped interactively. You can also adjust the +`Options` used to see the effect of different `WordSplitter`s and wrap +algorithms. -```shell -$ cargo run --features hyphenation --example layout +Run the demo with + +```sh +$ cargo run --example interactive ``` -The program will use the following string: - -> Memory safety without garbage collection. Concurrency without data -> races. Zero-cost abstractions. - -The string is wrapped at all widths between 15 and 60 columns. With -narrow columns the output looks like this: - -``` -.--- Width: 15 ---. -| Memory safety | -| without garbage | -| collection. | -| Concurrency | -| without data | -| races. Zero- | -| cost abstrac- | -| tions. | -.--- Width: 16 ----. -| Memory safety | -| without garbage | -| collection. Con- | -| currency without | -| data races. Ze- | -| ro-cost abstrac- | -| tions. | -``` - -Later, longer lines are used and the output now looks like this: - -``` -.-------------------- Width: 49 --------------------. -| Memory safety without garbage collection. Concur- | -| rency without data races. Zero-cost abstractions. | -.---------------------- Width: 53 ----------------------. -| Memory safety without garbage collection. Concurrency | -| without data races. Zero-cost abstractions. | -.------------------------- Width: 59 -------------------------. -| Memory safety without garbage collection. Concurrency with- | -| out data races. Zero-cost abstractions. | -``` - -Notice how words are split at hyphens (such as "zero-cost") but also -how words are hyphenated using automatic/machine hyphenation. - -### Terminal Width Example - -The `termwidth` example simply shows how the width can be set -automatically to the current terminal width. Run it with this command: - -``` -$ cargo run --example termwidth -``` - -If you run it in a narrow terminal, you'll see output like this: -``` -Formatted in within 60 columns: ----- -Memory safety without garbage collection. Concurrency -without data races. Zero-cost abstractions. ----- -``` - -If `stdout` is not connected to the terminal, the program will use a -default of 80 columns for the width: - -``` -$ cargo run --example termwidth | cat -Formatted in within 80 columns: ----- -Memory safety without garbage collection. Concurrency without data races. Zero- -cost abstractions. ----- -``` +The demo needs a Linux terminal to function. ## Release History -This section lists the largest changes per release. - -### Version 0.11.0 — December 9th, 2018 - -Due to our dependencies bumping their minimum supported version of -Rust, the minimum version of Rust we test against is now 1.22.0. - -* Merged [#141][issue-141]: Fix `dedent` handling of empty lines and - trailing newlines. Thanks @bbqsrc! -* Fixed [#151][issue-151]: Release of version with hyphenation 0.7. - -### Version 0.10.0 — April 28th, 2018 - -Due to our dependencies bumping their minimum supported version of -Rust, the minimum version of Rust we test against is now 1.17.0. - -* Fixed [#99][issue-99]: Word broken even though it would fit on line. -* Fixed [#107][issue-107]: Automatic hyphenation is off by one. -* Fixed [#122][issue-122]: Take newlines into account when wrapping. -* Fixed [#129][issue-129]: Panic on string with em-dash. - -### Version 0.9.0 — October 5th, 2017 - -The dependency on `term_size` is now optional, and by default this -feature is not enabled. This is a *breaking change* for users of -`Wrapper::with_termwidth`. Enable the `term_size` feature to restore -the old functionality. - -Added a regression test for the case where `width` is set to -`usize::MAX`, thanks @Fraser999! All public structs now implement -`Debug`, thanks @hcpl! - -* Fixed [#101][issue-101]: Make `term_size` an optional dependency. - -### Version 0.8.0 — September 4th, 2017 - -The `Wrapper` stuct is now generic over the type of word splitter -being used. This means less boxing and a nicer API. The -`Wrapper::word_splitter` method has been removed. This is a *breaking -API change* if you used the method to change the word splitter. - -The `Wrapper` struct has two new methods that will wrap the input text -lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those -if you will be iterating over the wrapped lines one by one. - -* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks - @hcpl! -* Fixed [#81][issue-81]: Set `html_root_url`. - -### Version 0.7.0 — July 20th, 2017 - -Version 0.7.0 changes the return type of `Wrapper::wrap` from -`Vec` to `Vec>`. This means that the output lines -borrow data from the input string. This is a *breaking API change* if -you relied on the exact return type of `Wrapper::wrap`. Callers of the -`textwrap::fill` convenience function will see no breakage. - -The above change and other optimizations makes version 0.7.0 roughly -15-30% faster than version 0.6.0. - -The `squeeze_whitespace` option has been removed since it was -complicating the above optimization. Let us know if this option is -important for you so we can provide a work around. - -* Fixed [#58][issue-58]: Add a "fast_wrap" function. -* Fixed [#61][issue-61]: Documentation errors. - -### Version 0.6.0 — May 22nd, 2017 - -Version 0.6.0 adds builder methods to `Wrapper` for easy one-line -initialization and configuration: - -```rust -let wrapper = Wrapper::new(60).break_words(false); -``` - -It also add a new `NoHyphenation` word splitter that will never split -words, not even at existing hyphens. - -* Fixed [#28][issue-28]: Support not squeezing whitespace. - -### Version 0.5.0 — May 15th, 2017 - -Version 0.5.0 has *breaking API changes*. However, this only affects -code using the hyphenation feature. The feature is now optional, so -you will first need to enable the `hyphenation` feature as described -above. Afterwards, please change your code from -```rust -wrapper.corpus = Some(&corpus); -``` -to -```rust -wrapper.splitter = Box::new(corpus); -``` - -Other changes include optimizations, so version 0.5.0 is roughly -10-15% faster than version 0.4.0. - -* Fixed [#19][issue-19]: Add support for finding terminal size. -* Fixed [#25][issue-25]: Handle words longer than `self.width`. -* Fixed [#26][issue-26]: Support custom indentation. -* Fixed [#36][issue-36]: Support building without `hyphenation`. -* Fixed [#39][issue-39]: Respect non-breaking spaces. - -### Version 0.4.0 — January 24th, 2017 - -Documented complexities and tested these via `cargo bench`. - -* Fixed [#13][issue-13]: Immediatedly add word if it fits. -* Fixed [#14][issue-14]: Avoid splitting on initial hyphens. - -### Version 0.3.0 — January 7th, 2017 - -Added support for automatic hyphenation. - -### Version 0.2.0 — December 28th, 2016 - -Introduced `Wrapper` struct. Added support for wrapping on hyphens. - -### Version 0.1.0 — December 17th, 2016 - -First public release with support for wrapping strings on whitespace. +Please see the [CHANGELOG file] for details on the changes made in +each release. ## License @@ -309,29 +146,18 @@ Textwrap can be distributed according to the [MIT license][mit]. Contributions will be accepted under the same license. [crates-io]: https://crates.io/crates/textwrap -[travis-ci]: https://travis-ci.org/mgeisler/textwrap -[appveyor]: https://ci.appveyor.com/project/mgeisler/textwrap +[build-status]: https://github.com/mgeisler/textwrap/actions?query=workflow%3Abuild+branch%3Amaster [codecov]: https://codecov.io/gh/mgeisler/textwrap -[py-textwrap]: https://docs.python.org/library/textwrap +[wasm-demo]: https://mgeisler.github.io/textwrap/ +[`textwrap-macros` crate]: https://crates.io/crates/textwrap-macros +[`hyphenation` example]: https://github.com/mgeisler/textwrap/blob/master/examples/hyphenation.rs +[`termwidth` example]: https://github.com/mgeisler/textwrap/blob/master/examples/termwidth.rs [patterns]: https://github.com/tapeinosyne/hyphenation/tree/master/patterns-tex +[en-us license]: https://github.com/hyphenation/tex-hyphen/blob/master/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-en-us.tex +[bincode]: https://github.com/tapeinosyne/hyphenation/tree/master/dictionaries +[`hyphenation` documentation]: http://docs.rs/hyphenation +[`examples/wasm/`]: https://github.com/mgeisler/textwrap/tree/master/examples/wasm +[`examples/interactive.rs`]: https://github.com/mgeisler/textwrap/tree/master/examples/interactive.rs [api-docs]: https://docs.rs/textwrap/ -[issue-13]: https://github.com/mgeisler/textwrap/issues/13 -[issue-14]: https://github.com/mgeisler/textwrap/issues/14 -[issue-19]: https://github.com/mgeisler/textwrap/issues/19 -[issue-25]: https://github.com/mgeisler/textwrap/issues/25 -[issue-26]: https://github.com/mgeisler/textwrap/issues/26 -[issue-28]: https://github.com/mgeisler/textwrap/issues/28 -[issue-36]: https://github.com/mgeisler/textwrap/issues/36 -[issue-39]: https://github.com/mgeisler/textwrap/issues/39 -[issue-58]: https://github.com/mgeisler/textwrap/issues/58 -[issue-59]: https://github.com/mgeisler/textwrap/issues/59 -[issue-61]: https://github.com/mgeisler/textwrap/issues/61 -[issue-81]: https://github.com/mgeisler/textwrap/issues/81 -[issue-99]: https://github.com/mgeisler/textwrap/issues/99 -[issue-101]: https://github.com/mgeisler/textwrap/issues/101 -[issue-107]: https://github.com/mgeisler/textwrap/issues/107 -[issue-122]: https://github.com/mgeisler/textwrap/issues/122 -[issue-129]: https://github.com/mgeisler/textwrap/issues/129 -[issue-141]: https://github.com/mgeisler/textwrap/issues/141 -[issue-151]: https://github.com/mgeisler/textwrap/issues/151 +[CHANGELOG file]: https://github.com/mgeisler/textwrap/blob/master/CHANGELOG.md [mit]: LICENSE diff --git a/third_party/rust/textwrap/benches/linear.rs b/third_party/rust/textwrap/benches/linear.rs deleted file mode 100644 index 104398a1b628..000000000000 --- a/third_party/rust/textwrap/benches/linear.rs +++ /dev/null @@ -1,122 +0,0 @@ -#![feature(test)] - -// The benchmarks here verify that the complexity grows as O(*n*) -// where *n* is the number of characters in the text to be wrapped. - -#[cfg(feature = "hyphenation")] -extern crate hyphenation; -extern crate lipsum; -extern crate rand; -extern crate rand_xorshift; -extern crate test; -extern crate textwrap; - -#[cfg(feature = "hyphenation")] -use hyphenation::{Language, Load, Standard}; -use lipsum::MarkovChain; -use rand::SeedableRng; -use rand_xorshift::XorShiftRng; -use test::Bencher; -#[cfg(feature = "hyphenation")] -use textwrap::Wrapper; - -const LINE_LENGTH: usize = 60; - -/// Generate a lorem ipsum text with the given number of characters. -fn lorem_ipsum(length: usize) -> String { - // The average word length in the lorem ipsum text is somewhere - // between 6 and 7. So we conservatively divide by 5 to have a - // long enough text that we can truncate below. - let rng = XorShiftRng::seed_from_u64(0); - let mut chain = MarkovChain::new_with_rng(rng); - chain.learn(lipsum::LOREM_IPSUM); - chain.learn(lipsum::LIBER_PRIMUS); - - let mut text = chain.generate_from(length / 5, ("Lorem", "ipsum")); - text.truncate(length); - text -} - -#[bench] -fn fill_100(b: &mut Bencher) { - let text = &lorem_ipsum(100); - b.iter(|| textwrap::fill(text, LINE_LENGTH)) -} - -#[bench] -fn fill_200(b: &mut Bencher) { - let text = &lorem_ipsum(200); - b.iter(|| textwrap::fill(text, LINE_LENGTH)) -} - -#[bench] -fn fill_400(b: &mut Bencher) { - let text = &lorem_ipsum(400); - b.iter(|| textwrap::fill(text, LINE_LENGTH)) -} - -#[bench] -fn fill_800(b: &mut Bencher) { - let text = &lorem_ipsum(800); - b.iter(|| textwrap::fill(text, LINE_LENGTH)) -} - -#[bench] -fn wrap_100(b: &mut Bencher) { - let text = &lorem_ipsum(100); - b.iter(|| textwrap::wrap(text, LINE_LENGTH)) -} - -#[bench] -fn wrap_200(b: &mut Bencher) { - let text = &lorem_ipsum(200); - b.iter(|| textwrap::wrap(text, LINE_LENGTH)) -} - -#[bench] -fn wrap_400(b: &mut Bencher) { - let text = &lorem_ipsum(400); - b.iter(|| textwrap::wrap(text, LINE_LENGTH)) -} - -#[bench] -fn wrap_800(b: &mut Bencher) { - let text = &lorem_ipsum(800); - b.iter(|| textwrap::wrap(text, LINE_LENGTH)) -} - -#[bench] -#[cfg(feature = "hyphenation")] -fn hyphenation_fill_100(b: &mut Bencher) { - let text = &lorem_ipsum(100); - let dictionary = Standard::from_embedded(Language::Latin).unwrap(); - let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); - b.iter(|| wrapper.fill(text)) -} - -#[bench] -#[cfg(feature = "hyphenation")] -fn hyphenation_fill_200(b: &mut Bencher) { - let text = &lorem_ipsum(200); - let dictionary = Standard::from_embedded(Language::Latin).unwrap(); - let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); - b.iter(|| wrapper.fill(text)) -} - -#[bench] -#[cfg(feature = "hyphenation")] -fn hyphenation_fill_400(b: &mut Bencher) { - let text = &lorem_ipsum(400); - let dictionary = Standard::from_embedded(Language::Latin).unwrap(); - let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); - b.iter(|| wrapper.fill(text)) -} - -#[bench] -#[cfg(feature = "hyphenation")] -fn hyphenation_fill_800(b: &mut Bencher) { - let text = &lorem_ipsum(800); - let dictionary = Standard::from_embedded(Language::Latin).unwrap(); - let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary); - b.iter(|| wrapper.fill(text)) -} diff --git a/third_party/rust/textwrap/examples/layout.rs b/third_party/rust/textwrap/examples/layout.rs deleted file mode 100644 index d36cb3ab93a3..000000000000 --- a/third_party/rust/textwrap/examples/layout.rs +++ /dev/null @@ -1,38 +0,0 @@ -#[cfg(feature = "hyphenation")] -extern crate hyphenation; -extern crate textwrap; - -#[cfg(feature = "hyphenation")] -use hyphenation::{Language, Load}; -use textwrap::Wrapper; - -#[cfg(not(feature = "hyphenation"))] -fn new_wrapper<'a>() -> Wrapper<'a, textwrap::HyphenSplitter> { - Wrapper::new(0) -} - -#[cfg(feature = "hyphenation")] -fn new_wrapper<'a>() -> Wrapper<'a, hyphenation::Standard> { - let dictionary = hyphenation::Standard::from_embedded(Language::EnglishUS).unwrap(); - Wrapper::with_splitter(0, dictionary) -} - -fn main() { - let example = "Memory safety without garbage collection. \ - Concurrency without data races. \ - Zero-cost abstractions."; - let mut prev_lines = vec![]; - let mut wrapper = new_wrapper(); - for width in 15..60 { - wrapper.width = width; - let lines = wrapper.wrap(example); - if lines != prev_lines { - let title = format!(" Width: {} ", width); - println!(".{:-^1$}.", title, width + 2); - for line in &lines { - println!("| {:1$} |", line, width); - } - prev_lines = lines; - } - } -} diff --git a/third_party/rust/textwrap/examples/termwidth.rs b/third_party/rust/textwrap/examples/termwidth.rs deleted file mode 100644 index 75db3aa7e406..000000000000 --- a/third_party/rust/textwrap/examples/termwidth.rs +++ /dev/null @@ -1,41 +0,0 @@ -#[cfg(feature = "hyphenation")] -extern crate hyphenation; -extern crate textwrap; - -#[cfg(feature = "hyphenation")] -use hyphenation::{Language, Load, Standard}; -#[cfg(feature = "term_size")] -use textwrap::Wrapper; - -#[cfg(not(feature = "term_size"))] -fn main() { - println!("Please enable the term_size feature to run this example."); -} - -#[cfg(feature = "term_size")] -fn main() { - #[cfg(not(feature = "hyphenation"))] - fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, textwrap::HyphenSplitter>) { - ("without hyphenation", Wrapper::with_termwidth()) - } - - #[cfg(feature = "hyphenation")] - fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, Standard>) { - let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); - ( - "with hyphenation", - Wrapper::with_splitter(textwrap::termwidth(), dictionary), - ) - } - - let example = "Memory safety without garbage collection. \ - Concurrency without data races. \ - Zero-cost abstractions."; - // Create a new Wrapper -- automatically set the width to the - // current terminal width. - let (msg, wrapper) = new_wrapper(); - println!("Formatted {} in {} columns:", msg, wrapper.width); - println!("----"); - println!("{}", wrapper.fill(example)); - println!("----"); -} diff --git a/third_party/rust/textwrap/src/core.rs b/third_party/rust/textwrap/src/core.rs new file mode 100644 index 000000000000..af024603384d --- /dev/null +++ b/third_party/rust/textwrap/src/core.rs @@ -0,0 +1,434 @@ +//! Building blocks for advanced wrapping functionality. +//! +//! The functions and structs in this module can be used to implement +//! advanced wrapping functionality when the [`wrap`](super::wrap) and +//! [`fill`](super::fill) function don't do what you want. +//! +//! In general, you want to follow these steps when wrapping +//! something: +//! +//! 1. Split your input into [`Fragment`]s. These are abstract blocks +//! of text or content which can be wrapped into lines. See +//! [`WordSeparator`](crate::word_separators::WordSeparator) for +//! how to do this for text. +//! +//! 2. Potentially split your fragments into smaller pieces. This +//! allows you to implement things like hyphenation. If you are +//! wrapping text represented as a sequence of [`Word`]s, then you +//! can use [`split_words`](crate::word_splitters::split_words) can +//! help you do this. +//! +//! 3. Potentially break apart fragments that are still too large to +//! fit on a single line. This is implemented in [`break_words`]. +//! +//! 4. Finally take your fragments and put them into lines. There are +//! two algorithms for this in the +//! [`wrap_algorithms`](crate::wrap_algorithms) module: +//! [`wrap_optimal_fit`](crate::wrap_algorithms::wrap_optimal_fit) +//! and [`wrap_first_fit`](crate::wrap_algorithms::wrap_first_fit). +//! The former produces better line breaks, the latter is faster. +//! +//! 5. Iterate through the slices returned by the wrapping functions +//! and construct your lines of output. +//! +//! Please [open an issue](https://github.com/mgeisler/textwrap/) if +//! the functionality here is not sufficient or if you have ideas for +//! improving it. We would love to hear from you! + +/// The CSI or “Control Sequence Introducer” introduces an ANSI escape +/// sequence. This is typically used for colored text and will be +/// ignored when computing the text width. +const CSI: (char, char) = ('\x1b', '['); +/// The final bytes of an ANSI escape sequence must be in this range. +const ANSI_FINAL_BYTE: std::ops::RangeInclusive = '\x40'..='\x7e'; + +/// Skip ANSI escape sequences. The `ch` is the current `char`, the +/// `chars` provide the following characters. The `chars` will be +/// modified if `ch` is the start of an ANSI escape sequence. +#[inline] +pub(crate) fn skip_ansi_escape_sequence>(ch: char, chars: &mut I) -> bool { + if ch == CSI.0 && chars.next() == Some(CSI.1) { + // We have found the start of an ANSI escape code, typically + // used for colored terminal text. We skip until we find a + // "final byte" in the range 0x40–0x7E. + for ch in chars { + if ANSI_FINAL_BYTE.contains(&ch) { + return true; + } + } + } + false +} + +#[cfg(feature = "unicode-width")] +#[inline] +fn ch_width(ch: char) -> usize { + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) +} + +/// First character which [`ch_width`] will classify as double-width. +/// Please see [`display_width`]. +#[cfg(not(feature = "unicode-width"))] +const DOUBLE_WIDTH_CUTOFF: char = '\u{1100}'; + +#[cfg(not(feature = "unicode-width"))] +#[inline] +fn ch_width(ch: char) -> usize { + if ch < DOUBLE_WIDTH_CUTOFF { + 1 + } else { + 2 + } +} + +/// Compute the display width of `text` while skipping over ANSI +/// escape sequences. +/// +/// # Examples +/// +/// ``` +/// use textwrap::core::display_width; +/// +/// assert_eq!(display_width("Café Plain"), 10); +/// assert_eq!(display_width("\u{1b}[31mCafé Rouge\u{1b}[0m"), 10); +/// ``` +/// +/// **Note:** When the `unicode-width` Cargo feature is disabled, the +/// width of a `char` is determined by a crude approximation which +/// simply counts chars below U+1100 as 1 column wide, and all other +/// characters as 2 columns wide. With the feature enabled, function +/// will correctly deal with [combining characters] in their +/// decomposed form (see [Unicode equivalence]). +/// +/// An example of a decomposed character is “é”, which can be +/// decomposed into: “e” followed by a combining acute accent: “◌́”. +/// Without the `unicode-width` Cargo feature, every `char` below +/// U+1100 has a width of 1. This includes the combining accent: +/// +/// ``` +/// use textwrap::core::display_width; +/// +/// assert_eq!(display_width("Cafe Plain"), 10); +/// #[cfg(feature = "unicode-width")] +/// assert_eq!(display_width("Cafe\u{301} Plain"), 10); +/// #[cfg(not(feature = "unicode-width"))] +/// assert_eq!(display_width("Cafe\u{301} Plain"), 11); +/// ``` +/// +/// ## Emojis and CJK Characters +/// +/// Characters such as emojis and [CJK characters] used in the +/// Chinese, Japanese, and Korean langauges are seen as double-width, +/// even if the `unicode-width` feature is disabled: +/// +/// ``` +/// use textwrap::core::display_width; +/// +/// assert_eq!(display_width("😂😭🥺🤣✨😍🙏🥰😊🔥"), 20); +/// assert_eq!(display_width("你好"), 4); // “Nǐ hǎo” or “Hello” in Chinese +/// ``` +/// +/// # Limitations +/// +/// The displayed width of a string cannot always be computed from the +/// string alone. This is because the width depends on the rendering +/// engine used. This is particularly visible with [emoji modifier +/// sequences] where a base emoji is modified with, e.g., skin tone or +/// hair color modifiers. It is up to the rendering engine to detect +/// this and to produce a suitable emoji. +/// +/// A simple example is “❤️”, which consists of “❤” (U+2764: Black +/// Heart Symbol) followed by U+FE0F (Variation Selector-16). By +/// itself, “❤” is a black heart, but if you follow it with the +/// variant selector, you may get a wider red heart. +/// +/// A more complex example would be “👨‍🦰” which should depict a man +/// with red hair. Here the computed width is too large — and the +/// width differs depending on the use of the `unicode-width` feature: +/// +/// ``` +/// use textwrap::core::display_width; +/// +/// assert_eq!("👨‍🦰".chars().collect::>(), ['\u{1f468}', '\u{200d}', '\u{1f9b0}']); +/// #[cfg(feature = "unicode-width")] +/// assert_eq!(display_width("👨‍🦰"), 4); +/// #[cfg(not(feature = "unicode-width"))] +/// assert_eq!(display_width("👨‍🦰"), 6); +/// ``` +/// +/// This happens because the grapheme consists of three code points: +/// “👨” (U+1F468: Man), Zero Width Joiner (U+200D), and “🦰” +/// (U+1F9B0: Red Hair). You can see them above in the test. With +/// `unicode-width` enabled, the ZWJ is correctly seen as having zero +/// width, without it is counted as a double-width character. +/// +/// ## Terminal Support +/// +/// Modern browsers typically do a great job at combining characters +/// as shown above, but terminals often struggle more. As an example, +/// Gnome Terminal version 3.38.1, shows “❤️” as a big red heart, but +/// shows "👨‍🦰" as “👨🦰”. +/// +/// [combining characters]: https://en.wikipedia.org/wiki/Combining_character +/// [Unicode equivalence]: https://en.wikipedia.org/wiki/Unicode_equivalence +/// [CJK characters]: https://en.wikipedia.org/wiki/CJK_characters +/// [emoji modifier sequences]: https://unicode.org/emoji/charts/full-emoji-modifiers.html +pub fn display_width(text: &str) -> usize { + let mut chars = text.chars(); + let mut width = 0; + while let Some(ch) = chars.next() { + if skip_ansi_escape_sequence(ch, &mut chars) { + continue; + } + width += ch_width(ch); + } + width +} + +/// A (text) fragment denotes the unit which we wrap into lines. +/// +/// Fragments represent an abstract _word_ plus the _whitespace_ +/// following the word. In case the word falls at the end of the line, +/// the whitespace is dropped and a so-called _penalty_ is inserted +/// instead (typically `"-"` if the word was hyphenated). +/// +/// For wrapping purposes, the precise content of the word, the +/// whitespace, and the penalty is irrelevant. All we need to know is +/// the displayed width of each part, which this trait provides. +pub trait Fragment: std::fmt::Debug { + /// Displayed width of word represented by this fragment. + fn width(&self) -> usize; + + /// Displayed width of the whitespace that must follow the word + /// when the word is not at the end of a line. + fn whitespace_width(&self) -> usize; + + /// Displayed width of the penalty that must be inserted if the + /// word falls at the end of a line. + fn penalty_width(&self) -> usize; +} + +/// A piece of wrappable text, including any trailing whitespace. +/// +/// A `Word` is an example of a [`Fragment`], so it has a width, +/// trailing whitespace, and potentially a penalty item. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct Word<'a> { + /// Word content. + pub word: &'a str, + /// Whitespace to insert if the word does not fall at the end of a line. + pub whitespace: &'a str, + /// Penalty string to insert if the word falls at the end of a line. + pub penalty: &'a str, + // Cached width in columns. + pub(crate) width: usize, +} + +impl std::ops::Deref for Word<'_> { + type Target = str; + + fn deref(&self) -> &Self::Target { + self.word + } +} + +impl<'a> Word<'a> { + /// Construct a `Word` from a string. + /// + /// A trailing stretch of `' '` is automatically taken to be the + /// whitespace part of the word. + pub fn from(word: &str) -> Word<'_> { + let trimmed = word.trim_end_matches(' '); + Word { + word: trimmed, + width: display_width(&trimmed), + whitespace: &word[trimmed.len()..], + penalty: "", + } + } + + /// Break this word into smaller words with a width of at most + /// `line_width`. The whitespace and penalty from this `Word` is + /// added to the last piece. + /// + /// # Examples + /// + /// ``` + /// use textwrap::core::Word; + /// assert_eq!( + /// Word::from("Hello! ").break_apart(3).collect::>(), + /// vec![Word::from("Hel"), Word::from("lo! ")] + /// ); + /// ``` + pub fn break_apart<'b>(&'b self, line_width: usize) -> impl Iterator> + 'b { + let mut char_indices = self.word.char_indices(); + let mut offset = 0; + let mut width = 0; + + std::iter::from_fn(move || { + while let Some((idx, ch)) = char_indices.next() { + if skip_ansi_escape_sequence(ch, &mut char_indices.by_ref().map(|(_, ch)| ch)) { + continue; + } + + if width > 0 && width + ch_width(ch) > line_width { + let word = Word { + word: &self.word[offset..idx], + width: width, + whitespace: "", + penalty: "", + }; + offset = idx; + width = ch_width(ch); + return Some(word); + } + + width += ch_width(ch); + } + + if offset < self.word.len() { + let word = Word { + word: &self.word[offset..], + width: width, + whitespace: self.whitespace, + penalty: self.penalty, + }; + offset = self.word.len(); + return Some(word); + } + + None + }) + } +} + +impl Fragment for Word<'_> { + #[inline] + fn width(&self) -> usize { + self.width + } + + // We assume the whitespace consist of ' ' only. This allows us to + // compute the display width in constant time. + #[inline] + fn whitespace_width(&self) -> usize { + self.whitespace.len() + } + + // We assume the penalty is `""` or `"-"`. This allows us to + // compute the display width in constant time. + #[inline] + fn penalty_width(&self) -> usize { + self.penalty.len() + } +} + +/// Forcibly break words wider than `line_width` into smaller words. +/// +/// This simply calls [`Word::break_apart`] on words that are too +/// wide. This means that no extra `'-'` is inserted, the word is +/// simply broken into smaller pieces. +pub fn break_words<'a, I>(words: I, line_width: usize) -> Vec> +where + I: IntoIterator>, +{ + let mut shortened_words = Vec::new(); + for word in words { + if word.width() > line_width { + shortened_words.extend(word.break_apart(line_width)); + } else { + shortened_words.push(word); + } + } + shortened_words +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(feature = "unicode-width")] + use unicode_width::UnicodeWidthChar; + + #[test] + fn skip_ansi_escape_sequence_works() { + let blue_text = "\u{1b}[34mHello\u{1b}[0m"; + let mut chars = blue_text.chars(); + let ch = chars.next().unwrap(); + assert!(skip_ansi_escape_sequence(ch, &mut chars)); + assert_eq!(chars.next(), Some('H')); + } + + #[test] + fn emojis_have_correct_width() { + use unic_emoji_char::is_emoji; + + // Emojis in the Basic Latin (ASCII) and Latin-1 Supplement + // blocks all have a width of 1 column. This includes + // characters such as '#' and '©'. + for ch in '\u{1}'..'\u{FF}' { + if is_emoji(ch) { + let desc = format!("{:?} U+{:04X}", ch, ch as u32); + + #[cfg(feature = "unicode-width")] + assert_eq!(ch.width().unwrap(), 1, "char: {}", desc); + + #[cfg(not(feature = "unicode-width"))] + assert_eq!(ch_width(ch), 1, "char: {}", desc); + } + } + + // Emojis in the remaining blocks of the Basic Multilingual + // Plane (BMP), in the Supplementary Multilingual Plane (SMP), + // and in the Supplementary Ideographic Plane (SIP), are all 1 + // or 2 columns wide when unicode-width is used, and always 2 + // columns wide otherwise. This includes all of our favorite + // emojis such as 😊. + for ch in '\u{FF}'..'\u{2FFFF}' { + if is_emoji(ch) { + let desc = format!("{:?} U+{:04X}", ch, ch as u32); + + #[cfg(feature = "unicode-width")] + assert!(ch.width().unwrap() <= 2, "char: {}", desc); + + #[cfg(not(feature = "unicode-width"))] + assert_eq!(ch_width(ch), 2, "char: {}", desc); + } + } + + // The remaining planes contain almost no assigned code points + // and thus also no emojis. + } + + #[test] + fn display_width_works() { + assert_eq!("Café Plain".len(), 11); // “é” is two bytes + assert_eq!(display_width("Café Plain"), 10); + assert_eq!(display_width("\u{1b}[31mCafé Rouge\u{1b}[0m"), 10); + } + + #[test] + fn display_width_narrow_emojis() { + #[cfg(feature = "unicode-width")] + assert_eq!(display_width("⁉"), 1); + + // The ⁉ character is above DOUBLE_WIDTH_CUTOFF. + #[cfg(not(feature = "unicode-width"))] + assert_eq!(display_width("⁉"), 2); + } + + #[test] + fn display_width_narrow_emojis_variant_selector() { + #[cfg(feature = "unicode-width")] + assert_eq!(display_width("⁉\u{fe0f}"), 1); + + // The variant selector-16 is also counted. + #[cfg(not(feature = "unicode-width"))] + assert_eq!(display_width("⁉\u{fe0f}"), 4); + } + + #[test] + fn display_width_emojis() { + assert_eq!(display_width("😂😭🥺🤣✨😍🙏🥰😊🔥"), 20); + } +} diff --git a/third_party/rust/textwrap/src/indentation.rs b/third_party/rust/textwrap/src/indentation.rs index 276ba1055345..5d90c0615692 100644 --- a/third_party/rust/textwrap/src/indentation.rs +++ b/third_party/rust/textwrap/src/indentation.rs @@ -4,56 +4,71 @@ //! The functions here can be used to uniformly indent or dedent //! (unindent) word wrapped lines of text. -/// Add prefix to each non-empty line. +/// Indent each line by the given prefix. +/// +/// # Examples /// /// ``` /// use textwrap::indent; /// -/// assert_eq!(indent(" -/// Foo -/// Bar -/// ", " "), " -/// Foo -/// Bar -/// "); +/// assert_eq!(indent("First line.\nSecond line.\n", " "), +/// " First line.\n Second line.\n"); /// ``` /// -/// Empty lines (lines consisting only of whitespace) are not indented -/// and the whitespace is replaced by a single newline (`\n`): +/// When indenting, trailing whitespace is stripped from the prefix. +/// This means that empty lines remain empty afterwards: /// /// ``` /// use textwrap::indent; /// -/// assert_eq!(indent(" -/// Foo -/// -/// Bar -/// \t -/// Baz -/// ", "->"), " -/// ->Foo -/// -/// ->Bar -/// -/// ->Baz -/// "); +/// assert_eq!(indent("First line.\n\n\nSecond line.\n", " "), +/// " First line.\n\n\n Second line.\n"); /// ``` /// -/// Leading and trailing whitespace on non-empty lines is kept -/// unchanged: +/// Notice how `"\n\n\n"` remained as `"\n\n\n"`. +/// +/// This feature is useful when you want to indent text and have a +/// space between your prefix and the text. In this case, you _don't_ +/// want a trailing space on empty lines: /// /// ``` /// use textwrap::indent; /// -/// assert_eq!(indent(" \t Foo ", "->"), "-> \t Foo \n"); +/// assert_eq!(indent("foo = 123\n\nprint(foo)\n", "# "), +/// "# foo = 123\n#\n# print(foo)\n"); +/// ``` +/// +/// Notice how `"\n\n"` became `"\n#\n"` instead of `"\n# \n"` which +/// would have trailing whitespace. +/// +/// Leading and trailing whitespace coming from the text itself is +/// kept unchanged: +/// +/// ``` +/// use textwrap::indent; +/// +/// assert_eq!(indent(" \t Foo ", "->"), "-> \t Foo "); /// ``` pub fn indent(s: &str, prefix: &str) -> String { - let mut result = String::new(); - for line in s.lines() { - if line.chars().any(|c| !c.is_whitespace()) { - result.push_str(prefix); - result.push_str(line); + // We know we'll need more than s.len() bytes for the output, but + // without counting '\n' characters (which is somewhat slow), we + // don't know exactly how much. However, we can preemptively do + // the first doubling of the output size. + let mut result = String::with_capacity(2 * s.len()); + let trimmed_prefix = prefix.trim_end(); + for (idx, line) in s.split_terminator('\n').enumerate() { + if idx > 0 { + result.push('\n'); } + if line.trim().is_empty() { + result.push_str(trimmed_prefix); + } else { + result.push_str(prefix); + } + result.push_str(line); + } + if s.ends_with('\n') { + // split_terminator will have eaten the final '\n'. result.push('\n'); } result @@ -138,41 +153,43 @@ pub fn dedent(s: &str) -> String { mod tests { use super::*; - /// Add newlines. Ensures that the final line in the vector also - /// has a newline. - fn add_nl(lines: &[&str]) -> String { - lines.join("\n") + "\n" - } - #[test] fn indent_empty() { assert_eq!(indent("\n", " "), "\n"); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn indent_nonempty() { - let x = vec![" foo", - "bar", - " baz"]; - let y = vec!["// foo", - "//bar", - "// baz"]; - assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y)); + let text = [ + " foo\n", + "bar\n", + " baz\n", + ].join(""); + let expected = [ + "// foo\n", + "// bar\n", + "// baz\n", + ].join(""); + assert_eq!(indent(&text, "// "), expected); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn indent_empty_line() { - let x = vec![" foo", - "bar", - "", - " baz"]; - let y = vec!["// foo", - "//bar", - "", - "// baz"]; - assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y)); + let text = [ + " foo", + "bar", + "", + " baz", + ].join("\n"); + let expected = [ + "// foo", + "// bar", + "//", + "// baz", + ].join("\n"); + assert_eq!(indent(&text, "// "), expected); } #[test] @@ -181,114 +198,150 @@ mod tests { } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_multi_line() { - let x = vec![" foo", - " bar", - " baz"]; - let y = vec![" foo", - "bar", - " baz"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + " foo", + " bar", + " baz", + ].join("\n"); + let y = [ + " foo", + "bar", + " baz" + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_empty_line() { - let x = vec![" foo", - " bar", - " ", - " baz"]; - let y = vec![" foo", - "bar", - "", - " baz"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + " foo", + " bar", + " ", + " baz" + ].join("\n"); + let y = [ + " foo", + "bar", + "", + " baz" + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_blank_line() { - let x = vec![" foo", - "", - " bar", - " foo", - " bar", - " baz"]; - let y = vec!["foo", - "", - " bar", - " foo", - " bar", - " baz"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + " foo", + "", + " bar", + " foo", + " bar", + " baz", + ].join("\n"); + let y = [ + "foo", + "", + " bar", + " foo", + " bar", + " baz", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_whitespace_line() { - let x = vec![" foo", - " ", - " bar", - " foo", - " bar", - " baz"]; - let y = vec!["foo", - "", - " bar", - " foo", - " bar", - " baz"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + " foo", + " ", + " bar", + " foo", + " bar", + " baz", + ].join("\n"); + let y = [ + "foo", + "", + " bar", + " foo", + " bar", + " baz", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_mixed_whitespace() { - let x = vec!["\tfoo", - " bar"]; - let y = vec!["\tfoo", - " bar"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + "\tfoo", + " bar", + ].join("\n"); + let y = [ + "\tfoo", + " bar", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_tabbed_whitespace() { - let x = vec!["\t\tfoo", - "\t\t\tbar"]; - let y = vec!["foo", - "\tbar"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + "\t\tfoo", + "\t\t\tbar", + ].join("\n"); + let y = [ + "foo", + "\tbar", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_mixed_tabbed_whitespace() { - let x = vec!["\t \tfoo", - "\t \t\tbar"]; - let y = vec!["foo", - "\tbar"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + "\t \tfoo", + "\t \t\tbar", + ].join("\n"); + let y = [ + "foo", + "\tbar", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_mixed_tabbed_whitespace2() { - let x = vec!["\t \tfoo", - "\t \tbar"]; - let y = vec!["\tfoo", - " \tbar"]; - assert_eq!(dedent(&add_nl(&x)), add_nl(&y)); + let x = [ + "\t \tfoo", + "\t \tbar", + ].join("\n"); + let y = [ + "\tfoo", + " \tbar", + ].join("\n"); + assert_eq!(dedent(&x), y); } #[test] - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn dedent_preserve_no_terminating_newline() { - let x = vec![" foo", - " bar"].join("\n"); - let y = vec!["foo", - " bar"].join("\n"); + let x = [ + " foo", + " bar", + ].join("\n"); + let y = [ + "foo", + " bar", + ].join("\n"); assert_eq!(dedent(&x), y); } } diff --git a/third_party/rust/textwrap/src/lib.rs b/third_party/rust/textwrap/src/lib.rs index 2f82325fbc2e..f2f5542d586f 100644 --- a/third_party/rust/textwrap/src/lib.rs +++ b/third_party/rust/textwrap/src/lib.rs @@ -1,20 +1,20 @@ -//! `textwrap` provides functions for word wrapping and filling text. +//! The textwrap library provides functions for word wrapping and +//! indenting text. //! -//! Wrapping text can be very useful in commandline programs where you -//! want to format dynamic output nicely so it looks good in a +//! # Wrapping Text +//! +//! Wrapping text can be very useful in command-line programs where +//! you want to format dynamic output nicely so it looks good in a //! terminal. A quick example: //! //! ```no_run -//! extern crate textwrap; -//! use textwrap::fill; -//! //! fn main() { //! let text = "textwrap: a small library for wrapping text."; -//! println!("{}", fill(text, 18)); +//! println!("{}", textwrap::fill(text, 18)); //! } //! ``` //! -//! This will display the following output: +//! When you run this program, it will display the following output: //! //! ```text //! textwrap: a small @@ -22,11 +22,48 @@ //! wrapping text. //! ``` //! -//! # Displayed Width vs Byte Size +//! If you enable the `hyphenation` Cargo feature, you can get +//! automatic hyphenation for a number of languages: +//! +//! ```no_run +//! # #[cfg(feature = "hyphenation")] +//! use hyphenation::{Language, Load, Standard}; +//! use textwrap::{fill, Options}; +//! +//! # #[cfg(feature = "hyphenation")] +//! fn main() { +//! let text = "textwrap: a small library for wrapping text."; +//! let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); +//! let options = Options::new(18).word_splitter(dictionary); +//! println!("{}", fill(text, &options)); +//! } +//! +//! # #[cfg(not(feature = "hyphenation"))] +//! # fn main() { } +//! ``` +//! +//! The program will now output: +//! +//! ```text +//! textwrap: a small +//! library for wrap- +//! ping text. +//! ``` +//! +//! See also the [`unfill`] and [`refill`] functions which allow you to +//! manipulate already wrapped text. +//! +//! ## Wrapping Strings at Compile Time +//! +//! If your strings are known at compile time, please take a look at +//! the procedural macros from the [textwrap-macros] crate. +//! +//! ## Displayed Width vs Byte Size //! //! To word wrap text, one must know the width of each word so one can -//! know when to break lines. This library measures the width of text -//! using the [displayed width][unicode-width], not the size in bytes. +//! know when to break lines. This library will by default measure the +//! width of text using the _displayed width_, not the size in bytes. +//! The `unicode-width` Cargo feature controls this. //! //! This is important for non-ASCII text. ASCII characters such as `a` //! and `!` are simple and take up one column each. This means that @@ -37,115 +74,430 @@ //! //! This is why we take care to use the displayed width instead of the //! byte count when computing line lengths. All functions in this -//! library handle Unicode characters like this. +//! library handle Unicode characters like this when the +//! `unicode-width` Cargo feature is enabled (it is enabled by +//! default). //! +//! # Indentation and Dedentation +//! +//! The textwrap library also offers functions for adding a prefix to +//! every line of a string and to remove leading whitespace. As an +//! example, the [`indent`] function allows you to turn lines of text +//! into a bullet list: +//! +//! ``` +//! let before = "\ +//! foo +//! bar +//! baz +//! "; +//! let after = "\ +//! * foo +//! * bar +//! * baz +//! "; +//! assert_eq!(textwrap::indent(before, "* "), after); +//! ``` +//! +//! Removing leading whitespace is done with [`dedent`]: +//! +//! ``` +//! let before = " +//! Some +//! indented +//! text +//! "; +//! let after = " +//! Some +//! indented +//! text +//! "; +//! assert_eq!(textwrap::dedent(before), after); +//! ``` +//! +//! # Cargo Features +//! +//! The textwrap library can be slimmed down as needed via a number of +//! Cargo features. This means you only pay for the features you +//! actually use. +//! +//! The full dependency graph, where dashed lines indicate optional +//! dependencies, is shown below: +//! +//! +//! +//! ## Default Features +//! +//! These features are enabled by default: +//! +//! * `unicode-linebreak`: enables finding words using the +//! [unicode-linebreak] crate, which implements the line breaking +//! algorithm described in [Unicode Standard Annex +//! #14](https://www.unicode.org/reports/tr14/). +//! +//! This feature can be disabled if you are happy to find words +//! separated by ASCII space characters only. People wrapping text +//! with emojis or East-Asian characters will want most likely want +//! to enable this feature. See the +//! [`word_separators::WordSeparator`] trait for details. +//! +//! * `unicode-width`: enables correct width computation of non-ASCII +//! characters via the [unicode-width] crate. Without this feature, +//! every [`char`] is 1 column wide, except for emojis which are 2 +//! columns wide. See the [`core::display_width`] function for +//! details. +//! +//! This feature can be disabled if you only need to wrap ASCII +//! text, or if the functions in [`core`] are used directly with +//! [`core::Fragment`]s for which the widths have been computed in +//! other ways. +//! +//! * `smawk`: enables linear-time wrapping of the whole paragraph via +//! the [smawk] crate. See the [`wrap_algorithms::wrap_optimal_fit`] +//! function for details on the optimal-fit algorithm. +//! +//! This feature can be disabled if you only ever intend to use +//! [`wrap_algorithms::wrap_first_fit`]. +//! +//! ## Optional Features +//! +//! These Cargo features enable new functionality: +//! +//! * `terminal_size`: enables automatic detection of the terminal +//! width via the [terminal_size] crate. See the +//! [`Options::with_termwidth`] constructor for details. +//! +//! * `hyphenation`: enables language-sensitive hyphenation via the +//! [hyphenation] crate. See the [`word_splitters::WordSplitter`] trait for details. +//! +//! [unicode-linebreak]: https://docs.rs/unicode-linebreak/ //! [unicode-width]: https://docs.rs/unicode-width/ +//! [smawk]: https://docs.rs/smawk/ +//! [textwrap-macros]: https://docs.rs/textwrap-macros/ +//! [terminal_size]: https://docs.rs/terminal_size/ +//! [hyphenation]: https://docs.rs/hyphenation/ -#![doc(html_root_url = "https://docs.rs/textwrap/0.11.0")] +#![doc(html_root_url = "https://docs.rs/textwrap/0.14.2")] +#![forbid(unsafe_code)] // See https://github.com/mgeisler/textwrap/issues/210 #![deny(missing_docs)] #![deny(missing_debug_implementations)] - -#[cfg(feature = "hyphenation")] -extern crate hyphenation; -#[cfg(feature = "term_size")] -extern crate term_size; -extern crate unicode_width; +#![allow(clippy::redundant_field_names)] use std::borrow::Cow; -use std::str::CharIndices; - -use unicode_width::UnicodeWidthChar; -use unicode_width::UnicodeWidthStr; - -/// A non-breaking space. -const NBSP: char = '\u{a0}'; mod indentation; -pub use indentation::dedent; -pub use indentation::indent; +pub use crate::indentation::dedent; +pub use crate::indentation::indent; -mod splitting; -pub use splitting::{HyphenSplitter, NoHyphenation, WordSplitter}; +pub mod word_separators; +pub mod word_splitters; +pub mod wrap_algorithms; -/// A Wrapper holds settings for wrapping and filling text. Use it -/// when the convenience [`wrap_iter`], [`wrap`] and [`fill`] functions -/// are not flexible enough. -/// -/// [`wrap_iter`]: fn.wrap_iter.html -/// [`wrap`]: fn.wrap.html -/// [`fill`]: fn.fill.html -/// -/// The algorithm used by the `WrapIter` iterator (returned from the -/// `wrap_iter` method) works by doing successive partial scans over -/// words in the input string (where each single scan yields a single -/// line) so that the overall time and memory complexity is O(*n*) where -/// *n* is the length of the input string. -#[derive(Clone, Debug)] -pub struct Wrapper<'a, S: WordSplitter> { +pub mod core; + +// These private macros lets us hide the actual WrapAlgorithm and +// WordSeperator used in the function signatures below. +#[cfg(feature = "smawk")] +macro_rules! DefaultWrapAlgorithm { + () => { + wrap_algorithms::OptimalFit + }; +} + +#[cfg(not(feature = "smawk"))] +macro_rules! DefaultWrapAlgorithm { + () => { + wrap_algorithms::FirstFit + }; +} + +#[cfg(feature = "unicode-linebreak")] +macro_rules! DefaultWordSeparator { + () => { + word_separators::UnicodeBreakProperties + }; +} + +#[cfg(not(feature = "unicode-linebreak"))] +macro_rules! DefaultWordSeparator { + () => { + word_separators::AsciiSpace + }; +} + +/// Holds settings for wrapping and filling text. +#[derive(Debug, Clone)] +pub struct Options< + 'a, + WrapAlgo = Box, + WordSep = Box, + WordSplit = Box, +> { /// The width in columns at which the text will be wrapped. pub width: usize, - /// Indentation used for the first line of output. + /// Indentation used for the first line of output. See the + /// [`Options::initial_indent`] method. pub initial_indent: &'a str, - /// Indentation used for subsequent lines of output. + /// Indentation used for subsequent lines of output. See the + /// [`Options::subsequent_indent`] method. pub subsequent_indent: &'a str, /// Allow long words to be broken if they cannot fit on a line. /// When set to `false`, some lines may be longer than - /// `self.width`. + /// `self.width`. See the [`Options::break_words`] method. pub break_words: bool, - /// The method for splitting words. If the `hyphenation` feature - /// is enabled, you can use a `hyphenation::Standard` dictionary - /// here to get language-aware hyphenation. - pub splitter: S, + /// Wrapping algorithm to use, see the implementations of the + /// [`wrap_algorithms::WrapAlgorithm`] trait for details. + pub wrap_algorithm: WrapAlgo, + /// The line breaking algorithm to use, see + /// [`word_separators::WordSeparator`] trait for an overview and + /// possible implementations. + pub word_separator: WordSep, + /// The method for splitting words. This can be used to prohibit + /// splitting words on hyphens, or it can be used to implement + /// language-aware machine hyphenation. Please see the + /// [`word_splitters::WordSplitter`] trait for details. + pub word_splitter: WordSplit, } -impl<'a> Wrapper<'a, HyphenSplitter> { - /// Create a new Wrapper for wrapping at the specified width. By - /// default, we allow words longer than `width` to be broken. A - /// [`HyphenSplitter`] will be used by default for splitting - /// words. See the [`WordSplitter`] trait for other options. +impl<'a, WrapAlgo, WordSep, WordSplit> From<&'a Options<'a, WrapAlgo, WordSep, WordSplit>> + for Options<'a, WrapAlgo, WordSep, WordSplit> +where + WrapAlgo: Clone, + WordSep: Clone, + WordSplit: Clone, +{ + fn from(options: &'a Options<'a, WrapAlgo, WordSep, WordSplit>) -> Self { + Self { + width: options.width, + initial_indent: options.initial_indent, + subsequent_indent: options.subsequent_indent, + break_words: options.break_words, + word_separator: options.word_separator.clone(), + wrap_algorithm: options.wrap_algorithm.clone(), + word_splitter: options.word_splitter.clone(), + } + } +} + +impl<'a> From + for Options< + 'a, + DefaultWrapAlgorithm!(), + DefaultWordSeparator!(), + word_splitters::HyphenSplitter, + > +{ + fn from(width: usize) -> Self { + Options::new(width) + } +} + +/// Constructors for boxed Options, specifically. +impl<'a> + Options<'a, DefaultWrapAlgorithm!(), DefaultWordSeparator!(), word_splitters::HyphenSplitter> +{ + /// Creates a new [`Options`] with the specified width and static + /// dispatch using the [`word_splitters::HyphenSplitter`]. + /// Equivalent to /// - /// [`HyphenSplitter`]: struct.HyphenSplitter.html - /// [`WordSplitter`]: trait.WordSplitter.html - pub fn new(width: usize) -> Wrapper<'a, HyphenSplitter> { - Wrapper::with_splitter(width, HyphenSplitter) + /// ``` + /// # use textwrap::word_splitters::{HyphenSplitter, WordSplitter}; + /// # use textwrap::Options; + /// # let width = 80; + /// # let actual = Options::new(width); + /// # let expected = + /// Options { + /// width: width, + /// initial_indent: "", + /// subsequent_indent: "", + /// break_words: true, + /// #[cfg(feature = "unicode-linebreak")] + /// word_separator: textwrap::word_separators::UnicodeBreakProperties, + /// #[cfg(not(feature = "unicode-linebreak"))] + /// word_separator: textwrap::word_separators::AsciiSpace, + /// #[cfg(feature = "smawk")] + /// wrap_algorithm: textwrap::wrap_algorithms::OptimalFit, + /// #[cfg(not(feature = "smawk"))] + /// wrap_algorithm: textwrap::wrap_algorithms::FirstFit, + /// word_splitter: textwrap::word_splitters::HyphenSplitter, + /// } + /// # ; + /// # assert_eq!(actual.width, expected.width); + /// # assert_eq!(actual.initial_indent, expected.initial_indent); + /// # assert_eq!(actual.subsequent_indent, expected.subsequent_indent); + /// # assert_eq!(actual.break_words, expected.break_words); + /// ``` + /// + /// Note that the default word separator and wrap algorithms + /// changes based on the available Cargo features. The best + /// available algorithm is used by default. + /// + /// Static dispatch means here, that the word splitter is stored as-is + /// and the type is known at compile-time. Thus the returned value + /// is actually a `Options`. + /// + /// Dynamic dispatch on the other hand, means that the word + /// separator and/or word splitter is stored as a trait object + /// such as a `Box`. This way + /// the word splitter's inner type can be changed without changing + /// the type of this struct, which then would be just `Options` as + /// a short cut for `Options, Box>`. + /// + /// The value and type of the word splitter can be choose from the + /// start using the [`Options::with_word_splitter`] constructor or + /// changed afterwards using the [`Options::word_splitter`] + /// method. Whether static or dynamic dispatch is used, depends on + /// whether these functions are given a boxed + /// [`word_splitters::WordSplitter`] or not. Take for example: + /// + /// ``` + /// use textwrap::Options; + /// use textwrap::word_splitters::{HyphenSplitter, NoHyphenation}; + /// # use textwrap::word_splitters::WordSplitter; + /// # use textwrap::word_separators::AsciiSpace; + /// # let width = 80; + /// + /// // uses HyphenSplitter with static dispatch + /// // the actual type: Options + /// let opt = Options::new(width); + /// + /// // uses NoHyphenation with static dispatch + /// // the actual type: Options + /// let opt = Options::new(width).word_splitter(NoHyphenation); + /// + /// // uses HyphenSplitter with dynamic dispatch + /// // the actual type: Options> + /// let opt: Options<_, _, _> = Options::new(width).word_splitter(Box::new(HyphenSplitter)); + /// + /// // uses NoHyphenation with dynamic dispatch + /// // the actual type: Options> + /// let opt: Options<_, _, _> = Options::new(width).word_splitter(Box::new(NoHyphenation)); + /// ``` + /// + /// Notice that the last two variables have the same type, despite + /// the different `WordSplitter` in use. Thus dynamic dispatch + /// allows to change the word splitter at run-time without + /// changing the variables type. + pub const fn new(width: usize) -> Self { + Options::with_word_splitter(width, word_splitters::HyphenSplitter) } - /// Create a new Wrapper for wrapping text at the current terminal - /// width. If the terminal width cannot be determined (typically - /// because the standard input and output is not connected to a - /// terminal), a width of 80 characters will be used. Other - /// settings use the same defaults as `Wrapper::new`. + /// Creates a new [`Options`] with `width` set to the current + /// terminal width. If the terminal width cannot be determined + /// (typically because the standard input and output is not + /// connected to a terminal), a width of 80 characters will be + /// used. Other settings use the same defaults as + /// [`Options::new`]. /// /// Equivalent to: /// /// ```no_run - /// # #![allow(unused_variables)] - /// use textwrap::{Wrapper, termwidth}; + /// use textwrap::{termwidth, Options}; /// - /// let wrapper = Wrapper::new(termwidth()); + /// let options = Options::new(termwidth()); /// ``` - #[cfg(feature = "term_size")] - pub fn with_termwidth() -> Wrapper<'a, HyphenSplitter> { - Wrapper::new(termwidth()) + /// + /// **Note:** Only available when the `terminal_size` feature is + /// enabled. + #[cfg(feature = "terminal_size")] + pub fn with_termwidth() -> Self { + Self::new(termwidth()) } } -impl<'a, S: WordSplitter> Wrapper<'a, S> { - /// Use the given [`WordSplitter`] to create a new Wrapper for - /// wrapping at the specified width. By default, we allow words - /// longer than `width` to be broken. +impl<'a, WordSplit> Options<'a, DefaultWrapAlgorithm!(), DefaultWordSeparator!(), WordSplit> { + /// Creates a new [`Options`] with the specified width and + /// word splitter. Equivalent to /// - /// [`WordSplitter`]: trait.WordSplitter.html - pub fn with_splitter(width: usize, splitter: S) -> Wrapper<'a, S> { - Wrapper { - width: width, + /// ``` + /// # use textwrap::Options; + /// # use textwrap::word_splitters::{NoHyphenation, HyphenSplitter}; + /// # const word_splitter: NoHyphenation = NoHyphenation; + /// # const width: usize = 80; + /// # let actual = Options::with_word_splitter(width, word_splitter); + /// # let expected = + /// Options { + /// width: width, + /// initial_indent: "", + /// subsequent_indent: "", + /// break_words: true, + /// #[cfg(feature = "unicode-linebreak")] + /// word_separator: textwrap::word_separators::UnicodeBreakProperties, + /// #[cfg(not(feature = "unicode-linebreak"))] + /// word_separator: textwrap::word_separators::AsciiSpace, + /// #[cfg(feature = "smawk")] + /// wrap_algorithm: textwrap::wrap_algorithms::OptimalFit, + /// #[cfg(not(feature = "smawk"))] + /// wrap_algorithm: textwrap::wrap_algorithms::FirstFit, + /// word_splitter: word_splitter, + /// } + /// # ; + /// # assert_eq!(actual.width, expected.width); + /// # assert_eq!(actual.initial_indent, expected.initial_indent); + /// # assert_eq!(actual.subsequent_indent, expected.subsequent_indent); + /// # assert_eq!(actual.break_words, expected.break_words); + /// ``` + /// + /// This constructor allows to specify the word splitter to be + /// used. It is like a short-cut for + /// `Options::new(w).word_splitter(s)`, but this function is a + /// `const fn`. The given word splitter may be in a [`Box`], which + /// then can be coerced into a trait object for dynamic dispatch: + /// + /// ``` + /// use textwrap::Options; + /// use textwrap::word_splitters::{HyphenSplitter, NoHyphenation, WordSplitter}; + /// # const width: usize = 80; + /// + /// // This opt contains a boxed trait object as splitter. + /// // The type annotation is important, otherwise it will be not a trait object + /// let mut opt: Options<_, _, Box> + /// = Options::with_word_splitter(width, Box::new(NoHyphenation)); + /// // Its type is actually: `Options>`: + /// let opt_coerced: Options<_, _, Box> = opt; + /// + /// // Thus, it can be overridden with a different word splitter. + /// opt = Options::with_word_splitter(width, Box::new(HyphenSplitter)); + /// // Now, containing a `HyphenSplitter` instead. + /// ``` + /// + /// Since the word splitter is given by value, which determines + /// the generic type parameter, it can be used to produce both an + /// [`Options`] with static and dynamic dispatch, respectively. + /// While dynamic dispatch allows to change the type of the inner + /// word splitter at run time as seen above, static dispatch + /// especially can store the word splitter directly, without the + /// need for a box. This in turn allows it to be used in constant + /// and static context: + /// + /// ``` + /// use textwrap::word_splitters::HyphenSplitter; use textwrap::{ Options}; + /// use textwrap::word_separators::AsciiSpace; + /// use textwrap::wrap_algorithms::FirstFit; + /// # const width: usize = 80; + /// + /// # #[cfg(all(not(feature = "smawk"), not(feature = "unicode-linebreak")))] { + /// const FOO: Options = + /// Options::with_word_splitter(width, HyphenSplitter); + /// static BAR: Options = FOO; + /// # } + /// ``` + pub const fn with_word_splitter(width: usize, word_splitter: WordSplit) -> Self { + Options { + width, initial_indent: "", subsequent_indent: "", break_words: true, - splitter: splitter, + word_separator: DefaultWordSeparator!(), + wrap_algorithm: DefaultWrapAlgorithm!(), + word_splitter: word_splitter, } } +} +impl<'a, WrapAlgo, WordSep, WordSplit> Options<'a, WrapAlgo, WordSep, WordSplit> { /// Change [`self.initial_indent`]. The initial indentation is /// used on the very first line of output. /// @@ -154,16 +506,18 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> { /// Classic paragraph indentation can be achieved by specifying an /// initial indentation and wrapping each paragraph by itself: /// - /// ```no_run - /// # #![allow(unused_variables)] - /// use textwrap::Wrapper; + /// ``` + /// use textwrap::{Options, wrap}; /// - /// let wrapper = Wrapper::new(15).initial_indent(" "); + /// let options = Options::new(16).initial_indent(" "); + /// assert_eq!(wrap("This is a little example.", options), + /// vec![" This is a", + /// "little example."]); /// ``` /// /// [`self.initial_indent`]: #structfield.initial_indent - pub fn initial_indent(self, indent: &'a str) -> Wrapper<'a, S> { - Wrapper { + pub fn initial_indent(self, indent: &'a str) -> Self { + Options { initial_indent: indent, ..self } @@ -177,18 +531,29 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> { /// Combining initial and subsequent indentation lets you format a /// single paragraph as a bullet list: /// - /// ```no_run - /// # #![allow(unused_variables)] - /// use textwrap::Wrapper; + /// ``` + /// use textwrap::{Options, wrap}; /// - /// let wrapper = Wrapper::new(15) + /// let options = Options::new(12) /// .initial_indent("* ") /// .subsequent_indent(" "); + /// #[cfg(feature = "smawk")] + /// assert_eq!(wrap("This is a little example.", options), + /// vec!["* This is", + /// " a little", + /// " example."]); + /// + /// // Without the `smawk` feature, the wrapping is a little different: + /// #[cfg(not(feature = "smawk"))] + /// assert_eq!(wrap("This is a little example.", options), + /// vec!["* This is a", + /// " little", + /// " example."]); /// ``` /// /// [`self.subsequent_indent`]: #structfield.subsequent_indent - pub fn subsequent_indent(self, indent: &'a str) -> Wrapper<'a, S> { - Wrapper { + pub fn subsequent_indent(self, indent: &'a str) -> Self { + Options { subsequent_indent: indent, ..self } @@ -198,528 +563,863 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> { /// than `self.width` can be broken, or if they will be left /// sticking out into the right margin. /// + /// # Examples + /// + /// ``` + /// use textwrap::{wrap, Options}; + /// + /// let options = Options::new(4).break_words(true); + /// assert_eq!(wrap("This is a little example.", options), + /// vec!["This", + /// "is a", + /// "litt", + /// "le", + /// "exam", + /// "ple."]); + /// ``` + /// /// [`self.break_words`]: #structfield.break_words - pub fn break_words(self, setting: bool) -> Wrapper<'a, S> { - Wrapper { + pub fn break_words(self, setting: bool) -> Self { + Options { break_words: setting, ..self } } - /// Fill a line of text at `self.width` characters. Strings are - /// wrapped based on their displayed width, not their size in - /// bytes. + /// Change [`self.word_separator`]. /// - /// The result is a string with newlines between each line. Use - /// the `wrap` method if you need access to the individual lines. + /// See [`word_separators::WordSeparator`] for details on the choices. /// - /// # Complexities - /// - /// This method simply joins the lines produced by `wrap_iter`. As - /// such, it inherits the O(*n*) time and memory complexity where - /// *n* is the input string length. - /// - /// # Examples - /// - /// ``` - /// use textwrap::Wrapper; - /// - /// let wrapper = Wrapper::new(15); - /// assert_eq!(wrapper.fill("Memory safety without garbage collection."), - /// "Memory safety\nwithout garbage\ncollection."); - /// ``` - pub fn fill(&self, s: &str) -> String { - // This will avoid reallocation in simple cases (no - // indentation, no hyphenation). - let mut result = String::with_capacity(s.len()); - - for (i, line) in self.wrap_iter(s).enumerate() { - if i > 0 { - result.push('\n'); - } - result.push_str(&line); - } - - result - } - - /// Wrap a line of text at `self.width` characters. Strings are - /// wrapped based on their displayed width, not their size in - /// bytes. - /// - /// # Complexities - /// - /// This method simply collects the lines produced by `wrap_iter`. - /// As such, it inherits the O(*n*) overall time and memory - /// complexity where *n* is the input string length. - /// - /// # Examples - /// - /// ``` - /// use textwrap::Wrapper; - /// - /// let wrap15 = Wrapper::new(15); - /// assert_eq!(wrap15.wrap("Concurrency without data races."), - /// vec!["Concurrency", - /// "without data", - /// "races."]); - /// - /// let wrap20 = Wrapper::new(20); - /// assert_eq!(wrap20.wrap("Concurrency without data races."), - /// vec!["Concurrency without", - /// "data races."]); - /// ``` - /// - /// Notice that newlines in the input are preserved. This means - /// that they force a line break, regardless of how long the - /// current line is: - /// - /// ``` - /// use textwrap::Wrapper; - /// - /// let wrapper = Wrapper::new(40); - /// assert_eq!(wrapper.wrap("First line.\nSecond line."), - /// vec!["First line.", "Second line."]); - /// ``` - /// - pub fn wrap(&self, s: &'a str) -> Vec> { - self.wrap_iter(s).collect::>() - } - - /// Lazily wrap a line of text at `self.width` characters. Strings - /// are wrapped based on their displayed width, not their size in - /// bytes. - /// - /// The [`WordSplitter`] stored in [`self.splitter`] is used - /// whenever when a word is too large to fit on the current line. - /// By changing the field, different hyphenation strategies can be - /// implemented. - /// - /// # Complexities - /// - /// This method returns a [`WrapIter`] iterator which borrows this - /// `Wrapper`. The algorithm used has a linear complexity, so - /// getting the next line from the iterator will take O(*w*) time, - /// where *w* is the wrapping width. Fully processing the iterator - /// will take O(*n*) time for an input string of length *n*. - /// - /// When no indentation is used, each line returned is a slice of - /// the input string and the memory overhead is thus constant. - /// Otherwise new memory is allocated for each line returned. - /// - /// # Examples - /// - /// ``` - /// use std::borrow::Cow; - /// use textwrap::Wrapper; - /// - /// let wrap20 = Wrapper::new(20); - /// let mut wrap20_iter = wrap20.wrap_iter("Zero-cost abstractions."); - /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); - /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); - /// assert_eq!(wrap20_iter.next(), None); - /// - /// let wrap25 = Wrapper::new(25); - /// let mut wrap25_iter = wrap25.wrap_iter("Zero-cost abstractions."); - /// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions."))); - /// assert_eq!(wrap25_iter.next(), None); - /// ``` - /// - /// [`self.splitter`]: #structfield.splitter - /// [`WordSplitter`]: trait.WordSplitter.html - /// [`WrapIter`]: struct.WrapIter.html - pub fn wrap_iter<'w>(&'w self, s: &'a str) -> WrapIter<'w, 'a, S> { - WrapIter { - wrapper: self, - inner: WrapIterImpl::new(self, s), + /// [`self.word_separator`]: #structfield.word_separator + pub fn word_separator( + self, + word_separator: NewWordSep, + ) -> Options<'a, WrapAlgo, NewWordSep, WordSplit> { + Options { + width: self.width, + initial_indent: self.initial_indent, + subsequent_indent: self.subsequent_indent, + break_words: self.break_words, + word_separator: word_separator, + wrap_algorithm: self.wrap_algorithm, + word_splitter: self.word_splitter, } } - /// Lazily wrap a line of text at `self.width` characters. Strings - /// are wrapped based on their displayed width, not their size in - /// bytes. + /// Change [`self.wrap_algorithm`]. /// - /// The [`WordSplitter`] stored in [`self.splitter`] is used - /// whenever when a word is too large to fit on the current line. - /// By changing the field, different hyphenation strategies can be - /// implemented. + /// See the [`wrap_algorithms::WrapAlgorithm`] trait for details on + /// the choices. /// - /// # Complexities - /// - /// This method consumes the `Wrapper` and returns a - /// [`IntoWrapIter`] iterator. Fully processing the iterator has - /// the same O(*n*) time complexity as [`wrap_iter`], where *n* is - /// the length of the input string. - /// - /// # Examples - /// - /// ``` - /// use std::borrow::Cow; - /// use textwrap::Wrapper; - /// - /// let wrap20 = Wrapper::new(20); - /// let mut wrap20_iter = wrap20.into_wrap_iter("Zero-cost abstractions."); - /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); - /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); - /// assert_eq!(wrap20_iter.next(), None); - /// ``` - /// - /// [`self.splitter`]: #structfield.splitter - /// [`WordSplitter`]: trait.WordSplitter.html - /// [`IntoWrapIter`]: struct.IntoWrapIter.html - /// [`wrap_iter`]: #method.wrap_iter - pub fn into_wrap_iter(self, s: &'a str) -> IntoWrapIter<'a, S> { - let inner = WrapIterImpl::new(&self, s); + /// [`self.wrap_algorithm`]: #structfield.wrap_algorithm + pub fn wrap_algorithm( + self, + wrap_algorithm: NewWrapAlgo, + ) -> Options<'a, NewWrapAlgo, WordSep, WordSplit> { + Options { + width: self.width, + initial_indent: self.initial_indent, + subsequent_indent: self.subsequent_indent, + break_words: self.break_words, + word_separator: self.word_separator, + wrap_algorithm: wrap_algorithm, + word_splitter: self.word_splitter, + } + } - IntoWrapIter { - wrapper: self, - inner: inner, + /// Change [`self.word_splitter`]. The + /// [`word_splitters::WordSplitter`] is used to fit part of a word + /// into the current line when wrapping text. + /// + /// This function may return a different type than `Self`. That is + /// the case when the given `splitter` is of a different type the + /// the currently stored one in the `splitter` field. Take for + /// example: + /// + /// ``` + /// use textwrap::word_splitters::{HyphenSplitter, NoHyphenation}; + /// use textwrap::Options; + /// // The default type returned by `new`: + /// let opt: Options<_, _, HyphenSplitter> = Options::new(80); + /// // Setting a different word splitter changes the type + /// let opt: Options<_, _, NoHyphenation> = opt.word_splitter(NoHyphenation); + /// ``` + /// + /// [`self.word_splitter`]: #structfield.word_splitter + pub fn word_splitter( + self, + word_splitter: NewWordSplit, + ) -> Options<'a, WrapAlgo, WordSep, NewWordSplit> { + Options { + width: self.width, + initial_indent: self.initial_indent, + subsequent_indent: self.subsequent_indent, + break_words: self.break_words, + word_separator: self.word_separator, + wrap_algorithm: self.wrap_algorithm, + word_splitter, } } } -/// An iterator over the lines of the input string which owns a -/// `Wrapper`. An instance of `IntoWrapIter` is typically obtained -/// through either [`wrap_iter`] or [`Wrapper::into_wrap_iter`]. +/// Return the current terminal width. /// -/// Each call of `.next()` method yields a line wrapped in `Some` if the -/// input hasn't been fully processed yet. Otherwise it returns `None`. -/// -/// [`wrap_iter`]: fn.wrap_iter.html -/// [`Wrapper::into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter -#[derive(Debug)] -pub struct IntoWrapIter<'a, S: WordSplitter> { - wrapper: Wrapper<'a, S>, - inner: WrapIterImpl<'a>, -} - -impl<'a, S: WordSplitter> Iterator for IntoWrapIter<'a, S> { - type Item = Cow<'a, str>; - - fn next(&mut self) -> Option> { - self.inner.next(&self.wrapper) - } -} - -/// An iterator over the lines of the input string which borrows a -/// `Wrapper`. An instance of `WrapIter` is typically obtained -/// through the [`Wrapper::wrap_iter`] method. -/// -/// Each call of `.next()` method yields a line wrapped in `Some` if the -/// input hasn't been fully processed yet. Otherwise it returns `None`. -/// -/// [`Wrapper::wrap_iter`]: struct.Wrapper.html#method.wrap_iter -#[derive(Debug)] -pub struct WrapIter<'w, 'a: 'w, S: WordSplitter + 'w> { - wrapper: &'w Wrapper<'a, S>, - inner: WrapIterImpl<'a>, -} - -impl<'w, 'a: 'w, S: WordSplitter> Iterator for WrapIter<'w, 'a, S> { - type Item = Cow<'a, str>; - - fn next(&mut self) -> Option> { - self.inner.next(self.wrapper) - } -} - -/// Like `char::is_whitespace`, but non-breaking spaces don't count. -#[inline] -fn is_whitespace(ch: char) -> bool { - ch.is_whitespace() && ch != NBSP -} - -/// Common implementation details for `WrapIter` and `IntoWrapIter`. -#[derive(Debug)] -struct WrapIterImpl<'a> { - // String to wrap. - source: &'a str, - // CharIndices iterator over self.source. - char_indices: CharIndices<'a>, - // Byte index where the current line starts. - start: usize, - // Byte index of the last place where the string can be split. - split: usize, - // Size in bytes of the character at self.source[self.split]. - split_len: usize, - // Width of self.source[self.start..idx]. - line_width: usize, - // Width of self.source[self.start..self.split]. - line_width_at_split: usize, - // Tracking runs of whitespace characters. - in_whitespace: bool, - // Has iterator finished producing elements? - finished: bool, -} - -impl<'a> WrapIterImpl<'a> { - fn new(wrapper: &Wrapper<'a, S>, s: &'a str) -> WrapIterImpl<'a> { - WrapIterImpl { - source: s, - char_indices: s.char_indices(), - start: 0, - split: 0, - split_len: 0, - line_width: wrapper.initial_indent.width(), - line_width_at_split: wrapper.initial_indent.width(), - in_whitespace: false, - finished: false, - } - } - - fn create_result_line(&self, wrapper: &Wrapper<'a, S>) -> Cow<'a, str> { - if self.start == 0 { - Cow::from(wrapper.initial_indent) - } else { - Cow::from(wrapper.subsequent_indent) - } - } - - fn next(&mut self, wrapper: &Wrapper<'a, S>) -> Option> { - if self.finished { - return None; - } - - while let Some((idx, ch)) = self.char_indices.next() { - let char_width = ch.width().unwrap_or(0); - let char_len = ch.len_utf8(); - - if ch == '\n' { - self.split = idx; - self.split_len = char_len; - self.line_width_at_split = self.line_width; - self.in_whitespace = false; - - // If this is not the final line, return the current line. Otherwise, - // we will return the line with its line break after exiting the loop - if self.split + self.split_len < self.source.len() { - let mut line = self.create_result_line(wrapper); - line += &self.source[self.start..self.split]; - - self.start = self.split + self.split_len; - self.line_width = wrapper.subsequent_indent.width(); - - return Some(line); - } - } else if is_whitespace(ch) { - // Extend the previous split or create a new one. - if self.in_whitespace { - self.split_len += char_len; - } else { - self.split = idx; - self.split_len = char_len; - } - self.line_width_at_split = self.line_width + char_width; - self.in_whitespace = true; - } else if self.line_width + char_width > wrapper.width { - // There is no room for this character on the current - // line. Try to split the final word. - self.in_whitespace = false; - let remaining_text = &self.source[self.split + self.split_len..]; - let final_word = match remaining_text.find(is_whitespace) { - Some(i) => &remaining_text[..i], - None => remaining_text, - }; - - let mut hyphen = ""; - let splits = wrapper.splitter.split(final_word); - for &(head, hyp, _) in splits.iter().rev() { - if self.line_width_at_split + head.width() + hyp.width() <= wrapper.width { - // We can fit head into the current line. - // Advance the split point by the width of the - // whitespace and the head length. - self.split += self.split_len + head.len(); - self.split_len = 0; - hyphen = hyp; - break; - } - } - - if self.start >= self.split { - // The word is too big to fit on a single line, so we - // need to split it at the current index. - if wrapper.break_words { - // Break work at current index. - self.split = idx; - self.split_len = 0; - self.line_width_at_split = self.line_width; - } else { - // Add smallest split. - self.split = self.start + splits[0].0.len(); - self.split_len = 0; - self.line_width_at_split = self.line_width; - } - } - - if self.start < self.split { - let mut line = self.create_result_line(wrapper); - line += &self.source[self.start..self.split]; - line += hyphen; - - self.start = self.split + self.split_len; - self.line_width += wrapper.subsequent_indent.width(); - self.line_width -= self.line_width_at_split; - self.line_width += char_width; - - return Some(line); - } - } else { - self.in_whitespace = false; - } - self.line_width += char_width; - } - - self.finished = true; - - // Add final line. - if self.start < self.source.len() { - let mut line = self.create_result_line(wrapper); - line += &self.source[self.start..]; - return Some(line); - } - - None - } -} - -/// Return the current terminal width. If the terminal width cannot be -/// determined (typically because the standard output is not connected -/// to a terminal), a default width of 80 characters will be used. +/// If the terminal width cannot be determined (typically because the +/// standard output is not connected to a terminal), a default width +/// of 80 characters will be used. /// /// # Examples /// -/// Create a `Wrapper` for the current terminal with a two column -/// margin: +/// Create an [`Options`] for wrapping at the current terminal width +/// with a two column margin to the left and the right: /// /// ```no_run -/// # #![allow(unused_variables)] -/// use textwrap::{Wrapper, NoHyphenation, termwidth}; +/// use textwrap::{termwidth, Options}; +/// use textwrap::word_splitters::NoHyphenation; /// /// let width = termwidth() - 4; // Two columns on each side. -/// let wrapper = Wrapper::with_splitter(width, NoHyphenation) +/// let options = Options::new(width) +/// .word_splitter(NoHyphenation) /// .initial_indent(" ") /// .subsequent_indent(" "); /// ``` -#[cfg(feature = "term_size")] +/// +/// **Note:** Only available when the `terminal_size` Cargo feature is +/// enabled. +#[cfg(feature = "terminal_size")] pub fn termwidth() -> usize { - term_size::dimensions_stdout().map_or(80, |(w, _)| w) + terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into()) } -/// Fill a line of text at `width` characters. Strings are wrapped -/// based on their displayed width, not their size in bytes. +/// Fill a line of text at a given width. /// -/// The result is a string with newlines between each line. Use -/// [`wrap`] if you need access to the individual lines or -/// [`wrap_iter`] for its iterator counterpart. +/// The result is a [`String`], complete with newlines between each +/// line. Use the [`wrap`] function if you need access to the +/// individual lines. +/// +/// The easiest way to use this function is to pass an integer for +/// `width_or_options`: /// /// ``` /// use textwrap::fill; /// -/// assert_eq!(fill("Memory safety without garbage collection.", 15), -/// "Memory safety\nwithout garbage\ncollection."); +/// assert_eq!( +/// fill("Memory safety without garbage collection.", 15), +/// "Memory safety\nwithout garbage\ncollection." +/// ); /// ``` /// -/// This function creates a Wrapper on the fly with default settings. -/// If you need to set a language corpus for automatic hyphenation, or -/// need to fill many strings, then it is suggested to create a Wrapper -/// and call its [`fill` method]. +/// If you need to customize the wrapping, you can pass an [`Options`] +/// instead of an `usize`: /// -/// [`wrap`]: fn.wrap.html -/// [`wrap_iter`]: fn.wrap_iter.html -/// [`fill` method]: struct.Wrapper.html#method.fill -pub fn fill(s: &str, width: usize) -> String { - Wrapper::new(width).fill(s) +/// ``` +/// use textwrap::{fill, Options}; +/// +/// let options = Options::new(15) +/// .initial_indent("- ") +/// .subsequent_indent(" "); +/// assert_eq!( +/// fill("Memory safety without garbage collection.", &options), +/// "- Memory safety\n without\n garbage\n collection." +/// ); +/// ``` +pub fn fill<'a, WrapAlgo, WordSep, WordSplit, Opt>(text: &str, width_or_options: Opt) -> String +where + WrapAlgo: wrap_algorithms::WrapAlgorithm, + WordSep: word_separators::WordSeparator, + WordSplit: word_splitters::WordSplitter, + Opt: Into>, +{ + // This will avoid reallocation in simple cases (no + // indentation, no hyphenation). + let mut result = String::with_capacity(text.len()); + + for (i, line) in wrap(text, width_or_options).iter().enumerate() { + if i > 0 { + result.push('\n'); + } + result.push_str(&line); + } + + result } -/// Wrap a line of text at `width` characters. Strings are wrapped -/// based on their displayed width, not their size in bytes. +/// Unpack a paragraph of already-wrapped text. /// -/// This function creates a Wrapper on the fly with default settings. -/// If you need to set a language corpus for automatic hyphenation, or -/// need to wrap many strings, then it is suggested to create a Wrapper -/// and call its [`wrap` method]. +/// This function attempts to recover the original text from a single +/// paragraph of text produced by the [`fill`] function. This means +/// that it turns /// -/// The result is a vector of strings. Use [`wrap_iter`] if you need an -/// iterator version. +/// ```text +/// textwrap: a small +/// library for +/// wrapping text. +/// ``` +/// +/// back into +/// +/// ```text +/// textwrap: a small library for wrapping text. +/// ``` +/// +/// In addition, it will recognize a common prefix among the lines. +/// The prefix of the first line is returned in +/// [`Options::initial_indent`] and the prefix (if any) of the the +/// other lines is returned in [`Options::subsequent_indent`]. +/// +/// In addition to `' '`, the prefixes can consist of characters used +/// for unordered lists (`'-'`, `'+'`, and `'*'`) and block quotes +/// (`'>'`) in Markdown as well as characters often used for inline +/// comments (`'#'` and `'/'`). +/// +/// The text must come from a single wrapped paragraph. This means +/// that there can be no `"\n\n"` within the text. /// /// # Examples /// /// ``` +/// use textwrap::unfill; +/// +/// let (text, options) = unfill("\ +/// * This is an +/// example of +/// a list item. +/// "); +/// +/// assert_eq!(text, "This is an example of a list item.\n"); +/// assert_eq!(options.initial_indent, "* "); +/// assert_eq!(options.subsequent_indent, " "); +/// ``` +pub fn unfill( + text: &str, +) -> ( + String, + Options<'_, DefaultWrapAlgorithm!(), DefaultWordSeparator!(), word_splitters::HyphenSplitter>, +) { + let trimmed = text.trim_end_matches('\n'); + let prefix_chars: &[_] = &[' ', '-', '+', '*', '>', '#', '/']; + + let mut options = Options::new(0); + for (idx, line) in trimmed.split('\n').enumerate() { + options.width = std::cmp::max(options.width, core::display_width(line)); + let without_prefix = line.trim_start_matches(prefix_chars); + let prefix = &line[..line.len() - without_prefix.len()]; + + if idx == 0 { + options.initial_indent = prefix; + } else if idx == 1 { + options.subsequent_indent = prefix; + } else if idx > 1 { + for ((idx, x), y) in prefix.char_indices().zip(options.subsequent_indent.chars()) { + if x != y { + options.subsequent_indent = &prefix[..idx]; + break; + } + } + if prefix.len() < options.subsequent_indent.len() { + options.subsequent_indent = prefix; + } + } + } + + let mut unfilled = String::with_capacity(text.len()); + for (idx, line) in trimmed.split('\n').enumerate() { + if idx == 0 { + unfilled.push_str(&line[options.initial_indent.len()..]); + } else { + unfilled.push(' '); + unfilled.push_str(&line[options.subsequent_indent.len()..]); + } + } + + unfilled.push_str(&text[trimmed.len()..]); + (unfilled, options) +} + +/// Refill a paragraph of wrapped text with a new width. +/// +/// This function will first use the [`unfill`] function to remove +/// newlines from the text. Afterwards the text is filled again using +/// the [`fill`] function. +/// +/// The `new_width_or_options` argument specify the new width and can +/// specify other options as well — except for +/// [`Options::initial_indent`] and [`Options::subsequent_indent`], +/// which are deduced from `filled_text`. +/// +/// # Examples +/// +/// ``` +/// use textwrap::refill; +/// +/// // Some loosely wrapped text. The "> " prefix is recognized automatically. +/// let text = "\ +/// > Memory +/// > safety without garbage +/// > collection. +/// "; +/// +/// assert_eq!(refill(text, 20), "\ +/// > Memory safety +/// > without garbage +/// > collection. +/// "); +/// +/// assert_eq!(refill(text, 40), "\ +/// > Memory safety without garbage +/// > collection. +/// "); +/// +/// assert_eq!(refill(text, 60), "\ +/// > Memory safety without garbage collection. +/// "); +/// ``` +/// +/// You can also reshape bullet points: +/// +/// ``` +/// use textwrap::refill; +/// +/// let text = "\ +/// - This is my +/// list item. +/// "; +/// +/// assert_eq!(refill(text, 20), "\ +/// - This is my list +/// item. +/// "); +/// ``` +pub fn refill<'a, WrapAlgo, WordSep, WordSplit, Opt>( + filled_text: &str, + new_width_or_options: Opt, +) -> String +where + WrapAlgo: wrap_algorithms::WrapAlgorithm, + WordSep: word_separators::WordSeparator, + WordSplit: word_splitters::WordSplitter, + Opt: Into>, +{ + let trimmed = filled_text.trim_end_matches('\n'); + let (text, options) = unfill(trimmed); + let mut new_options = new_width_or_options.into(); + new_options.initial_indent = options.initial_indent; + new_options.subsequent_indent = options.subsequent_indent; + let mut refilled = fill(&text, new_options); + refilled.push_str(&filled_text[trimmed.len()..]); + refilled +} + +/// Wrap a line of text at a given width. +/// +/// The result is a vector of lines, each line is of type [`Cow<'_, +/// str>`](Cow), which means that the line will borrow from the input +/// `&str` if possible. The lines do not have trailing whitespace, +/// including a final `'\n'`. Please use the [`fill`] function if you +/// need a [`String`] instead. +/// +/// The easiest way to use this function is to pass an integer for +/// `width_or_options`: +/// +/// ``` /// use textwrap::wrap; /// -/// assert_eq!(wrap("Concurrency without data races.", 15), -/// vec!["Concurrency", -/// "without data", -/// "races."]); -/// -/// assert_eq!(wrap("Concurrency without data races.", 20), -/// vec!["Concurrency without", -/// "data races."]); +/// let lines = wrap("Memory safety without garbage collection.", 15); +/// assert_eq!(lines, &[ +/// "Memory safety", +/// "without garbage", +/// "collection.", +/// ]); /// ``` /// -/// [`wrap_iter`]: fn.wrap_iter.html -/// [`wrap` method]: struct.Wrapper.html#method.wrap -pub fn wrap(s: &str, width: usize) -> Vec> { - Wrapper::new(width).wrap(s) +/// If you need to customize the wrapping, you can pass an [`Options`] +/// instead of an `usize`: +/// +/// ``` +/// use textwrap::{wrap, Options}; +/// +/// let options = Options::new(15) +/// .initial_indent("- ") +/// .subsequent_indent(" "); +/// let lines = wrap("Memory safety without garbage collection.", &options); +/// assert_eq!(lines, &[ +/// "- Memory safety", +/// " without", +/// " garbage", +/// " collection.", +/// ]); +/// ``` +/// +/// # Optimal-Fit Wrapping +/// +/// By default, `wrap` will try to ensure an even right margin by +/// finding breaks which avoid short lines. We call this an +/// “optimal-fit algorithm” since the line breaks are computed by +/// considering all possible line breaks. The alternative is a +/// “first-fit algorithm” which simply accumulates words until they no +/// longer fit on the line. +/// +/// As an example, using the first-fit algorithm to wrap the famous +/// Hamlet quote “To be, or not to be: that is the question” in a +/// narrow column with room for only 10 characters looks like this: +/// +/// ``` +/// # use textwrap::{wrap_algorithms::FirstFit, Options, wrap}; +/// # +/// # let lines = wrap("To be, or not to be: that is the question", +/// # Options::new(10).wrap_algorithm(FirstFit)); +/// # assert_eq!(lines.join("\n") + "\n", "\ +/// To be, or +/// not to be: +/// that is +/// the +/// question +/// # "); +/// ``` +/// +/// Notice how the second to last line is quite narrow because +/// “question” was too large to fit? The greedy first-fit algorithm +/// doesn’t look ahead, so it has no other option than to put +/// “question” onto its own line. +/// +/// With the optimal-fit wrapping algorithm, the previous lines are +/// shortened slightly in order to make the word “is” go into the +/// second last line: +/// +/// ``` +/// # #[cfg(feature = "smawk")] { +/// # use textwrap::{Options, wrap}; +/// # use textwrap::wrap_algorithms::OptimalFit; +/// # +/// # let lines = wrap("To be, or not to be: that is the question", +/// # Options::new(10).wrap_algorithm(OptimalFit)); +/// # assert_eq!(lines.join("\n") + "\n", "\ +/// To be, +/// or not to +/// be: that +/// is the +/// question +/// # "); } +/// ``` +/// +/// Please see the [`wrap_algorithms::WrapAlgorithm`] trait for details. +/// +/// # Examples +/// +/// The returned iterator yields lines of type `Cow<'_, str>`. If +/// possible, the wrapped lines will borrow from the input string. As +/// an example, a hanging indentation, the first line can borrow from +/// the input, but the subsequent lines become owned strings: +/// +/// ``` +/// use std::borrow::Cow::{Borrowed, Owned}; +/// use textwrap::{wrap, Options}; +/// +/// let options = Options::new(15).subsequent_indent("...."); +/// let lines = wrap("Wrapping text all day long.", &options); +/// let annotated = lines +/// .iter() +/// .map(|line| match line { +/// Borrowed(text) => format!("[Borrowed] {}", text), +/// Owned(text) => format!("[Owned] {}", text), +/// }) +/// .collect::>(); +/// assert_eq!( +/// annotated, +/// &[ +/// "[Borrowed] Wrapping text", +/// "[Owned] ....all day", +/// "[Owned] ....long.", +/// ] +/// ); +/// ``` +/// +/// ## Leading and Trailing Whitespace +/// +/// As a rule, leading whitespace (indentation) is preserved and +/// trailing whitespace is discarded. +/// +/// In more details, when wrapping words into lines, words are found +/// by splitting the input text on space characters. One or more +/// spaces (shown here as “␣”) are attached to the end of each word: +/// +/// ```text +/// "Foo␣␣␣bar␣baz" -> ["Foo␣␣␣", "bar␣", "baz"] +/// ``` +/// +/// These words are then put into lines. The interword whitespace is +/// preserved, unless the lines are wrapped so that the `"Foo␣␣␣"` +/// word falls at the end of a line: +/// +/// ``` +/// use textwrap::wrap; +/// +/// assert_eq!(wrap("Foo bar baz", 10), vec!["Foo bar", "baz"]); +/// assert_eq!(wrap("Foo bar baz", 8), vec!["Foo", "bar baz"]); +/// ``` +/// +/// Notice how the trailing whitespace is removed in both case: in the +/// first example, `"bar␣"` becomes `"bar"` and in the second case +/// `"Foo␣␣␣"` becomes `"Foo"`. +/// +/// Leading whitespace is preserved when the following word fits on +/// the first line. To understand this, consider how words are found +/// in a text with leading spaces: +/// +/// ```text +/// "␣␣foo␣bar" -> ["␣␣", "foo␣", "bar"] +/// ``` +/// +/// When put into lines, the indentation is preserved if `"foo"` fits +/// on the first line, otherwise you end up with an empty line: +/// +/// ``` +/// use textwrap::wrap; +/// +/// assert_eq!(wrap(" foo bar", 8), vec![" foo", "bar"]); +/// assert_eq!(wrap(" foo bar", 4), vec!["", "foo", "bar"]); +/// ``` +pub fn wrap<'a, WrapAlgo, WordSep, WordSplit, Opt>( + text: &str, + width_or_options: Opt, +) -> Vec> +where + WrapAlgo: wrap_algorithms::WrapAlgorithm, + WordSep: word_separators::WordSeparator, + WordSplit: word_splitters::WordSplitter, + Opt: Into>, +{ + let options = width_or_options.into(); + + let initial_width = options + .width + .saturating_sub(core::display_width(options.initial_indent)); + let subsequent_width = options + .width + .saturating_sub(core::display_width(options.subsequent_indent)); + + let mut lines = Vec::new(); + for line in text.split('\n') { + let words = options.word_separator.find_words(line); + let split_words = word_splitters::split_words(words, &options.word_splitter); + let broken_words = if options.break_words { + let mut broken_words = core::break_words(split_words, subsequent_width); + if !options.initial_indent.is_empty() { + // Without this, the first word will always go into + // the first line. However, since we break words based + // on the _second_ line width, it can be wrong to + // unconditionally put the first word onto the first + // line. An empty zero-width word fixed this. + broken_words.insert(0, core::Word::from("")); + } + broken_words + } else { + split_words.collect::>() + }; + + let line_widths = [initial_width, subsequent_width]; + let wrapped_words = options.wrap_algorithm.wrap(&broken_words, &line_widths); + + let mut idx = 0; + for words in wrapped_words { + let last_word = match words.last() { + None => { + lines.push(Cow::from("")); + continue; + } + Some(word) => word, + }; + + // We assume here that all words are contiguous in `line`. + // That is, the sum of their lengths should add up to the + // length of `line`. + let len = words + .iter() + .map(|word| word.len() + word.whitespace.len()) + .sum::() + - last_word.whitespace.len(); + + // The result is owned if we have indentation, otherwise + // we can simply borrow an empty string. + let mut result = if lines.is_empty() && !options.initial_indent.is_empty() { + Cow::Owned(options.initial_indent.to_owned()) + } else if !lines.is_empty() && !options.subsequent_indent.is_empty() { + Cow::Owned(options.subsequent_indent.to_owned()) + } else { + // We can use an empty string here since string + // concatenation for `Cow` preserves a borrowed value + // when either side is empty. + Cow::from("") + }; + + result += &line[idx..idx + len]; + + if !last_word.penalty.is_empty() { + result.to_mut().push_str(&last_word.penalty); + } + + lines.push(result); + + // Advance by the length of `result`, plus the length of + // `last_word.whitespace` -- even if we had a penalty, we + // need to skip over the whitespace. + idx += len + last_word.whitespace.len(); + } + } + + lines } -/// Lazily wrap a line of text at `width` characters. Strings are -/// wrapped based on their displayed width, not their size in bytes. +/// Wrap text into columns with a given total width. /// -/// This function creates a Wrapper on the fly with default settings. -/// It then calls the [`into_wrap_iter`] method. Hence, the return -/// value is an [`IntoWrapIter`], not a [`WrapIter`] as the function -/// name would otherwise suggest. +/// The `left_gap`, `middle_gap` and `right_gap` arguments specify the +/// strings to insert before, between, and after the columns. The +/// total width of all columns and all gaps is specified using the +/// `total_width_or_options` argument. This argument can simply be an +/// integer if you want to use default settings when wrapping, or it +/// can be a [`Options`] value if you want to customize the wrapping. /// -/// If you need to set a language corpus for automatic hyphenation, or -/// need to wrap many strings, then it is suggested to create a Wrapper -/// and call its [`wrap_iter`] or [`into_wrap_iter`] methods. +/// If the columns are narrow, it is recommended to set +/// [`Options::break_words`] to `true` to prevent words from +/// protruding into the margins. +/// +/// The per-column width is computed like this: +/// +/// ``` +/// # let (left_gap, middle_gap, right_gap) = ("", "", ""); +/// # let columns = 2; +/// # let options = textwrap::Options::new(80); +/// let inner_width = options.width +/// - textwrap::core::display_width(left_gap) +/// - textwrap::core::display_width(right_gap) +/// - textwrap::core::display_width(middle_gap) * (columns - 1); +/// let column_width = inner_width / columns; +/// ``` +/// +/// The `text` is wrapped using [`wrap`] and the given `options` +/// argument, but the width is overwritten to the computed +/// `column_width`. +/// +/// # Panics +/// +/// Panics if `columns` is zero. /// /// # Examples /// /// ``` -/// use std::borrow::Cow; -/// use textwrap::wrap_iter; +/// use textwrap::wrap_columns; /// -/// let mut wrap20_iter = wrap_iter("Zero-cost abstractions.", 20); -/// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost"))); -/// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions."))); -/// assert_eq!(wrap20_iter.next(), None); +/// let text = "\ +/// This is an example text, which is wrapped into three columns. \ +/// Notice how the final column can be shorter than the others."; /// -/// let mut wrap25_iter = wrap_iter("Zero-cost abstractions.", 25); -/// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions."))); -/// assert_eq!(wrap25_iter.next(), None); +/// #[cfg(feature = "smawk")] +/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"), +/// vec!["| This is | into three | column can be |", +/// "| an example | columns. | shorter than |", +/// "| text, which | Notice how | the others. |", +/// "| is wrapped | the final | |"]); +/// +/// // Without the `smawk` feature, the middle column is a little more uneven: +/// #[cfg(not(feature = "smawk"))] +/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"), +/// vec!["| This is an | three | column can be |", +/// "| example text, | columns. | shorter than |", +/// "| which is | Notice how | the others. |", +/// "| wrapped into | the final | |"]); +pub fn wrap_columns<'a, WrapAlgo, WordSep, WordSplit, Opt>( + text: &str, + columns: usize, + total_width_or_options: Opt, + left_gap: &str, + middle_gap: &str, + right_gap: &str, +) -> Vec +where + WrapAlgo: wrap_algorithms::WrapAlgorithm, + WordSep: word_separators::WordSeparator, + WordSplit: word_splitters::WordSplitter, + Opt: Into>, +{ + assert!(columns > 0); + + let mut options = total_width_or_options.into(); + + let inner_width = options + .width + .saturating_sub(core::display_width(left_gap)) + .saturating_sub(core::display_width(right_gap)) + .saturating_sub(core::display_width(middle_gap) * (columns - 1)); + + let column_width = std::cmp::max(inner_width / columns, 1); + options.width = column_width; + let last_column_padding = " ".repeat(inner_width % column_width); + let wrapped_lines = wrap(text, options); + let lines_per_column = + wrapped_lines.len() / columns + usize::from(wrapped_lines.len() % columns > 0); + let mut lines = Vec::new(); + for line_no in 0..lines_per_column { + let mut line = String::from(left_gap); + for column_no in 0..columns { + match wrapped_lines.get(line_no + column_no * lines_per_column) { + Some(column_line) => { + line.push_str(&column_line); + line.push_str(&" ".repeat(column_width - core::display_width(&column_line))); + } + None => { + line.push_str(&" ".repeat(column_width)); + } + } + if column_no == columns - 1 { + line.push_str(&last_column_padding); + } else { + line.push_str(middle_gap); + } + } + line.push_str(right_gap); + lines.push(line); + } + + lines +} + +/// Fill `text` in-place without reallocating the input string. +/// +/// This function works by modifying the input string: some `' '` +/// characters will be replaced by `'\n'` characters. The rest of the +/// text remains untouched. +/// +/// Since we can only replace existing whitespace in the input with +/// `'\n'`, we cannot do hyphenation nor can we split words longer +/// than the line width. We also need to use `AsciiSpace` as the word +/// separator since we need `' '` characters between words in order to +/// replace some of them with a `'\n'`. Indentation is also ruled out. +/// In other words, `fill_inplace(width)` behaves as if you had called +/// [`fill`] with these options: +/// +/// ``` +/// # use textwrap::{core, Options}; +/// # use textwrap::{word_separators, word_splitters, wrap_algorithms}; +/// # let width = 80; +/// Options { +/// width: width, +/// initial_indent: "", +/// subsequent_indent: "", +/// break_words: false, +/// word_separator: word_separators::AsciiSpace, +/// wrap_algorithm: wrap_algorithms::FirstFit, +/// word_splitter: word_splitters::NoHyphenation, +/// }; /// ``` /// -/// [`wrap_iter`]: struct.Wrapper.html#method.wrap_iter -/// [`into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter -/// [`IntoWrapIter`]: struct.IntoWrapIter.html -/// [`WrapIter`]: struct.WrapIter.html -pub fn wrap_iter(s: &str, width: usize) -> IntoWrapIter { - Wrapper::new(width).into_wrap_iter(s) +/// The wrap algorithm is [`wrap_algorithms::FirstFit`] since this +/// is the fastest algorithm — and the main reason to use +/// `fill_inplace` is to get the string broken into newlines as fast +/// as possible. +/// +/// A last difference is that (unlike [`fill`]) `fill_inplace` can +/// leave trailing whitespace on lines. This is because we wrap by +/// inserting a `'\n'` at the final whitespace in the input string: +/// +/// ``` +/// let mut text = String::from("Hello World!"); +/// textwrap::fill_inplace(&mut text, 10); +/// assert_eq!(text, "Hello \nWorld!"); +/// ``` +/// +/// If we didn't do this, the word `World!` would end up being +/// indented. You can avoid this if you make sure that your input text +/// has no double spaces. +/// +/// # Performance +/// +/// In benchmarks, `fill_inplace` is about twice as fast as [`fill`]. +/// Please see the [`linear` +/// benchmark](https://github.com/mgeisler/textwrap/blob/master/benches/linear.rs) +/// for details. +pub fn fill_inplace(text: &mut String, width: usize) { + use word_separators::WordSeparator; + let mut indices = Vec::new(); + + let mut offset = 0; + for line in text.split('\n') { + let words = word_separators::AsciiSpace + .find_words(line) + .collect::>(); + let wrapped_words = wrap_algorithms::wrap_first_fit(&words, &[width]); + + let mut line_offset = offset; + for words in &wrapped_words[..wrapped_words.len() - 1] { + let line_len = words + .iter() + .map(|word| word.len() + word.whitespace.len()) + .sum::(); + + line_offset += line_len; + // We've advanced past all ' ' characters -- want to move + // one ' ' backwards and insert our '\n' there. + indices.push(line_offset - 1); + } + + // Advance past entire line, plus the '\n' which was removed + // by the split call above. + offset += line.len() + 1; + } + + let mut bytes = std::mem::take(text).into_bytes(); + for idx in indices { + bytes[idx] = b'\n'; + } + *text = String::from_utf8(bytes).unwrap(); } #[cfg(test)] mod tests { - #[cfg(feature = "hyphenation")] - extern crate hyphenation; - use super::*; + use crate::word_splitters::WordSplitter; + use crate::{word_splitters, wrap_algorithms}; + #[cfg(feature = "hyphenation")] use hyphenation::{Language, Load, Standard}; + #[test] + fn options_agree_with_usize() { + let opt_usize = Options::from(42_usize); + let opt_options = Options::new(42); + + assert_eq!(opt_usize.width, opt_options.width); + assert_eq!(opt_usize.initial_indent, opt_options.initial_indent); + assert_eq!(opt_usize.subsequent_indent, opt_options.subsequent_indent); + assert_eq!(opt_usize.break_words, opt_options.break_words); + assert_eq!( + opt_usize.word_splitter.split_points("hello-world"), + opt_options.word_splitter.split_points("hello-world") + ); + } + #[test] fn no_wrap() { assert_eq!(wrap("foo", 10), vec!["foo"]); } #[test] - fn simple() { + fn wrap_simple() { assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]); } #[test] - fn multi_word_on_line() { + fn to_be_or_not() { + assert_eq!( + wrap( + "To be, or not to be, that is the question.", + Options::new(10).wrap_algorithm(wrap_algorithms::FirstFit) + ), + vec!["To be, or", "not to be,", "that is", "the", "question."] + ); + } + + #[test] + fn multiple_words_on_first_line() { assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]); } @@ -743,23 +1443,21 @@ mod tests { assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]); } + #[test] + fn leading_whitespace_empty_first_line() { + // If there is no space for the first word, the first line + // will be empty. This is because the string is split into + // words like [" ", "foobar ", "baz"], which puts "foobar " on + // the second line. We never output trailing whitespace + assert_eq!(wrap(" foobar baz", 6), vec!["", "foobar", "baz"]); + } + #[test] fn trailing_whitespace() { - assert_eq!(wrap("foo bar ", 6), vec!["foo", "bar "]); - } - - #[test] - fn interior_whitespace() { - assert_eq!(wrap("foo: bar baz", 10), vec!["foo: bar", "baz"]); - } - - #[test] - fn extra_whitespace_start_of_line() { // Whitespace is only significant inside a line. After a line // gets too long and is broken, the first word starts in - // column zero and is not indented. The line before might end - // up with trailing whitespace. - assert_eq!(wrap("foo bar", 5), vec!["foo", "bar"]); + // column zero and is not indented. + assert_eq!(wrap("foo bar baz ", 5), vec!["foo", "bar", "baz"]); } #[test] @@ -776,40 +1474,83 @@ mod tests { fn issue_129() { // The dash is an em-dash which takes up four bytes. We used // to panic since we tried to index into the character. - assert_eq!(wrap("x – x", 1), vec!["x", "–", "x"]); + let options = Options::new(1).word_separator(word_separators::AsciiSpace); + assert_eq!(wrap("x – x", options), vec!["x", "–", "x"]); } #[test] + #[cfg(feature = "unicode-width")] fn wide_character_handling() { assert_eq!(wrap("Hello, World!", 15), vec!["Hello, World!"]); assert_eq!( - wrap("Hello, World!", 15), + wrap( + "Hello, World!", + Options::new(15).word_separator(word_separators::AsciiSpace) + ), vec!["Hello,", "World!"] ); + + // Wide characters are allowed to break if the + // unicode-linebreak feature is enabled. + #[cfg(feature = "unicode-linebreak")] + assert_eq!( + wrap( + "Hello, World!", + Options::new(15).word_separator(word_separators::UnicodeBreakProperties) + ), + vec!["Hello, W", "orld!"] + ); } #[test] - fn empty_input_not_indented() { - let wrapper = Wrapper::new(10).initial_indent("!!!"); - assert_eq!(wrapper.fill(""), ""); + fn empty_line_is_indented() { + // Previously, indentation was not applied to empty lines. + // However, this is somewhat inconsistent and undesirable if + // the indentation is something like a border ("| ") which you + // want to apply to all lines, empty or not. + let options = Options::new(10).initial_indent("!!!"); + assert_eq!(fill("", &options), "!!!"); } #[test] fn indent_single_line() { - let wrapper = Wrapper::new(10).initial_indent(">>>"); // No trailing space - assert_eq!(wrapper.fill("foo"), ">>>foo"); + let options = Options::new(10).initial_indent(">>>"); // No trailing space + assert_eq!(fill("foo", &options), ">>>foo"); + } + + #[test] + #[cfg(feature = "unicode-width")] + fn indent_first_emoji() { + let options = Options::new(10).initial_indent("👉👉"); + assert_eq!( + wrap("x x x x x x x x x x x x x", &options), + vec!["👉👉x x x", "x x x x x", "x x x x x"] + ); } #[test] fn indent_multiple_lines() { - let wrapper = Wrapper::new(6).initial_indent("* ").subsequent_indent(" "); - assert_eq!(wrapper.wrap("foo bar baz"), vec!["* foo", " bar", " baz"]); + let options = Options::new(6).initial_indent("* ").subsequent_indent(" "); + assert_eq!( + wrap("foo bar baz", &options), + vec!["* foo", " bar", " baz"] + ); } #[test] fn indent_break_words() { - let wrapper = Wrapper::new(5).initial_indent("* ").subsequent_indent(" "); - assert_eq!(wrapper.wrap("foobarbaz"), vec!["* foo", " bar", " baz"]); + let options = Options::new(5).initial_indent("* ").subsequent_indent(" "); + assert_eq!(wrap("foobarbaz", &options), vec!["* foo", " bar", " baz"]); + } + + #[test] + fn initial_indent_break_words() { + // This is a corner-case showing how the long word is broken + // according to the width of the subsequent lines. The first + // fragment of the word no longer fits on the first line, + // which ends up being pure indentation. + let options = Options::new(5).initial_indent("-->"); + assert_eq!(wrap("foobarbaz", &options), vec!["-->", "fooba", "rbaz"]); } #[test] @@ -819,8 +1560,8 @@ mod tests { #[test] fn trailing_hyphen() { - let wrapper = Wrapper::new(5).break_words(false); - assert_eq!(wrapper.wrap("foobar-"), vec!["foobar-"]); + let options = Options::new(5).break_words(false); + assert_eq!(wrap("foobar-", &options), vec!["foobar-"]); } #[test] @@ -830,17 +1571,17 @@ mod tests { #[test] fn hyphens_flag() { - let wrapper = Wrapper::new(5).break_words(false); + let options = Options::new(5).break_words(false); assert_eq!( - wrapper.wrap("The --foo-bar flag."), + wrap("The --foo-bar flag.", &options), vec!["The", "--foo-", "bar", "flag."] ); } #[test] fn repeated_hyphens() { - let wrapper = Wrapper::new(4).break_words(false); - assert_eq!(wrapper.wrap("foo--bar"), vec!["foo--bar"]); + let options = Options::new(4).break_words(false); + assert_eq!(wrap("foo--bar", &options), vec!["foo--bar"]); } #[test] @@ -850,8 +1591,8 @@ mod tests { #[test] fn hyphens_non_alphanumeric() { - let wrapper = Wrapper::new(5).break_words(false); - assert_eq!(wrapper.wrap("foo(-)bar"), vec!["foo(-)bar"]); + let options = Options::new(5).break_words(false); + assert_eq!(wrap("foo(-)bar", &options), vec!["foo(-)bar"]); } #[test] @@ -861,42 +1602,117 @@ mod tests { #[test] fn forced_split() { - let wrapper = Wrapper::new(5).break_words(false); - assert_eq!(wrapper.wrap("foobar-baz"), vec!["foobar-", "baz"]); + let options = Options::new(5).break_words(false); + assert_eq!(wrap("foobar-baz", &options), vec!["foobar-", "baz"]); } #[test] - fn no_hyphenation() { - let wrapper = Wrapper::with_splitter(8, NoHyphenation); - assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]); + fn multiple_unbroken_words_issue_193() { + let options = Options::new(3).break_words(false); + assert_eq!( + wrap("small large tiny", &options), + vec!["small", "large", "tiny"] + ); + assert_eq!( + wrap("small large tiny", &options), + vec!["small", "large", "tiny"] + ); + } + + #[test] + fn very_narrow_lines_issue_193() { + let options = Options::new(1).break_words(false); + assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]); + assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]); + } + + #[test] + fn simple_hyphens_static() { + let options = Options::new(8).word_splitter(word_splitters::HyphenSplitter); + assert_eq!(wrap("foo bar-baz", &options), vec!["foo bar-", "baz"]); + } + + #[test] + fn simple_hyphens_dynamic() { + let options: Options<_, _> = + Options::new(8).word_splitter(Box::new(word_splitters::HyphenSplitter)); + assert_eq!(wrap("foo bar-baz", &options), vec!["foo bar-", "baz"]); + } + + #[test] + fn no_hyphenation_static() { + let options = Options::new(8).word_splitter(word_splitters::NoHyphenation); + assert_eq!(wrap("foo bar-baz", &options), vec!["foo", "bar-baz"]); + } + + #[test] + fn no_hyphenation_dynamic() { + let options: Options<_, _> = + Options::new(8).word_splitter(Box::new(word_splitters::NoHyphenation)); + assert_eq!(wrap("foo bar-baz", &options), vec!["foo", "bar-baz"]); } #[test] #[cfg(feature = "hyphenation")] - fn auto_hyphenation() { + fn auto_hyphenation_double_hyphenation_static() { let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); - let wrapper = Wrapper::new(10); + let options = Options::new(10); assert_eq!( - wrapper.wrap("Internationalization"), + wrap("Internationalization", &options), vec!["Internatio", "nalization"] ); - let wrapper = Wrapper::with_splitter(10, dictionary); + let options = Options::new(10).word_splitter(dictionary); assert_eq!( - wrapper.wrap("Internationalization"), + wrap("Internationalization", &options), vec!["Interna-", "tionaliza-", "tion"] ); } + #[test] + #[cfg(feature = "hyphenation")] + fn auto_hyphenation_double_hyphenation_dynamic() { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let mut options: Options<_, _, Box> = + Options::new(10).word_splitter(Box::new(word_splitters::HyphenSplitter)); + assert_eq!( + wrap("Internationalization", &options), + vec!["Internatio", "nalization"] + ); + + options = Options::new(10).word_splitter(Box::new(dictionary)); + assert_eq!( + wrap("Internationalization", &options), + vec!["Interna-", "tionaliza-", "tion"] + ); + } + + #[test] + #[cfg(feature = "hyphenation")] + fn auto_hyphenation_issue_158() { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let options = Options::new(10); + assert_eq!( + wrap("participation is the key to success", &options), + vec!["participat", "ion is", "the key to", "success"] + ); + + let options = Options::new(10).word_splitter(dictionary); + assert_eq!( + wrap("participation is the key to success", &options), + vec!["partici-", "pation is", "the key to", "success"] + ); + } + #[test] #[cfg(feature = "hyphenation")] fn split_len_hyphenation() { // Test that hyphenation takes the width of the wihtespace // into account. let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); - let wrapper = Wrapper::with_splitter(15, dictionary); + let options = Options::new(15).word_splitter(dictionary); assert_eq!( - wrapper.wrap("garbage collection"), + wrap("garbage collection", &options), vec!["garbage col-", "lection"] ); } @@ -908,8 +1724,8 @@ mod tests { // line is borrowed. use std::borrow::Cow::{Borrowed, Owned}; let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); - let wrapper = Wrapper::with_splitter(10, dictionary); - let lines = wrapper.wrap("Internationalization"); + let options = Options::new(10).word_splitter(dictionary); + let lines = wrap("Internationalization", &options); if let Borrowed(s) = lines[0] { assert!(false, "should not have been borrowed: {:?}", s); } @@ -925,12 +1741,15 @@ mod tests { #[cfg(feature = "hyphenation")] fn auto_hyphenation_with_hyphen() { let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); - let wrapper = Wrapper::new(8).break_words(false); - assert_eq!(wrapper.wrap("over-caffinated"), vec!["over-", "caffinated"]); - - let wrapper = Wrapper::with_splitter(8, dictionary).break_words(false); + let options = Options::new(8).break_words(false); assert_eq!( - wrapper.wrap("over-caffinated"), + wrap("over-caffinated", &options), + vec!["over-", "caffinated"] + ); + + let options = options.word_splitter(dictionary); + assert_eq!( + wrap("over-caffinated", &options), vec!["over-", "caffi-", "nated"] ); } @@ -942,7 +1761,10 @@ mod tests { #[test] fn break_words_wide_characters() { - assert_eq!(wrap("Hello", 5), vec!["He", "ll", "o"]); + // Even the poor man's version of `ch_width` counts these + // characters as wide. + let options = Options::new(5).word_separator(word_separators::AsciiSpace); + assert_eq!(wrap("Hello", options), vec!["He", "ll", "o"]); } #[test] @@ -950,6 +1772,11 @@ mod tests { assert_eq!(wrap("foobar", 0), vec!["f", "o", "o", "b", "a", "r"]); } + #[test] + fn break_long_first_word() { + assert_eq!(wrap("testx y", 4), vec!["test", "x y"]); + } + #[test] fn break_words_line_breaks() { assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl"); @@ -957,31 +1784,352 @@ mod tests { } #[test] - fn preserve_line_breaks() { - assert_eq!(fill("test\n", 11), "test\n"); - assert_eq!(fill("test\n\na\n\n", 11), "test\n\na\n\n"); - assert_eq!(fill("1 3 5 7\n1 3 5 7", 7), "1 3 5 7\n1 3 5 7"); + fn break_words_empty_lines() { + assert_eq!( + fill("foo\nbar", &Options::new(2).break_words(false)), + "foo\nbar" + ); } #[test] - fn wrap_preserve_line_breaks() { - assert_eq!(fill("1 3 5 7\n1 3 5 7", 5), "1 3 5\n7\n1 3 5\n7"); + fn preserve_line_breaks() { + assert_eq!(fill("", 80), ""); + assert_eq!(fill("\n", 80), "\n"); + assert_eq!(fill("\n\n\n", 80), "\n\n\n"); + assert_eq!(fill("test\n", 80), "test\n"); + assert_eq!(fill("test\n\na\n\n", 80), "test\n\na\n\n"); + assert_eq!( + fill( + "1 3 5 7\n1 3 5 7", + Options::new(7).wrap_algorithm(wrap_algorithms::FirstFit) + ), + "1 3 5 7\n1 3 5 7" + ); + assert_eq!( + fill( + "1 3 5 7\n1 3 5 7", + Options::new(5).wrap_algorithm(wrap_algorithms::FirstFit) + ), + "1 3 5\n7\n1 3 5\n7" + ); + } + + #[test] + fn preserve_line_breaks_with_whitespace() { + assert_eq!(fill(" ", 80), ""); + assert_eq!(fill(" \n ", 80), "\n"); + assert_eq!(fill(" \n \n \n ", 80), "\n\n\n"); } #[test] fn non_breaking_space() { - let wrapper = Wrapper::new(5).break_words(false); - assert_eq!(wrapper.fill("foo bar baz"), "foo bar baz"); + let options = Options::new(5).break_words(false); + assert_eq!(fill("foo bar baz", &options), "foo bar baz"); } #[test] fn non_breaking_hyphen() { - let wrapper = Wrapper::new(5).break_words(false); - assert_eq!(wrapper.fill("foo‑bar‑baz"), "foo‑bar‑baz"); + let options = Options::new(5).break_words(false); + assert_eq!(fill("foo‑bar‑baz", &options), "foo‑bar‑baz"); } #[test] fn fill_simple() { assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz"); } + + #[test] + fn fill_colored_text() { + // The words are much longer than 6 bytes, but they remain + // intact after filling the text. + let green_hello = "\u{1b}[0m\u{1b}[32mHello\u{1b}[0m"; + let blue_world = "\u{1b}[0m\u{1b}[34mWorld!\u{1b}[0m"; + assert_eq!( + fill(&(String::from(green_hello) + " " + &blue_world), 6), + String::from(green_hello) + "\n" + &blue_world + ); + } + + #[test] + fn fill_unicode_boundary() { + // https://github.com/mgeisler/textwrap/issues/390 + fill("\u{1b}!Ͽ", 10); + } + + #[test] + #[cfg(not(feature = "smawk"))] + #[cfg(not(feature = "unicode-linebreak"))] + fn cloning_works() { + static OPT: Options< + wrap_algorithms::FirstFit, + word_separators::AsciiSpace, + word_splitters::HyphenSplitter, + > = Options::with_word_splitter(80, word_splitters::HyphenSplitter); + #[allow(clippy::clone_on_copy)] + let opt = OPT.clone(); + assert_eq!(opt.width, 80); + } + + #[test] + fn fill_inplace_empty() { + let mut text = String::from(""); + fill_inplace(&mut text, 80); + assert_eq!(text, ""); + } + + #[test] + fn fill_inplace_simple() { + let mut text = String::from("foo bar baz"); + fill_inplace(&mut text, 10); + assert_eq!(text, "foo bar\nbaz"); + } + + #[test] + fn fill_inplace_multiple_lines() { + let mut text = String::from("Some text to wrap over multiple lines"); + fill_inplace(&mut text, 12); + assert_eq!(text, "Some text to\nwrap over\nmultiple\nlines"); + } + + #[test] + fn fill_inplace_long_word() { + let mut text = String::from("Internationalization is hard"); + fill_inplace(&mut text, 10); + assert_eq!(text, "Internationalization\nis hard"); + } + + #[test] + fn fill_inplace_no_hyphen_splitting() { + let mut text = String::from("A well-chosen example"); + fill_inplace(&mut text, 10); + assert_eq!(text, "A\nwell-chosen\nexample"); + } + + #[test] + fn fill_inplace_newlines() { + let mut text = String::from("foo bar\n\nbaz\n\n\n"); + fill_inplace(&mut text, 10); + assert_eq!(text, "foo bar\n\nbaz\n\n\n"); + } + + #[test] + fn fill_inplace_newlines_reset_line_width() { + let mut text = String::from("1 3 5\n1 3 5 7 9\n1 3 5 7 9 1 3"); + fill_inplace(&mut text, 10); + assert_eq!(text, "1 3 5\n1 3 5 7 9\n1 3 5 7 9\n1 3"); + } + + #[test] + fn fill_inplace_leading_whitespace() { + let mut text = String::from(" foo bar baz"); + fill_inplace(&mut text, 10); + assert_eq!(text, " foo bar\nbaz"); + } + + #[test] + fn fill_inplace_trailing_whitespace() { + let mut text = String::from("foo bar baz "); + fill_inplace(&mut text, 10); + assert_eq!(text, "foo bar\nbaz "); + } + + #[test] + fn fill_inplace_interior_whitespace() { + // To avoid an unwanted indentation of "baz", it is important + // to replace the final ' ' with '\n'. + let mut text = String::from("foo bar baz"); + fill_inplace(&mut text, 10); + assert_eq!(text, "foo bar \nbaz"); + } + + #[test] + fn unfill_simple() { + let (text, options) = unfill("foo\nbar"); + assert_eq!(text, "foo bar"); + assert_eq!(options.width, 3); + } + + #[test] + fn unfill_trailing_newlines() { + let (text, options) = unfill("foo\nbar\n\n\n"); + assert_eq!(text, "foo bar\n\n\n"); + assert_eq!(options.width, 3); + } + + #[test] + fn unfill_initial_indent() { + let (text, options) = unfill(" foo\nbar\nbaz"); + assert_eq!(text, "foo bar baz"); + assert_eq!(options.width, 5); + assert_eq!(options.initial_indent, " "); + } + + #[test] + fn unfill_differing_indents() { + let (text, options) = unfill(" foo\n bar\n baz"); + assert_eq!(text, "foo bar baz"); + assert_eq!(options.width, 7); + assert_eq!(options.initial_indent, " "); + assert_eq!(options.subsequent_indent, " "); + } + + #[test] + fn unfill_list_item() { + let (text, options) = unfill("* foo\n bar\n baz"); + assert_eq!(text, "foo bar baz"); + assert_eq!(options.width, 5); + assert_eq!(options.initial_indent, "* "); + assert_eq!(options.subsequent_indent, " "); + } + + #[test] + fn unfill_multiple_char_prefix() { + let (text, options) = unfill(" // foo bar\n // baz\n // quux"); + assert_eq!(text, "foo bar baz quux"); + assert_eq!(options.width, 14); + assert_eq!(options.initial_indent, " // "); + assert_eq!(options.subsequent_indent, " // "); + } + + #[test] + fn unfill_block_quote() { + let (text, options) = unfill("> foo\n> bar\n> baz"); + assert_eq!(text, "foo bar baz"); + assert_eq!(options.width, 5); + assert_eq!(options.initial_indent, "> "); + assert_eq!(options.subsequent_indent, "> "); + } + + #[test] + fn unfill_whitespace() { + assert_eq!(unfill("foo bar").0, "foo bar"); + } + + #[test] + fn trait_object_vec() { + // Create a vector of Options containing trait-objects. + let mut vector: Vec< + Options< + _, + Box, + Box, + >, + > = Vec::new(); + // Expected result from each options + let mut results = Vec::new(); + + let opt_full_type: Options< + _, + Box, + Box, + > = + Options::new(10) + .word_splitter(Box::new(word_splitters::HyphenSplitter) + as Box) + .word_separator(Box::new(word_separators::AsciiSpace) + as Box); + vector.push(opt_full_type); + results.push(vec!["over-", "caffinated"]); + + // Actually: Options, Box> + let opt_abbreviated_type = + Options::new(10) + .break_words(false) + .word_splitter(Box::new(word_splitters::NoHyphenation) + as Box) + .word_separator(Box::new(word_separators::AsciiSpace) + as Box); + vector.push(opt_abbreviated_type); + results.push(vec!["over-caffinated"]); + + #[cfg(feature = "hyphenation")] + { + let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); + let opt_hyp = Options::new(8) + .word_splitter(Box::new(dictionary) as Box) + .word_separator(Box::new(word_separators::AsciiSpace) + as Box); + vector.push(opt_hyp); + results.push(vec!["over-", "caffi-", "nated"]); + } + + // Test each entry + for (opt, expected) in vector.into_iter().zip(results) { + assert_eq!(wrap("over-caffinated", opt), expected); + } + } + + #[test] + fn wrap_columns_empty_text() { + assert_eq!(wrap_columns("", 1, 10, "| ", "", " |"), vec!["| |"]); + } + + #[test] + fn wrap_columns_single_column() { + assert_eq!( + wrap_columns("Foo", 3, 30, "| ", " | ", " |"), + vec!["| Foo | | |"] + ); + } + + #[test] + fn wrap_columns_uneven_columns() { + // The gaps take up a total of 5 columns, so the columns are + // (21 - 5)/4 = 4 columns wide: + assert_eq!( + wrap_columns("Foo Bar Baz Quux", 4, 21, "|", "|", "|"), + vec!["|Foo |Bar |Baz |Quux|"] + ); + // As the total width increases, the last column absorbs the + // excess width: + assert_eq!( + wrap_columns("Foo Bar Baz Quux", 4, 24, "|", "|", "|"), + vec!["|Foo |Bar |Baz |Quux |"] + ); + // Finally, when the width is 25, the columns can be resized + // to a width of (25 - 5)/4 = 5 columns: + assert_eq!( + wrap_columns("Foo Bar Baz Quux", 4, 25, "|", "|", "|"), + vec!["|Foo |Bar |Baz |Quux |"] + ); + } + + #[test] + #[cfg(feature = "unicode-width")] + fn wrap_columns_with_emojis() { + assert_eq!( + wrap_columns( + "Words and a few emojis 😍 wrapped in ⓶ columns", + 2, + 30, + "✨ ", + " ⚽ ", + " 👀" + ), + vec![ + "✨ Words ⚽ wrapped in 👀", + "✨ and a few ⚽ ⓶ columns 👀", + "✨ emojis 😍 ⚽ 👀" + ] + ); + } + + #[test] + fn wrap_columns_big_gaps() { + // The column width shrinks to 1 because the gaps take up all + // the space. + assert_eq!( + wrap_columns("xyz", 2, 10, "----> ", " !!! ", " <----"), + vec![ + "----> x !!! z <----", // + "----> y !!! <----" + ] + ); + } + + #[test] + #[should_panic] + fn wrap_columns_panic_with_zero_columns() { + wrap_columns("", 0, 10, "", "", ""); + } } diff --git a/third_party/rust/textwrap/src/splitting.rs b/third_party/rust/textwrap/src/splitting.rs deleted file mode 100644 index f6b65afda1e1..000000000000 --- a/third_party/rust/textwrap/src/splitting.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Word splitting functionality. -//! -//! To wrap text into lines, long words sometimes need to be split -//! across lines. The [`WordSplitter`] trait defines this -//! functionality. [`HyphenSplitter`] is the default implementation of -//! this treat: it will simply split words on existing hyphens. - -#[cfg(feature = "hyphenation")] -use hyphenation::{Hyphenator, Standard}; - -/// An interface for splitting words. -/// -/// When the [`wrap_iter`] method will try to fit text into a line, it -/// will eventually find a word that it too large the current text -/// width. It will then call the currently configured `WordSplitter` to -/// have it attempt to split the word into smaller parts. This trait -/// describes that functionality via the [`split`] method. -/// -/// If the `textwrap` crate has been compiled with the `hyphenation` -/// feature enabled, you will find an implementation of `WordSplitter` -/// by the `hyphenation::language::Corpus` struct. Use this struct for -/// language-aware hyphenation. See the [`hyphenation` documentation] -/// for details. -/// -/// [`wrap_iter`]: ../struct.Wrapper.html#method.wrap_iter -/// [`split`]: #tymethod.split -/// [`hyphenation` documentation]: https://docs.rs/hyphenation/ -pub trait WordSplitter { - /// Return all possible splits of word. Each split is a triple - /// with a head, a hyphen, and a tail where `head + &hyphen + - /// &tail == word`. The hyphen can be empty if there is already a - /// hyphen in the head. - /// - /// The splits should go from smallest to longest and should - /// include no split at all. So the word "technology" could be - /// split into - /// - /// ```no_run - /// vec![("tech", "-", "nology"), - /// ("technol", "-", "ogy"), - /// ("technolo", "-", "gy"), - /// ("technology", "", "")]; - /// ``` - fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)>; -} - -/// Use this as a [`Wrapper.splitter`] to avoid any kind of -/// hyphenation: -/// -/// ``` -/// use textwrap::{Wrapper, NoHyphenation}; -/// -/// let wrapper = Wrapper::with_splitter(8, NoHyphenation); -/// assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]); -/// ``` -/// -/// [`Wrapper.splitter`]: ../struct.Wrapper.html#structfield.splitter -#[derive(Clone, Debug)] -pub struct NoHyphenation; - -/// `NoHyphenation` implements `WordSplitter` by not splitting the -/// word at all. -impl WordSplitter for NoHyphenation { - fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { - vec![(word, "", "")] - } -} - -/// Simple and default way to split words: splitting on existing -/// hyphens only. -/// -/// You probably don't need to use this type since it's already used -/// by default by `Wrapper::new`. -#[derive(Clone, Debug)] -pub struct HyphenSplitter; - -/// `HyphenSplitter` is the default `WordSplitter` used by -/// `Wrapper::new`. It will split words on any existing hyphens in the -/// word. -/// -/// It will only use hyphens that are surrounded by alphanumeric -/// characters, which prevents a word like "--foo-bar" from being -/// split on the first or second hyphen. -impl WordSplitter for HyphenSplitter { - fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { - let mut triples = Vec::new(); - // Split on hyphens, smallest split first. We only use hyphens - // that are surrounded by alphanumeric characters. This is to - // avoid splitting on repeated hyphens, such as those found in - // --foo-bar. - let mut char_indices = word.char_indices(); - // Early return if the word is empty. - let mut prev = match char_indices.next() { - None => return vec![(word, "", "")], - Some((_, ch)) => ch, - }; - - // Find current word, or return early if the word only has a - // single character. - let (mut idx, mut cur) = match char_indices.next() { - None => return vec![(word, "", "")], - Some((idx, cur)) => (idx, cur), - }; - - for (i, next) in char_indices { - if prev.is_alphanumeric() && cur == '-' && next.is_alphanumeric() { - let (head, tail) = word.split_at(idx + 1); - triples.push((head, "", tail)); - } - prev = cur; - idx = i; - cur = next; - } - - // Finally option is no split at all. - triples.push((word, "", "")); - - triples - } -} - -/// A hyphenation dictionary can be used to do language-specific -/// hyphenation using patterns from the hyphenation crate. -#[cfg(feature = "hyphenation")] -impl WordSplitter for Standard { - fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> { - // Find splits based on language dictionary. - let mut triples = Vec::new(); - for n in self.hyphenate(word).breaks { - let (head, tail) = word.split_at(n); - let hyphen = if head.ends_with('-') { "" } else { "-" }; - triples.push((head, hyphen, tail)); - } - // Finally option is no split at all. - triples.push((word, "", "")); - - triples - } -} diff --git a/third_party/rust/textwrap/src/word_separators.rs b/third_party/rust/textwrap/src/word_separators.rs new file mode 100644 index 000000000000..db03a91f8542 --- /dev/null +++ b/third_party/rust/textwrap/src/word_separators.rs @@ -0,0 +1,406 @@ +//! Functionality for finding words. +//! +//! In order to wrap text, we need to know where the legal break +//! points are, i.e., where the words of the text are. This means that +//! we need to define what a "word" is. +//! +//! A simple approach is to simply split the text on whitespace, but +//! this does not work for East-Asian languages such as Chinese or +//! Japanese where there are no spaces between words. Breaking a long +//! sequence of emojis is another example where line breaks might be +//! wanted even if there are no whitespace to be found. +//! +//! The [`WordSeparator`] trait is responsible for determining where +//! there words are in a line of text. Please refer to the trait and +//! the structs which implement it for more information. + +#[cfg(feature = "unicode-linebreak")] +use crate::core::skip_ansi_escape_sequence; +use crate::core::Word; + +/// Describes where words occur in a line of text. +/// +/// The simplest approach is say that words are separated by one or +/// more ASCII spaces (`' '`). This works for Western languages +/// without emojis. A more complex approach is to use the Unicode line +/// breaking algorithm, which finds break points in non-ASCII text. +/// +/// The line breaks occur between words, please see the +/// [`WordSplitter`](crate::word_splitters::WordSplitter) trait for +/// options of how to handle hyphenation of individual words. +/// +/// # Examples +/// +/// ``` +/// use textwrap::core::Word; +/// use textwrap::word_separators::{WordSeparator, AsciiSpace}; +/// +/// let words = AsciiSpace.find_words("Hello World!").collect::>(); +/// assert_eq!(words, vec![Word::from("Hello "), Word::from("World!")]); +/// ``` +pub trait WordSeparator: WordSeparatorClone + std::fmt::Debug { + // This trait should really return impl Iterator, but + // this isn't possible until Rust supports higher-kinded types: + // https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md + /// Find all words in `line`. + fn find_words<'a>(&self, line: &'a str) -> Box> + 'a>; +} + +// The internal `WordSeparatorClone` trait is allows us to implement +// `Clone` for `Box`. This in used in the +// `From<&Options<'_, WrapAlgo, WordSep, WordSplit>> for Options<'a, +// WrapAlgo, WordSep, WordSplit>` implementation. +#[doc(hidden)] +pub trait WordSeparatorClone { + fn clone_box(&self) -> Box; +} + +impl WordSeparatorClone for T { + fn clone_box(&self) -> Box { + Box::new(self.clone()) + } +} + +impl Clone for Box { + fn clone(&self) -> Box { + use std::ops::Deref; + self.deref().clone_box() + } +} + +impl WordSeparator for Box { + fn find_words<'a>(&self, line: &'a str) -> Box> + 'a> { + use std::ops::Deref; + self.deref().find_words(line) + } +} + +/// Find words by splitting on regions of `' '` characters. +#[derive(Clone, Copy, Debug, Default)] +pub struct AsciiSpace; + +/// Split `line` into words separated by regions of `' '` characters. +/// +/// # Examples +/// +/// ``` +/// use textwrap::core::Word; +/// use textwrap::word_separators::{AsciiSpace, WordSeparator}; +/// +/// let words = AsciiSpace.find_words("Hello World!").collect::>(); +/// assert_eq!(words, vec![Word::from("Hello "), +/// Word::from("World!")]); +/// ``` +impl WordSeparator for AsciiSpace { + fn find_words<'a>(&self, line: &'a str) -> Box> + 'a> { + let mut start = 0; + let mut in_whitespace = false; + let mut char_indices = line.char_indices(); + + Box::new(std::iter::from_fn(move || { + // for (idx, ch) in char_indices does not work, gives this + // error: + // + // > cannot move out of `char_indices`, a captured variable in + // > an `FnMut` closure + #[allow(clippy::while_let_on_iterator)] + while let Some((idx, ch)) = char_indices.next() { + if in_whitespace && ch != ' ' { + let word = Word::from(&line[start..idx]); + start = idx; + in_whitespace = ch == ' '; + return Some(word); + } + + in_whitespace = ch == ' '; + } + + if start < line.len() { + let word = Word::from(&line[start..]); + start = line.len(); + return Some(word); + } + + None + })) + } +} + +/// Find words using the Unicode line breaking algorithm. +#[cfg(feature = "unicode-linebreak")] +#[derive(Clone, Copy, Debug, Default)] +pub struct UnicodeBreakProperties; + +/// Split `line` into words using Unicode break properties. +/// +/// This word separator uses the Unicode line breaking algorithm +/// described in [Unicode Standard Annex +/// #14](https://www.unicode.org/reports/tr14/) to find legal places +/// to break lines. There is a small difference in that the U+002D +/// (Hyphen-Minus) and U+00AD (Soft Hyphen) don’t create a line break: +/// to allow a line break at a hyphen, use the +/// [`HyphenSplitter`](crate::word_splitters::HyphenSplitter). Soft +/// hyphens are not currently supported. +/// +/// # Examples +/// +/// Unlike [`AsciiSpace`], the Unicode line breaking algorithm will +/// find line break opportunities between some characters with no +/// intervening whitespace: +/// +/// ``` +/// #[cfg(feature = "unicode-linebreak")] { +/// use textwrap::word_separators::{WordSeparator, UnicodeBreakProperties}; +/// use textwrap::core::Word; +/// +/// assert_eq!(UnicodeBreakProperties.find_words("Emojis: 😂😍").collect::>(), +/// vec![Word::from("Emojis: "), +/// Word::from("😂"), +/// Word::from("😍")]); +/// +/// assert_eq!(UnicodeBreakProperties.find_words("CJK: 你好").collect::>(), +/// vec![Word::from("CJK: "), +/// Word::from("你"), +/// Word::from("好")]); +/// } +/// ``` +/// +/// A U+2060 (Word Joiner) character can be inserted if you want to +/// manually override the defaults and keep the characters together: +/// +/// ``` +/// #[cfg(feature = "unicode-linebreak")] { +/// use textwrap::word_separators::{UnicodeBreakProperties, WordSeparator}; +/// use textwrap::core::Word; +/// +/// assert_eq!(UnicodeBreakProperties.find_words("Emojis: 😂\u{2060}😍").collect::>(), +/// vec![Word::from("Emojis: "), +/// Word::from("😂\u{2060}😍")]); +/// } +/// ``` +/// +/// The Unicode line breaking algorithm will also automatically +/// suppress break breaks around certain punctuation characters:: +/// +/// ``` +/// #[cfg(feature = "unicode-linebreak")] { +/// use textwrap::word_separators::{UnicodeBreakProperties, WordSeparator}; +/// use textwrap::core::Word; +/// +/// assert_eq!(UnicodeBreakProperties.find_words("[ foo ] bar !").collect::>(), +/// vec![Word::from("[ foo ] "), +/// Word::from("bar !")]); +/// } +/// ``` +#[cfg(feature = "unicode-linebreak")] +impl WordSeparator for UnicodeBreakProperties { + fn find_words<'a>(&self, line: &'a str) -> Box> + 'a> { + // Construct an iterator over (original index, stripped index) + // tuples. We find the Unicode linebreaks on a stripped string, + // but we need the original indices so we can form words based on + // the original string. + let mut last_stripped_idx = 0; + let mut char_indices = line.char_indices(); + let mut idx_map = std::iter::from_fn(move || match char_indices.next() { + Some((orig_idx, ch)) => { + let stripped_idx = last_stripped_idx; + if !skip_ansi_escape_sequence(ch, &mut char_indices.by_ref().map(|(_, ch)| ch)) { + last_stripped_idx += ch.len_utf8(); + } + Some((orig_idx, stripped_idx)) + } + None => None, + }); + + let stripped = strip_ansi_escape_sequences(&line); + let mut opportunities = unicode_linebreak::linebreaks(&stripped) + .filter(|(idx, _)| { + #[allow(clippy::match_like_matches_macro)] + match &stripped[..*idx].chars().next_back() { + // We suppress breaks at ‘-’ since we want to control + // this via the WordSplitter. + Some('-') => false, + // Soft hyphens are currently not supported since we + // require all `Word` fragments to be continuous in + // the input string. + Some(SHY) => false, + // Other breaks should be fine! + _ => true, + } + }) + .collect::>() + .into_iter(); + + // Remove final break opportunity, we will add it below using + // &line[start..]; This ensures that we correctly include a + // trailing ANSI escape sequence. + opportunities.next_back(); + + let mut start = 0; + Box::new(std::iter::from_fn(move || { + #[allow(clippy::while_let_on_iterator)] + while let Some((idx, _)) = opportunities.next() { + if let Some((orig_idx, _)) = idx_map.find(|&(_, stripped_idx)| stripped_idx == idx) + { + let word = Word::from(&line[start..orig_idx]); + start = orig_idx; + return Some(word); + } + } + + if start < line.len() { + let word = Word::from(&line[start..]); + start = line.len(); + return Some(word); + } + + None + })) + } +} + +/// Soft hyphen, also knows as a “shy hyphen”. Should show up as ‘-’ +/// if a line is broken at this point, and otherwise be invisible. +/// Textwrap does not currently support breaking words at soft +/// hyphens. +#[cfg(feature = "unicode-linebreak")] +const SHY: char = '\u{00ad}'; + +// Strip all ANSI escape sequences from `text`. +#[cfg(feature = "unicode-linebreak")] +fn strip_ansi_escape_sequences(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + + let mut chars = text.chars(); + while let Some(ch) = chars.next() { + if skip_ansi_escape_sequence(ch, &mut chars) { + continue; + } + result.push(ch); + } + + result +} + +#[cfg(test)] +mod tests { + use super::*; + + // Like assert_eq!, but the left expression is an iterator. + macro_rules! assert_iter_eq { + ($left:expr, $right:expr) => { + assert_eq!($left.collect::>(), $right); + }; + } + + #[test] + fn ascii_space_empty() { + assert_iter_eq!(AsciiSpace.find_words(""), vec![]); + } + + #[test] + fn ascii_space_single_word() { + assert_iter_eq!(AsciiSpace.find_words("foo"), vec![Word::from("foo")]); + } + + #[test] + fn ascii_space_two_words() { + assert_iter_eq!( + AsciiSpace.find_words("foo bar"), + vec![Word::from("foo "), Word::from("bar")] + ); + } + + #[test] + fn ascii_space_multiple_words() { + assert_iter_eq!( + AsciiSpace.find_words("foo bar baz"), + vec![Word::from("foo "), Word::from("bar "), Word::from("baz")] + ); + } + + #[test] + fn ascii_space_only_whitespace() { + assert_iter_eq!(AsciiSpace.find_words(" "), vec![Word::from(" ")]); + } + + #[test] + fn ascii_space_inter_word_whitespace() { + assert_iter_eq!( + AsciiSpace.find_words("foo bar"), + vec![Word::from("foo "), Word::from("bar")] + ) + } + + #[test] + fn ascii_space_trailing_whitespace() { + assert_iter_eq!(AsciiSpace.find_words("foo "), vec![Word::from("foo ")]); + } + + #[test] + fn ascii_space_leading_whitespace() { + assert_iter_eq!( + AsciiSpace.find_words(" foo"), + vec![Word::from(" "), Word::from("foo")] + ); + } + + #[test] + fn ascii_space_multi_column_char() { + assert_iter_eq!( + AsciiSpace.find_words("\u{1f920}"), // cowboy emoji 🤠 + vec![Word::from("\u{1f920}")] + ); + } + + #[test] + fn ascii_space_hyphens() { + assert_iter_eq!( + AsciiSpace.find_words("foo-bar"), + vec![Word::from("foo-bar")] + ); + assert_iter_eq!( + AsciiSpace.find_words("foo- bar"), + vec![Word::from("foo- "), Word::from("bar")] + ); + assert_iter_eq!( + AsciiSpace.find_words("foo - bar"), + vec![Word::from("foo "), Word::from("- "), Word::from("bar")] + ); + assert_iter_eq!( + AsciiSpace.find_words("foo -bar"), + vec![Word::from("foo "), Word::from("-bar")] + ); + } + + #[test] + #[cfg(unix)] + fn ascii_space_colored_text() { + use termion::color::{Blue, Fg, Green, Reset}; + + let green_hello = format!("{}Hello{} ", Fg(Green), Fg(Reset)); + let blue_world = format!("{}World!{}", Fg(Blue), Fg(Reset)); + assert_iter_eq!( + AsciiSpace.find_words(&format!("{}{}", green_hello, blue_world)), + vec![Word::from(&green_hello), Word::from(&blue_world)] + ); + + #[cfg(feature = "unicode-linebreak")] + assert_iter_eq!( + UnicodeBreakProperties.find_words(&format!("{}{}", green_hello, blue_world)), + vec![Word::from(&green_hello), Word::from(&blue_world)] + ); + } + + #[test] + fn ascii_space_color_inside_word() { + let text = "foo\u{1b}[0m\u{1b}[32mbar\u{1b}[0mbaz"; + assert_iter_eq!(AsciiSpace.find_words(&text), vec![Word::from(text)]); + + #[cfg(feature = "unicode-linebreak")] + assert_iter_eq!( + UnicodeBreakProperties.find_words(&text), + vec![Word::from(text)] + ); + } +} diff --git a/third_party/rust/textwrap/src/word_splitters.rs b/third_party/rust/textwrap/src/word_splitters.rs new file mode 100644 index 000000000000..f4d94c7021b1 --- /dev/null +++ b/third_party/rust/textwrap/src/word_splitters.rs @@ -0,0 +1,311 @@ +//! Word splitting functionality. +//! +//! To wrap text into lines, long words sometimes need to be split +//! across lines. The [`WordSplitter`] trait defines this +//! functionality. [`HyphenSplitter`] is the default implementation of +//! this treat: it will simply split words on existing hyphens. + +use std::ops::Deref; + +use crate::core::{display_width, Word}; + +/// The `WordSplitter` trait describes where words can be split. +/// +/// If the textwrap crate has been compiled with the `hyphenation` +/// Cargo feature enabled, you will find an implementation of +/// `WordSplitter` by the `hyphenation::Standard` struct. Use this +/// struct for language-aware hyphenation: +/// +/// ``` +/// #[cfg(feature = "hyphenation")] +/// { +/// use hyphenation::{Language, Load, Standard}; +/// use textwrap::{wrap, Options}; +/// +/// let text = "Oxidation is the loss of electrons."; +/// let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); +/// let options = Options::new(8).word_splitter(dictionary); +/// assert_eq!(wrap(text, &options), vec!["Oxida-", +/// "tion is", +/// "the loss", +/// "of elec-", +/// "trons."]); +/// } +/// ``` +/// +/// Please see the documentation for the [hyphenation] crate for more +/// details. +/// +/// [hyphenation]: https://docs.rs/hyphenation/ +pub trait WordSplitter: WordSplitterClone + std::fmt::Debug { + /// Return all possible indices where `word` can be split. + /// + /// The indices returned must be in range `0..word.len()`. They + /// should point to the index _after_ the split point, i.e., after + /// `-` if splitting on hyphens. This way, `word.split_at(idx)` + /// will break the word into two well-formed pieces. + /// + /// # Examples + /// + /// ``` + /// use textwrap::word_splitters::{HyphenSplitter, NoHyphenation, WordSplitter}; + /// assert_eq!(NoHyphenation.split_points("cannot-be-split"), vec![]); + /// assert_eq!(HyphenSplitter.split_points("can-be-split"), vec![4, 7]); + /// ``` + fn split_points(&self, word: &str) -> Vec; +} + +// The internal `WordSplitterClone` trait is allows us to implement +// `Clone` for `Box`. This in used in the +// `From<&Options<'_, WrapAlgo, WordSep, WordSplit>> for Options<'a, +// WrapAlgo, WordSep, WordSplit>` implementation. +#[doc(hidden)] +pub trait WordSplitterClone { + fn clone_box(&self) -> Box; +} + +impl WordSplitterClone for T { + fn clone_box(&self) -> Box { + Box::new(self.clone()) + } +} + +impl Clone for Box { + fn clone(&self) -> Box { + self.deref().clone_box() + } +} + +impl WordSplitter for Box { + fn split_points(&self, word: &str) -> Vec { + self.deref().split_points(word) + } +} + +/// Use this as a [`Options.word_splitter`] to avoid any kind of +/// hyphenation: +/// +/// ``` +/// use textwrap::{wrap, Options}; +/// use textwrap::word_splitters::NoHyphenation; +/// +/// let options = Options::new(8).word_splitter(NoHyphenation); +/// assert_eq!(wrap("foo bar-baz", &options), +/// vec!["foo", "bar-baz"]); +/// ``` +/// +/// [`Options.word_splitter`]: super::Options::word_splitter +#[derive(Clone, Copy, Debug)] +pub struct NoHyphenation; + +/// `NoHyphenation` implements `WordSplitter` by not splitting the +/// word at all. +impl WordSplitter for NoHyphenation { + fn split_points(&self, _: &str) -> Vec { + Vec::new() + } +} + +/// Simple and default way to split words: splitting on existing +/// hyphens only. +/// +/// You probably don't need to use this type since it's already used +/// by default by [`Options::new`](super::Options::new). +#[derive(Clone, Copy, Debug)] +pub struct HyphenSplitter; + +/// `HyphenSplitter` is the default `WordSplitter` used by +/// [`Options::new`](super::Options::new). It will split words on any +/// existing hyphens in the word. +/// +/// It will only use hyphens that are surrounded by alphanumeric +/// characters, which prevents a word like `"--foo-bar"` from being +/// split into `"--"` and `"foo-bar"`. +impl WordSplitter for HyphenSplitter { + fn split_points(&self, word: &str) -> Vec { + let mut splits = Vec::new(); + + for (idx, _) in word.match_indices('-') { + // We only use hyphens that are surrounded by alphanumeric + // characters. This is to avoid splitting on repeated hyphens, + // such as those found in --foo-bar. + let prev = word[..idx].chars().next_back(); + let next = word[idx + 1..].chars().next(); + + if prev.filter(|ch| ch.is_alphanumeric()).is_some() + && next.filter(|ch| ch.is_alphanumeric()).is_some() + { + splits.push(idx + 1); // +1 due to width of '-'. + } + } + + splits + } +} + +/// A hyphenation dictionary can be used to do language-specific +/// hyphenation using patterns from the [hyphenation] crate. +/// +/// **Note:** Only available when the `hyphenation` Cargo feature is +/// enabled. +/// +/// [hyphenation]: https://docs.rs/hyphenation/ +#[cfg(feature = "hyphenation")] +impl WordSplitter for hyphenation::Standard { + fn split_points(&self, word: &str) -> Vec { + use hyphenation::Hyphenator; + self.hyphenate(word).breaks + } +} + +/// Split words into smaller words according to the split points given +/// by `word_splitter`. +/// +/// Note that we split all words, regardless of their length. This is +/// to more cleanly separate the business of splitting (including +/// automatic hyphenation) from the business of word wrapping. +/// +/// # Examples +/// +/// ``` +/// use textwrap::core::Word; +/// use textwrap::word_splitters::{split_words, NoHyphenation, HyphenSplitter}; +/// +/// assert_eq!( +/// split_words(vec![Word::from("foo-bar")], &HyphenSplitter).collect::>(), +/// vec![Word::from("foo-"), Word::from("bar")] +/// ); +/// +/// // The NoHyphenation splitter ignores the '-': +/// assert_eq!( +/// split_words(vec![Word::from("foo-bar")], &NoHyphenation).collect::>(), +/// vec![Word::from("foo-bar")] +/// ); +/// ``` +pub fn split_words<'a, I, WordSplit>( + words: I, + word_splitter: &'a WordSplit, +) -> impl Iterator> +where + I: IntoIterator>, + WordSplit: WordSplitter, +{ + words.into_iter().flat_map(move |word| { + let mut prev = 0; + let mut split_points = word_splitter.split_points(&word).into_iter(); + std::iter::from_fn(move || { + if let Some(idx) = split_points.next() { + let need_hyphen = !word[..idx].ends_with('-'); + let w = Word { + word: &word.word[prev..idx], + width: display_width(&word[prev..idx]), + whitespace: "", + penalty: if need_hyphen { "-" } else { "" }, + }; + prev = idx; + return Some(w); + } + + if prev < word.word.len() || prev == 0 { + let w = Word { + word: &word.word[prev..], + width: display_width(&word[prev..]), + whitespace: word.whitespace, + penalty: word.penalty, + }; + prev = word.word.len() + 1; + return Some(w); + } + + None + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Like assert_eq!, but the left expression is an iterator. + macro_rules! assert_iter_eq { + ($left:expr, $right:expr) => { + assert_eq!($left.collect::>(), $right); + }; + } + + #[test] + fn split_words_no_words() { + assert_iter_eq!(split_words(vec![], &HyphenSplitter), vec![]); + } + + #[test] + fn split_words_empty_word() { + assert_iter_eq!( + split_words(vec![Word::from(" ")], &HyphenSplitter), + vec![Word::from(" ")] + ); + } + + #[test] + fn split_words_single_word() { + assert_iter_eq!( + split_words(vec![Word::from("foobar")], &HyphenSplitter), + vec![Word::from("foobar")] + ); + } + + #[test] + fn split_words_hyphen_splitter() { + assert_iter_eq!( + split_words(vec![Word::from("foo-bar")], &HyphenSplitter), + vec![Word::from("foo-"), Word::from("bar")] + ); + } + + #[test] + fn split_words_adds_penalty() { + #[derive(Clone, Debug)] + struct FixedSplitPoint; + impl WordSplitter for FixedSplitPoint { + fn split_points(&self, _: &str) -> Vec { + vec![3] + } + } + + assert_iter_eq!( + split_words(vec![Word::from("foobar")].into_iter(), &FixedSplitPoint), + vec![ + Word { + word: "foo", + width: 3, + whitespace: "", + penalty: "-" + }, + Word { + word: "bar", + width: 3, + whitespace: "", + penalty: "" + } + ] + ); + + assert_iter_eq!( + split_words(vec![Word::from("fo-bar")].into_iter(), &FixedSplitPoint), + vec![ + Word { + word: "fo-", + width: 3, + whitespace: "", + penalty: "" + }, + Word { + word: "bar", + width: 3, + whitespace: "", + penalty: "" + } + ] + ); + } +} diff --git a/third_party/rust/textwrap/src/wrap_algorithms.rs b/third_party/rust/textwrap/src/wrap_algorithms.rs new file mode 100644 index 000000000000..368ef2a4fdff --- /dev/null +++ b/third_party/rust/textwrap/src/wrap_algorithms.rs @@ -0,0 +1,257 @@ +//! Word wrapping algorithms. +//! +//! After a text has been broken into words (or [`Fragment`]s), one +//! now has to decide how to break the fragments into lines. The +//! simplest algorithm for this is implemented by [`wrap_first_fit`]: +//! it uses no look-ahead and simply adds fragments to the line as +//! long as they fit. However, this can lead to poor line breaks if a +//! large fragment almost-but-not-quite fits on a line. When that +//! happens, the fragment is moved to the next line and it will leave +//! behind a large gap. A more advanced algorithm, implemented by +//! [`wrap_optimal_fit`], will take this into account. The optimal-fit +//! algorithm considers all possible line breaks and will attempt to +//! minimize the gaps left behind by overly short lines. +//! +//! While both algorithms run in linear time, the first-fit algorithm +//! is about 4 times faster than the optimal-fit algorithm. + +#[cfg(feature = "smawk")] +mod optimal_fit; +#[cfg(feature = "smawk")] +pub use optimal_fit::{wrap_optimal_fit, OptimalFit}; + +use crate::core::{Fragment, Word}; + +/// Describes how to wrap words into lines. +/// +/// The simplest approach is to wrap words one word at a time. This is +/// implemented by [`FirstFit`]. If the `smawk` Cargo feature is +/// enabled, a more complex algorithm is available, implemented by +/// [`OptimalFit`], which will look at an entire paragraph at a time +/// in order to find optimal line breaks. +pub trait WrapAlgorithm: WrapAlgorithmClone + std::fmt::Debug { + /// Wrap words according to line widths. + /// + /// The `line_widths` slice gives the target line width for each + /// line (the last slice element is repeated as necessary). This + /// can be used to implement hanging indentation. + /// + /// Please see the implementors of the trait for examples. + fn wrap<'a, 'b>(&self, words: &'b [Word<'a>], line_widths: &'b [usize]) -> Vec<&'b [Word<'a>]>; +} + +// The internal `WrapAlgorithmClone` trait is allows us to implement +// `Clone` for `Box`. This in used in the +// `From<&Options<'_, WrapAlgo, WordSep, WordSplit>> for Options<'a, +// WrapAlgo, WordSep, WordSplit>` implementation. +#[doc(hidden)] +pub trait WrapAlgorithmClone { + fn clone_box(&self) -> Box; +} + +impl WrapAlgorithmClone for T { + fn clone_box(&self) -> Box { + Box::new(self.clone()) + } +} + +impl Clone for Box { + fn clone(&self) -> Box { + use std::ops::Deref; + self.deref().clone_box() + } +} + +impl WrapAlgorithm for Box { + fn wrap<'a, 'b>(&self, words: &'b [Word<'a>], line_widths: &'b [usize]) -> Vec<&'b [Word<'a>]> { + use std::ops::Deref; + self.deref().wrap(words, line_widths) + } +} + +/// Wrap words using a fast and simple algorithm. +/// +/// This algorithm uses no look-ahead when finding line breaks. +/// Implemented by [`wrap_first_fit`], please see that function for +/// details and examples. +#[derive(Clone, Copy, Debug, Default)] +pub struct FirstFit; + +impl WrapAlgorithm for FirstFit { + #[inline] + fn wrap<'a, 'b>(&self, words: &'b [Word<'a>], line_widths: &'b [usize]) -> Vec<&'b [Word<'a>]> { + wrap_first_fit(words, line_widths) + } +} + +/// Wrap abstract fragments into lines with a first-fit algorithm. +/// +/// The `line_widths` slice gives the target line width for each line +/// (the last slice element is repeated as necessary). This can be +/// used to implement hanging indentation. +/// +/// The fragments must already have been split into the desired +/// widths, this function will not (and cannot) attempt to split them +/// further when arranging them into lines. +/// +/// # First-Fit Algorithm +/// +/// This implements a simple “greedy” algorithm: accumulate fragments +/// one by one and when a fragment no longer fits, start a new line. +/// There is no look-ahead, we simply take first fit of the fragments +/// we find. +/// +/// While fast and predictable, this algorithm can produce poor line +/// breaks when a long fragment is moved to a new line, leaving behind +/// a large gap: +/// +/// ``` +/// use textwrap::core::Word; +/// use textwrap::wrap_algorithms; +/// use textwrap::word_separators::{AsciiSpace, WordSeparator}; +/// +/// // Helper to convert wrapped lines to a Vec. +/// fn lines_to_strings(lines: Vec<&[Word<'_>]>) -> Vec { +/// lines.iter().map(|line| { +/// line.iter().map(|word| &**word).collect::>().join(" ") +/// }).collect::>() +/// } +/// +/// let text = "These few words will unfortunately not wrap nicely."; +/// let words = AsciiSpace.find_words(text).collect::>(); +/// assert_eq!(lines_to_strings(wrap_algorithms::wrap_first_fit(&words, &[15])), +/// vec!["These few words", +/// "will", // <-- short line +/// "unfortunately", +/// "not wrap", +/// "nicely."]); +/// +/// // We can avoid the short line if we look ahead: +/// #[cfg(feature = "smawk")] +/// assert_eq!(lines_to_strings(wrap_algorithms::wrap_optimal_fit(&words, &[15])), +/// vec!["These few", +/// "words will", +/// "unfortunately", +/// "not wrap", +/// "nicely."]); +/// ``` +/// +/// The [`wrap_optimal_fit`] function was used above to get better +/// line breaks. It uses an advanced algorithm which tries to avoid +/// short lines. This function is about 4 times faster than +/// [`wrap_optimal_fit`]. +/// +/// # Examples +/// +/// Imagine you're building a house site and you have a number of +/// tasks you need to execute. Things like pour foundation, complete +/// framing, install plumbing, electric cabling, install insulation. +/// +/// The construction workers can only work during daytime, so they +/// need to pack up everything at night. Because they need to secure +/// their tools and move machines back to the garage, this process +/// takes much more time than the time it would take them to simply +/// switch to another task. +/// +/// You would like to make a list of tasks to execute every day based +/// on your estimates. You can model this with a program like this: +/// +/// ``` +/// use textwrap::wrap_algorithms::wrap_first_fit; +/// use textwrap::core::{Fragment, Word}; +/// +/// #[derive(Debug)] +/// struct Task<'a> { +/// name: &'a str, +/// hours: usize, // Time needed to complete task. +/// sweep: usize, // Time needed for a quick sweep after task during the day. +/// cleanup: usize, // Time needed for full cleanup if day ends with this task. +/// } +/// +/// impl Fragment for Task<'_> { +/// fn width(&self) -> usize { self.hours } +/// fn whitespace_width(&self) -> usize { self.sweep } +/// fn penalty_width(&self) -> usize { self.cleanup } +/// } +/// +/// // The morning tasks +/// let tasks = vec![ +/// Task { name: "Foundation", hours: 4, sweep: 2, cleanup: 3 }, +/// Task { name: "Framing", hours: 3, sweep: 1, cleanup: 2 }, +/// Task { name: "Plumbing", hours: 2, sweep: 2, cleanup: 2 }, +/// Task { name: "Electrical", hours: 2, sweep: 1, cleanup: 2 }, +/// Task { name: "Insulation", hours: 2, sweep: 1, cleanup: 2 }, +/// Task { name: "Drywall", hours: 3, sweep: 1, cleanup: 2 }, +/// Task { name: "Floors", hours: 3, sweep: 1, cleanup: 2 }, +/// Task { name: "Countertops", hours: 1, sweep: 1, cleanup: 2 }, +/// Task { name: "Bathrooms", hours: 2, sweep: 1, cleanup: 2 }, +/// ]; +/// +/// // Fill tasks into days, taking `day_length` into account. The +/// // output shows the hours worked per day along with the names of +/// // the tasks for that day. +/// fn assign_days<'a>(tasks: &[Task<'a>], day_length: usize) -> Vec<(usize, Vec<&'a str>)> { +/// let mut days = Vec::new(); +/// // Assign tasks to days. The assignment is a vector of slices, +/// // with a slice per day. +/// let assigned_days: Vec<&[Task<'a>]> = wrap_first_fit(&tasks, &[day_length]); +/// for day in assigned_days.iter() { +/// let last = day.last().unwrap(); +/// let work_hours: usize = day.iter().map(|t| t.hours + t.sweep).sum(); +/// let names = day.iter().map(|t| t.name).collect::>(); +/// days.push((work_hours - last.sweep + last.cleanup, names)); +/// } +/// days +/// } +/// +/// // With a single crew working 8 hours a day: +/// assert_eq!( +/// assign_days(&tasks, 8), +/// [ +/// (7, vec!["Foundation"]), +/// (8, vec!["Framing", "Plumbing"]), +/// (7, vec!["Electrical", "Insulation"]), +/// (5, vec!["Drywall"]), +/// (7, vec!["Floors", "Countertops"]), +/// (4, vec!["Bathrooms"]), +/// ] +/// ); +/// +/// // With two crews working in shifts, 16 hours a day: +/// assert_eq!( +/// assign_days(&tasks, 16), +/// [ +/// (14, vec!["Foundation", "Framing", "Plumbing"]), +/// (15, vec!["Electrical", "Insulation", "Drywall", "Floors"]), +/// (6, vec!["Countertops", "Bathrooms"]), +/// ] +/// ); +/// ``` +/// +/// Apologies to anyone who actually knows how to build a house and +/// knows how long each step takes :-) +pub fn wrap_first_fit<'a, 'b, T: Fragment>( + fragments: &'a [T], + line_widths: &'b [usize], +) -> Vec<&'a [T]> { + // The final line width is used for all remaining lines. + let default_line_width = line_widths.last().copied().unwrap_or(0); + let mut lines = Vec::new(); + let mut start = 0; + let mut width = 0; + + for (idx, fragment) in fragments.iter().enumerate() { + let line_width = line_widths + .get(lines.len()) + .copied() + .unwrap_or(default_line_width); + if width + fragment.width() + fragment.penalty_width() > line_width && idx > start { + lines.push(&fragments[start..idx]); + start = idx; + width = 0; + } + width += fragment.width() + fragment.whitespace_width(); + } + lines.push(&fragments[start..]); + lines +} diff --git a/third_party/rust/textwrap/src/wrap_algorithms/optimal_fit.rs b/third_party/rust/textwrap/src/wrap_algorithms/optimal_fit.rs new file mode 100644 index 000000000000..95ecf1f7886d --- /dev/null +++ b/third_party/rust/textwrap/src/wrap_algorithms/optimal_fit.rs @@ -0,0 +1,256 @@ +use std::cell::RefCell; + +use crate::core::{Fragment, Word}; +use crate::wrap_algorithms::WrapAlgorithm; + +/// Wrap words using an advanced algorithm with look-ahead. +/// +/// This wrapping algorithm considers the entire paragraph to find +/// optimal line breaks. Implemented by [`wrap_optimal_fit`], please +/// see that function for details and examples. +/// +/// **Note:** Only available when the `smawk` Cargo feature is +/// enabled. +#[derive(Clone, Copy, Debug, Default)] +pub struct OptimalFit; + +impl WrapAlgorithm for OptimalFit { + #[inline] + fn wrap<'a, 'b>(&self, words: &'b [Word<'a>], line_widths: &'b [usize]) -> Vec<&'b [Word<'a>]> { + wrap_optimal_fit(words, line_widths) + } +} + +/// Cache for line numbers. This is necessary to avoid a O(n**2) +/// behavior when computing line numbers in [`wrap_optimal_fit`]. +struct LineNumbers { + line_numbers: RefCell>, +} + +impl LineNumbers { + fn new(size: usize) -> Self { + let mut line_numbers = Vec::with_capacity(size); + line_numbers.push(0); + LineNumbers { + line_numbers: RefCell::new(line_numbers), + } + } + + fn get(&self, i: usize, minima: &[(usize, T)]) -> usize { + while self.line_numbers.borrow_mut().len() < i + 1 { + let pos = self.line_numbers.borrow().len(); + let line_number = 1 + self.get(minima[pos].0, &minima); + self.line_numbers.borrow_mut().push(line_number); + } + + self.line_numbers.borrow()[i] + } +} + +/// Per-line penalty. This is added for every line, which makes it +/// expensive to output more lines than the minimum required. +const NLINE_PENALTY: i32 = 1000; + +/// Per-character cost for lines that overflow the target line width. +/// +/// With a value of 50², every single character costs as much as +/// leaving a gap of 50 characters behind. This is becuase we assign +/// as cost of `gap * gap` to a short line. This means that we can +/// overflow the line by 1 character in extreme cases: +/// +/// ``` +/// use textwrap::wrap_algorithms::wrap_optimal_fit; +/// use textwrap::core::Word; +/// +/// let short = "foo "; +/// let long = "x".repeat(50); +/// let fragments = vec![Word::from(short), Word::from(&long)]; +/// +/// // Perfect fit, both words are on a single line with no overflow. +/// let wrapped = wrap_optimal_fit(&fragments, &[short.len() + long.len()]); +/// assert_eq!(wrapped, vec![&[Word::from(short), Word::from(&long)]]); +/// +/// // The words no longer fit, yet we get a single line back. While +/// // the cost of overflow (`1 * 2500`) is the same as the cost of the +/// // gap (`50 * 50 = 2500`), the tie is broken by `NLINE_PENALTY` +/// // which makes it cheaper to overflow than to use two lines. +/// let wrapped = wrap_optimal_fit(&fragments, &[short.len() + long.len() - 1]); +/// assert_eq!(wrapped, vec![&[Word::from(short), Word::from(&long)]]); +/// +/// // The cost of overflow would be 2 * 2500, whereas the cost of the +/// // gap is only `49 * 49 + NLINE_PENALTY = 2401 + 1000 = 3401`. We +/// // therefore get two lines. +/// let wrapped = wrap_optimal_fit(&fragments, &[short.len() + long.len() - 2]); +/// assert_eq!(wrapped, vec![&[Word::from(short)], +/// &[Word::from(&long)]]); +/// ``` +/// +/// This only happens if the overflowing word is 50 characters long +/// _and_ if it happens to overflow the line by exactly one character. +/// If it overflows by more than one character, the overflow penalty +/// will quickly outgrow the cost of the gap, as seen above. +const OVERFLOW_PENALTY: i32 = 50 * 50; + +/// The last line is short if it is less than 1/4 of the target width. +const SHORT_LINE_FRACTION: usize = 4; + +/// Penalize a short last line. +const SHORT_LAST_LINE_PENALTY: i32 = 25; + +/// Penalty for lines ending with a hyphen. +const HYPHEN_PENALTY: i32 = 25; + +/// Wrap abstract fragments into lines with an optimal-fit algorithm. +/// +/// The `line_widths` slice gives the target line width for each line +/// (the last slice element is repeated as necessary). This can be +/// used to implement hanging indentation. +/// +/// The fragments must already have been split into the desired +/// widths, this function will not (and cannot) attempt to split them +/// further when arranging them into lines. +/// +/// # Optimal-Fit Algorithm +/// +/// The algorithm considers all possible break points and picks the +/// breaks which minimizes the gaps at the end of each line. More +/// precisely, the algorithm assigns a cost or penalty to each break +/// point, determined by `cost = gap * gap` where `gap = target_width - +/// line_width`. Shorter lines are thus penalized more heavily since +/// they leave behind a larger gap. +/// +/// We can illustrate this with the text “To be, or not to be: that is +/// the question”. We will be wrapping it in a narrow column with room +/// for only 10 characters. The [greedy +/// algorithm](super::wrap_first_fit) will produce these lines, each +/// annotated with the corresponding penalty: +/// +/// ```text +/// "To be, or" 1² = 1 +/// "not to be:" 0² = 0 +/// "that is" 3² = 9 +/// "the" 7² = 49 +/// "question" 2² = 4 +/// ``` +/// +/// We see that line four with “the” leaves a gap of 7 columns, which +/// gives it a penalty of 49. The sum of the penalties is 63. +/// +/// There are 10 words, which means that there are `2_u32.pow(9)` or +/// 512 different ways to typeset it. We can compute +/// the sum of the penalties for each possible line break and search +/// for the one with the lowest sum: +/// +/// ```text +/// "To be," 4² = 16 +/// "or not to" 1² = 1 +/// "be: that" 2² = 4 +/// "is the" 4² = 16 +/// "question" 2² = 4 +/// ``` +/// +/// The sum of the penalties is 41, which is better than what the +/// greedy algorithm produced. +/// +/// Searching through all possible combinations would normally be +/// prohibitively slow. However, it turns out that the problem can be +/// formulated as the task of finding column minima in a cost matrix. +/// This matrix has a special form (totally monotone) which lets us +/// use a [linear-time algorithm called +/// SMAWK](https://lib.rs/crates/smawk) to find the optimal break +/// points. +/// +/// This means that the time complexity remains O(_n_) where _n_ is +/// the number of words. Compared to +/// [`wrap_first_fit`](super::wrap_first_fit), this function is about +/// 4 times slower. +/// +/// The optimization of per-line costs over the entire paragraph is +/// inspired by the line breaking algorithm used in TeX, as described +/// in the 1981 article [_Breaking Paragraphs into +/// Lines_](http://www.eprg.org/G53DOC/pdfs/knuth-plass-breaking.pdf) +/// by Knuth and Plass. The implementation here is based on [Python +/// code by David +/// Eppstein](https://github.com/jfinkels/PADS/blob/master/pads/wrap.py). +/// +/// **Note:** Only available when the `smawk` Cargo feature is +/// enabled. +pub fn wrap_optimal_fit<'a, 'b, T: Fragment>( + fragments: &'a [T], + line_widths: &'b [usize], +) -> Vec<&'a [T]> { + // The final line width is used for all remaining lines. + let default_line_width = line_widths.last().copied().unwrap_or(0); + let mut widths = Vec::with_capacity(fragments.len() + 1); + let mut width = 0; + widths.push(width); + for fragment in fragments { + width += fragment.width() + fragment.whitespace_width(); + widths.push(width); + } + + let line_numbers = LineNumbers::new(fragments.len()); + + let minima = smawk::online_column_minima(0, widths.len(), |minima, i, j| { + // Line number for fragment `i`. + let line_number = line_numbers.get(i, &minima); + let line_width = line_widths + .get(line_number) + .copied() + .unwrap_or(default_line_width); + let target_width = std::cmp::max(1, line_width); + + // Compute the width of a line spanning fragments[i..j] in + // constant time. We need to adjust widths[j] by subtracting + // the whitespace of fragment[j-i] and then add the penalty. + let line_width = widths[j] - widths[i] - fragments[j - 1].whitespace_width() + + fragments[j - 1].penalty_width(); + + // We compute cost of the line containing fragments[i..j]. We + // start with values[i].1, which is the optimal cost for + // breaking before fragments[i]. + // + // First, every extra line cost NLINE_PENALTY. + let mut cost = minima[i].1 + NLINE_PENALTY; + + // Next, we add a penalty depending on the line length. + if line_width > target_width { + // Lines that overflow get a hefty penalty. + let overflow = (line_width - target_width) as i32; + cost += overflow * OVERFLOW_PENALTY; + } else if j < fragments.len() { + // Other lines (except for the last line) get a milder + // penalty which depend on the size of the gap. + let gap = (target_width - line_width) as i32; + cost += gap * gap; + } else if i + 1 == j && line_width < target_width / SHORT_LINE_FRACTION { + // The last line can have any size gap, but we do add a + // penalty if the line is very short (typically because it + // contains just a single word). + cost += SHORT_LAST_LINE_PENALTY; + } + + // Finally, we discourage hyphens. + if fragments[j - 1].penalty_width() > 0 { + // TODO: this should use a penalty value from the fragment + // instead. + cost += HYPHEN_PENALTY; + } + + cost + }); + + let mut lines = Vec::with_capacity(line_numbers.get(fragments.len(), &minima)); + let mut pos = fragments.len(); + loop { + let prev = minima[pos].0; + lines.push(&fragments[prev..pos]); + pos = prev; + if pos == 0 { + break; + } + } + + lines.reverse(); + lines +} diff --git a/third_party/rust/textwrap/tests/indent.rs b/third_party/rust/textwrap/tests/indent.rs new file mode 100644 index 000000000000..9dd5ad2642d4 --- /dev/null +++ b/third_party/rust/textwrap/tests/indent.rs @@ -0,0 +1,88 @@ +/// tests cases ported over from python standard library +use textwrap::{dedent, indent}; + +const ROUNDTRIP_CASES: [&str; 3] = [ + // basic test case + "Hi.\nThis is a test.\nTesting.", + // include a blank line + "Hi.\nThis is a test.\n\nTesting.", + // include leading and trailing blank lines + "\nHi.\nThis is a test.\nTesting.\n", +]; + +const WINDOWS_CASES: [&str; 2] = [ + // use windows line endings + "Hi.\r\nThis is a test.\r\nTesting.", + // pathological case + "Hi.\r\nThis is a test.\n\r\nTesting.\r\n\n", +]; + +#[test] +fn test_indent_nomargin_default() { + // indent should do nothing if 'prefix' is empty. + for text in ROUNDTRIP_CASES.iter() { + assert_eq!(&indent(text, ""), text); + } + for text in WINDOWS_CASES.iter() { + assert_eq!(&indent(text, ""), text); + } +} + +#[test] +fn test_roundtrip_spaces() { + // A whitespace prefix should roundtrip with dedent + for text in ROUNDTRIP_CASES.iter() { + assert_eq!(&dedent(&indent(text, " ")), text); + } +} + +#[test] +fn test_roundtrip_tabs() { + // A whitespace prefix should roundtrip with dedent + for text in ROUNDTRIP_CASES.iter() { + assert_eq!(&dedent(&indent(text, "\t\t")), text); + } +} + +#[test] +fn test_roundtrip_mixed() { + // A whitespace prefix should roundtrip with dedent + for text in ROUNDTRIP_CASES.iter() { + assert_eq!(&dedent(&indent(text, " \t \t ")), text); + } +} + +#[test] +fn test_indent_default() { + // Test default indenting of lines that are not whitespace only + let prefix = " "; + let expected = [ + // Basic test case + " Hi.\n This is a test.\n Testing.", + // Include a blank line + " Hi.\n This is a test.\n\n Testing.", + // Include leading and trailing blank lines + "\n Hi.\n This is a test.\n Testing.\n", + ]; + for (text, expect) in ROUNDTRIP_CASES.iter().zip(expected.iter()) { + assert_eq!(&indent(text, prefix), expect) + } + let expected = [ + // Use Windows line endings + " Hi.\r\n This is a test.\r\n Testing.", + // Pathological case + " Hi.\r\n This is a test.\n\r\n Testing.\r\n\n", + ]; + for (text, expect) in WINDOWS_CASES.iter().zip(expected.iter()) { + assert_eq!(&indent(text, prefix), expect) + } +} + +#[test] +fn indented_text_should_have_the_same_number_of_lines_as_the_original_text() { + let texts = ["foo\nbar", "foo\nbar\n", "foo\nbar\nbaz"]; + for original in texts.iter() { + let indented = indent(original, ""); + assert_eq!(&indented, original); + } +} diff --git a/third_party/rust/textwrap/tests/traits.rs b/third_party/rust/textwrap/tests/traits.rs new file mode 100644 index 000000000000..cd0d73c831a3 --- /dev/null +++ b/third_party/rust/textwrap/tests/traits.rs @@ -0,0 +1,86 @@ +use textwrap::word_separators::{AsciiSpace, WordSeparator}; +use textwrap::word_splitters::{HyphenSplitter, NoHyphenation, WordSplitter}; +use textwrap::wrap_algorithms::{FirstFit, WrapAlgorithm}; +use textwrap::Options; + +/// Cleaned up type name. +fn type_name(_val: &T) -> String { + std::any::type_name::().replace("alloc::boxed::Box", "Box") +} + +#[test] +#[cfg(not(feature = "smawk"))] +#[cfg(not(feature = "unicode-linebreak"))] +fn static_hyphensplitter() { + // Inferring the full type. + let options = Options::new(10); + assert_eq!( + type_name(&options), + format!( + "textwrap::Options<{}, {}, {}>", + "textwrap::wrap_algorithms::FirstFit", + "textwrap::word_separators::AsciiSpace", + "textwrap::word_splitters::HyphenSplitter" + ) + ); + + // Inferring part of the type. + let options: Options<_, _, HyphenSplitter> = Options::new(10); + assert_eq!( + type_name(&options), + format!( + "textwrap::Options<{}, {}, {}>", + "textwrap::wrap_algorithms::FirstFit", + "textwrap::word_separators::AsciiSpace", + "textwrap::word_splitters::HyphenSplitter" + ) + ); + + // Explicitly making all parameters inferred. + let options: Options<_, _, _> = Options::new(10); + assert_eq!( + type_name(&options), + format!( + "textwrap::Options<{}, {}, {}>", + "textwrap::wrap_algorithms::FirstFit", + "textwrap::word_separators::AsciiSpace", + "textwrap::word_splitters::HyphenSplitter" + ) + ); +} + +#[test] +fn box_static_nohyphenation() { + // Inferred static type. + let options = Options::new(10) + .wrap_algorithm(Box::new(FirstFit)) + .word_splitter(Box::new(NoHyphenation)) + .word_separator(Box::new(AsciiSpace)); + assert_eq!( + type_name(&options), + format!( + "textwrap::Options<{}, {}, {}>", + "Box", + "Box", + "Box" + ) + ); +} + +#[test] +fn box_dyn_wordsplitter() { + // Inferred dynamic type due to default type parameter. + let options = Options::new(10) + .wrap_algorithm(Box::new(FirstFit) as Box) + .word_splitter(Box::new(HyphenSplitter) as Box) + .word_separator(Box::new(AsciiSpace) as Box); + assert_eq!( + type_name(&options), + format!( + "textwrap::Options<{}, {}, {}>", + "Box", + "Box", + "Box" + ) + ); +} diff --git a/third_party/rust/textwrap/tests/version-numbers.rs b/third_party/rust/textwrap/tests/version-numbers.rs index 85c52e372f4f..3f429b187adb 100644 --- a/third_party/rust/textwrap/tests/version-numbers.rs +++ b/third_party/rust/textwrap/tests/version-numbers.rs @@ -1,17 +1,22 @@ -#[macro_use] -extern crate version_sync; - #[test] fn test_readme_deps() { - assert_markdown_deps_updated!("README.md"); + version_sync::assert_markdown_deps_updated!("README.md"); } #[test] -fn test_readme_changelog() { - assert_contains_regex!("README.md", r"^### Version {version} — .* \d\d?.., 20\d\d$"); +fn test_changelog() { + version_sync::assert_contains_regex!( + "CHANGELOG.md", + r"^## Version {version} \(20\d\d-\d\d-\d\d\)" + ); } #[test] fn test_html_root_url() { - assert_html_root_url_updated!("src/lib.rs"); + version_sync::assert_html_root_url_updated!("src/lib.rs"); +} + +#[test] +fn test_dependency_graph() { + version_sync::assert_contains_regex!("src/lib.rs", "master/images/textwrap-{version}.svg"); }