{"id":13533066,"url":"https://github.com/tailhook/rust-argparse","last_synced_at":"2025-04-08T09:08:39.000Z","repository":{"id":16711894,"uuid":"19468749","full_name":"tailhook/rust-argparse","owner":"tailhook","description":"The command-line argument parser library for rust","archived":false,"fork":false,"pushed_at":"2023-05-27T12:04:55.000Z","size":827,"stargazers_count":243,"open_issues_count":11,"forks_count":40,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-01T07:51:43.731Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tailhook.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2014-05-05T19:43:09.000Z","updated_at":"2025-01-17T13:51:03.000Z","dependencies_parsed_at":"2024-01-14T02:32:38.148Z","dependency_job_id":"7828b356-9f53-4837-b1d2-48041b611518","html_url":"https://github.com/tailhook/rust-argparse","commit_stats":{"total_commits":170,"total_committers":23,"mean_commits":7.391304347826087,"dds":0.2529411764705882,"last_synced_commit":"da2b248d3d26650e23d033841ee1beeff8484ab2"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tailhook%2Frust-argparse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tailhook%2Frust-argparse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tailhook%2Frust-argparse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tailhook%2Frust-argparse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tailhook","download_url":"https://codeload.github.com/tailhook/rust-argparse/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247809962,"owners_count":20999816,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T07:01:16.263Z","updated_at":"2025-04-08T09:08:38.976Z","avatar_url":"https://github.com/tailhook.png","language":"Rust","readme":"# Argparse\r\n\r\nThe `rust-argparse` is a command-line parsing module for Rust. It's inspired by Python's `argparse` module.\r\n\r\nFeatures:\r\n\r\n- Supports standard (GNU) option conventions\r\n- Properly typed values\r\n- Automatically generated help and usage messages\r\n\r\n## Importing\r\n\r\nEdit your Cargo.toml to add `rust-argparse` to your project.\r\n\r\n```toml\r\n[dependencies]\r\nargparse = \"0.2.2\"\r\n```\r\n\r\n## Example\r\n\r\nThe following code is a simple Rust program with command-line arguments:\r\n\r\n```rs\r\nextern crate argparse;\r\n\r\nuse argparse::{ArgumentParser, StoreTrue, Store};\r\n\r\nfn main() {\r\n    let mut verbose = false;\r\n    let mut name = \"World\".to_string();\r\n    {  // this block limits scope of borrows by ap.refer() method\r\n        let mut ap = ArgumentParser::new();\r\n        ap.set_description(\"Greet somebody.\");\r\n        ap.refer(\u0026mut verbose)\r\n            .add_option(\u0026[\"-v\", \"--verbose\"], StoreTrue,\r\n            \"Be verbose\");\r\n        ap.refer(\u0026mut name)\r\n            .add_option(\u0026[\"--name\"], Store,\r\n            \"Name for the greeting\");\r\n        ap.parse_args_or_exit();\r\n    }\r\n\r\n    if verbose {\r\n        println!(\"name is {}\", name);\r\n    }\r\n    println!(\"Hello {}!\", name);\r\n}\r\n```\r\n\r\nAssuming the Rust code above is saved into a file `greeting.rs`, let's see what we have now:\r\n\r\n```\r\n$ rustc greeting.rs\r\n$ ./greeting -h\r\nUsage:\r\n  ./greeting [OPTIONS]\r\n\r\nGreet somebody.\r\n\r\nOptional arguments:\r\n  -h, --help  Show this help message and exit\r\n  -v, --verbose\r\n             Be verbose\r\n  --name NAME Name for the greeting\r\n$ ./greeting\r\nHello World!\r\n$ ./greeting --name Bob\r\nHello Bob!\r\n$ ./greeting -v --name Alice\r\nname is Alice\r\nHello Alice!\r\n```\r\n\r\n## Basic Workflow\r\n\r\n### Create ArgumentParser\r\n\r\nThe argument parser is created empty and is built incrementally. So we create a mutable variable:\r\n\r\n```rs\r\nextern crate argparse;\r\nuse argparse::ArgumentParser;\r\n\r\nlet mut parser = ArgumentParser::new();\r\n```\r\n\r\n### Customize\r\n\r\nThere are optional customization methods. The most important one is:\r\n\r\n```rs\r\nparser.set_description(\"My command-line utility\");\r\n```\r\n\r\nThe description is rewrapped to fit 80 column string nicely. Just like option descriptions.\r\n\r\n### Add Options\r\n\r\nThe `refer` method creates a cell variable, which the result will be written to:\r\n\r\n```rs\r\nlet mut verbose = false;\r\nparser.refer(\u0026mut verbose);\r\n```\r\n\r\nNext we add options which control the variable. For example:\r\n\r\n```rs\r\nparser.refer(\u0026mut verbose)\r\n    .add_option(\u0026[\"-v\", \"--verbose\"], StoreTrue,\r\n                \"Be verbose\");\r\n```\r\n\r\nYou may add multiple options for the same variable:\r\n\r\n```rs\r\nparser.refer(\u0026mut verbose)\r\n    .add_option(\u0026[\"-v\", \"--verbose\"], StoreTrue,\r\n                \"Be verbose\")\r\n    .add_option(\u0026[\"-q\", \"--quiet\"], StoreFalse,\r\n                \"Be verbose\");\r\n```\r\n\r\nSimilarly positional arguments are added:\r\n\r\n```rs\r\nlet mut command = String::new();\r\nparser.refer(\u0026mut command)\r\n    .add_argument(\"command\", Store,\r\n                  \"Command to run\");\r\n```\r\n\r\n### Organizing Options\r\n\r\nIt's often useful to organize options into some kind of structure. You can easily borrow variables from the structure into option parser. For example:\r\n\r\n```rs\r\nstruct Options {\r\n    verbose: bool,\r\n}\r\n// ...\r\nlet mut options = Options { verbose: false };\r\nparser.refer(\u0026mut options.verbose)\r\n    .add_option(\u0026[\"-v\"], StoreTrue,\r\n                \"Be verbose\");\r\n```\r\n\r\n### Parsing Arguments\r\n\r\nAll the complex work is done in `parser.parse_args()`. But there is a simpler option:\r\n\r\n```rs\r\nparser.parse_args_or_exit();\r\n```\r\n\r\nIn case you don't want argparse to exit itself, you might use the `parse_args` function directly:\r\n\r\n```rs\r\nuse std::process::exit;\r\n\r\nmatch parser.parse_args() {\r\n    Ok(()) =\u003e {}\r\n    Err(x) =\u003e {\r\n        std::process::exit(x);\r\n    }\r\n}\r\n```\r\n\r\n## ArgumentParser Methods\r\n\r\n***`parser.refer\u003cT\u003e(var: \u0026mut T) -\u003e Ref`***\r\n\r\nAttach the variable to the argument parser. The options are added to the returned `Ref` object and modify a variable passed to the method.\r\n\r\n***`parser.add_option(names: \u0026[\u0026str], action: TypedAction, help: \u0026str)`***\r\n\r\nAdd a single option which has no parameters. Most options must be added by `refer(..)` and methods on `Ref` object (see below).\r\n\r\nExample:\r\n\r\n```rs\r\nap.add_option(\u0026[\"-V\", \"--version\"],\r\n    Print(env!(\"CARGO_PKG_VERSION\").to_string()), \"Show version\");\r\n```\r\n\r\n***`parser.set_description(descr: \u0026str)`***\r\n\r\nSet description that is at the top of help message.\r\n\r\n***`parser.stop_on_first_argument(val: bool)`***\r\n\r\nIf called with `true`, parser will stop searching for options when first non-option (the one doesn't start with `-`) argument is encountered. This is useful if you want to parse following options with another argparser or external program.\r\n\r\n***`parser.silence_double_dash(val: bool)`***\r\n\r\nIf called with `true` (default), parser will not treat first double dash `--` as positional argument. Use `false` if you need to add some meaning to the `--` marker.\r\n\r\n***`parser.print_usage(name: \u0026str, writer: \u0026mut Write)`***\r\n\r\nPrint usage string to stderr.\r\n\r\n***`parser.print_help(name: \u0026str, writer: \u0026mut Write)`***\r\n\r\nWrites help to `writer`, used by `--help` option internally.\r\n\r\n***`parser.parse_args()`***\r\n\r\nMethod that does all the dirty work and returns `Result`.\r\n\r\n***`parser.parse_args_or_exit()`***\r\n\r\nMethod that does all the dirty work and in case of failure just `exit()`.\r\n\r\n## Variable Reference Methods\r\n\r\nThe `argparse::Ref` object is returned from `parser.refer()`. The following methods are used to add and customize arguments:\r\n\r\n***`option.add_option(names: \u0026[\u0026str], action: TypedAction, help: \u0026str)`***\r\n\r\nAdd an option. All items in names should be either in format `-X` or `--long-option` (i.e. one dash and one char or two dashes and long name). How this option will be interpreted and whether it will have an argument dependes on the action. See below list of actions.\r\n\r\n***`option.add_argument(name: \u0026str, action: TypedAction, help: \u0026str)`***\r\n\r\nAdd a positional argument.\r\n\r\n***`option.metavar(var: \u0026str)`***\r\n\r\nA name of the argument in usage messages (for options having argument).\r\n\r\n***`option.envvar(var: \u0026str)`***\r\n\r\nA name of the environment variable to get option value from. The value would be parsed with `FromStr::from_str`, just like an option having `Store` action.\r\n\r\n***`option.required()`***\r\n\r\nThe option or argument is required (it's optional by default). If multiple options or multiple arguments are defined for this reference at least one of them is required.\r\n\r\n## Actions\r\n\r\nThe following actions are available out of the box. They may be used in either `add_option` or `add_argument`:\r\n\r\n***`Store`***\r\n\r\nAn option has single argument. Stores a value from command-line in a variable. Any type that has the `FromStr` and `Clone` traits implemented may be used.\r\n\r\n***`StoreOption`***\r\n\r\nAs `Store`, but wrap value with `Some` for use with `Option`. For example:\r\n\r\n```rs\r\nlet mut x: Option\u003ci32\u003e = None; ap.refer(\u0026mut x).add_option(\u0026[\"-x\"], StoreOption, \"Set var x\");\r\n```\r\n\r\n***`StoreConst(value)`***\r\n\r\nAn option has no arguments. Store a hard-coded `value` into variable, when specified. Any type with the `Clone` trait implemented may be used.\r\n\r\n***`PushConst(value)`***\r\n\r\nAn option has no arguments. Push a hard-coded `value` into variable, when specified. Any type which has the `Clone` trait implemented may be used. Option might used for a list of operations to perform, when `required` is set for this variable, at least one operation is required.\r\n\r\n***`StoreTrue`***\r\n\r\nStores boolean `true` value in a variable. (shortcut for `StoreConst(true)`)\r\n\r\n***`StoreFalse`***\r\n\r\nStores boolean `false` value in a variable. (shortcut for `StoreConst(false)`)\r\n\r\n***`IncrBy(num)`***\r\n\r\nAn option has no arguments. Increments the value stored in a variable by a value `num`. Any type which has the `Add` and `Clone` traits may be used.\r\n\r\n***`DecrBy(num)`***\r\n\r\nDecrements the value stored in a variable by a value `num`. Any type which has the `Sub` and `Clone` traits may be used.\r\n\r\n***`Collect`***\r\n\r\nWhen used for an `--option`, requires single argument. When used for a positional argument consumes all remaining arguments. Parsed options are added to the list. I.e. a `Collect` action requires a `Vec\u003cint\u003e` variable. Parses arguments using `FromStr` trait.\r\n\r\n***`List`***\r\n\r\nWhen used for positional argument, works the same as `List`. When used as an option, consumes all remaining arguments.\r\n\r\nNote the usage of `List` is strongly discouraged, because of complex rules below. Use `Collect` and positional options if possible. But usage of `List` action may be useful if you need shell expansion of anything other than last positional argument.\r\n\r\nLet's learn rules by example. For the next options:\r\n\r\n```rs\r\nap.refer(\u0026mut lst1).add_option(\u0026[\"-X\", \"--xx\"], List, \"List1\");\r\nap.refer(\u0026mut lst2).add_argument(\"yy\", List, \"List2\");\r\n```\r\n\r\nThe following command line:\r\n\r\n```\r\n./run 1 2 3 -X 4 5 6\r\n```\r\n\r\nWill return `[1, 2, 3]` in the `lst1` and the `[4, 5, 6]` in the `lst2`.\r\n\r\nNote that using when using `=` or equivalent short option mode, the 'consume all' mode is not enabled. I.e. in the following command-line:\r\n\r\n```\r\n./run 1 2 -X3 4 --xx=5 6\r\n```\r\n\r\nThe `lst1` has `[3, 5]` and `lst2` has `[1, 2, 4, 6]`. The argument consuming also stops on `--` or the next option:\r\n\r\n```\r\n./run -X 1 2 3 -- 4 5 6\r\n./run -X 1 2 --xx=3 4 5 6\r\n```\r\n\r\nBoth of the above parse `[4, 5, 6]` as `lst1` and the `[1, 2, 3]` as the `lst2`.\r\n\r\n***`Print(value)`***\r\n\r\nPrint the text and exit (with status `0`). Useful for the `--version` option:\r\n\r\n```rs\r\nap.add_option(\u0026[\"-V\", \"--version\"],\r\n        Print(env!(\"CARGO_PKG_VERSION\").to_string()), \"Show version\");\r\n```\r\n","funding_links":[],"categories":["Rust","[Rust](https://www.rust-lang.org/)"],"sub_categories":["Useful awesome list for Ruby cli"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftailhook%2Frust-argparse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftailhook%2Frust-argparse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftailhook%2Frust-argparse/lists"}