pico-args-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100127220ustar { "git": { "sha1": "56e8872fa31f168fd87e84fdc5f24bd60875daea" }, "path_in_vcs": "" }pico-args-0.5.0/.github/workflows/main.yml000064400000000000000000000015040072674642500166060ustar 00000000000000name: Rust on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-18.04 strategy: matrix: rust: - 1.32.0 - stable steps: - name: Checkout uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Test with default features run: cargo test - name: Test without default features run: cargo test --no-default-features - name: Test with short-space-opt run: cargo test --no-default-features --features short-space-opt - name: Test with combined-flags run: cargo test --no-default-features --features combined-flags - name: Test with all features run: cargo test --all-features pico-args-0.5.0/.gitignore000064400000000000000000000000530072674642500135300ustar 00000000000000target **/*.rs.bk Cargo.lock /.idea /*.iml pico-args-0.5.0/CHANGELOG.md000064400000000000000000000067710072674642500133660ustar 00000000000000# Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ## [0.5.0] - 2022-06-04 ### Changed - The `eq-separator` build feature is no longer enabled by default. - Small changes to the `Display` output for `Error`. ## [0.4.2] - 2021-06-03 ### Fixed - Ignore long options when parsing short options when `combined-flags` feature is enabled. Thanks to [@riquito](https://github.com/riquito). - `Arguments::contains` docs. Thanks to [@jneem](https://github.com/jneem). ## [0.4.1] - 2021-05-03 ### Added - `combined-flags` feature. Thanks to [@alexwennerberg](https://github.com/alexwennerberg). ## [0.4.0] - 2021-01-03 ### Added - `Arguments::opt_free_from_*`. ### Changed - `Arguments::finish` no longer returns an error and simply returns remaining arguments as is. - `Arguments::free_from_*` methods no longer check that argument doesn't start with `-`. - `Arguments::free_from_*` methods return `T` instead of `Option` now. Use `Arguments::opt_free_from_*` instead. ### Removed - `Arguments::free` and `Arguments::free_os`. You should use `Arguments::free_from_*` methods or parse them manually after calling `Arguments::finish`. - `Error::UnusedArgsLeft`. This should be handled by the caller now. ## [0.3.4] - 2020-08-09 ### Added - `short-space-opt` build feature. Thanks to [@hdamron17](https://github.com/hdamron17). ## [0.3.3] - 2020-06-26 ### Added - `values_from_str`, `values_from_fn` and `values_from_os_str`.
Those functions can be used to parse arguments like:
`--file /path1 --file /path2 --file /path3`
But not `--file /path1 /path2 /path3`. ## [0.3.2] - 2020-06-15 ### Added - `eq-separator` build feature. ## [0.3.1] - 2020-01-08 ### Added - `Arguments::subcommand`. Thanks to [@matklad](https://github.com/matklad). ## [0.3.0] - 2019-09-23 ### Added - Required arguments support. - `Error::MissingOption` when option is required but not present. ### Changed - Rename `value_from_str` into `opt_value_from_str`. - Rename `value_from_fn` into `opt_value_from_fn`. - Rename `value_from_os_str` into `opt_value_from_os_str`. - `value_from_str`, `value_from_fn` and `value_from_os_str` will return `T` and not `Option` from now. ## [0.2.0] - 2019-07-26 ### Added - Non UTF-8 arguments support. - `free_from_str`, `free_from_fn` and `free_from_os_str`. - `value_from_os_str`. ### Changed - `value_from_fn` allows any error type that implements `Display` now and not only `String`. - `from_args` -> `from_vec`. And it accepts `Vec` now. - The `Error` enum. ### Fixed - Do not panic while parsing non UTF-8 arguments. [Unreleased]: https://github.com/RazrFalcon/pico-args/compare/v0.5.0...HEAD [0.5.0]: https://github.com/RazrFalcon/pico-args/compare/v0.4.2...v0.5.0 [0.4.2]: https://github.com/RazrFalcon/pico-args/compare/v0.4.1...v0.4.2 [0.4.1]: https://github.com/RazrFalcon/pico-args/compare/v0.4.0...v0.4.1 [0.4.0]: https://github.com/RazrFalcon/pico-args/compare/v0.3.4...v0.4.0 [0.3.4]: https://github.com/RazrFalcon/pico-args/compare/v0.3.3...v0.3.4 [0.3.3]: https://github.com/RazrFalcon/pico-args/compare/v0.3.2...v0.3.3 [0.3.2]: https://github.com/RazrFalcon/pico-args/compare/v0.3.1...v0.3.2 [0.3.1]: https://github.com/RazrFalcon/pico-args/compare/v0.3.0...v0.3.1 [0.3.0]: https://github.com/RazrFalcon/pico-args/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/RazrFalcon/pico-args/compare/v0.1.0...v0.2.0 pico-args-0.5.0/Cargo.lock0000644000000002310000000000100106710ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "pico-args" version = "0.5.0" pico-args-0.5.0/Cargo.toml0000644000000016350000000000100107250ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "pico-args" version = "0.5.0" authors = ["Yevhenii Reizner "] exclude = ["test-apps/**"] description = "An ultra simple CLI arguments parser." documentation = "https://docs.rs/pico-args/" readme = "README.md" keywords = [ "args", "cli", ] license = "MIT" repository = "https://github.com/RazrFalcon/pico-args" [features] combined-flags = [] default = [] eq-separator = [] short-space-opt = [] pico-args-0.5.0/Cargo.toml.orig000064400000000000000000000006770072674642500144430ustar 00000000000000[package] name = "pico-args" version = "0.5.0" authors = ["Yevhenii Reizner "] edition = "2018" keywords = ["args", "cli"] license = "MIT" description = "An ultra simple CLI arguments parser." repository = "https://github.com/RazrFalcon/pico-args" documentation = "https://docs.rs/pico-args/" readme = "README.md" exclude = ["test-apps/**"] [features] default = [] eq-separator = [] combined-flags = [] short-space-opt = [] pico-args-0.5.0/LICENSE000064400000000000000000000020450072674642500125500ustar 00000000000000Copyright (c) 2019 Yevhenii Reizner 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. pico-args-0.5.0/README.md000064400000000000000000000055300072674642500130240ustar 00000000000000# pico-args ![Build Status](https://github.com/RazrFalcon/pico-args/workflows/Rust/badge.svg) [![Crates.io](https://img.shields.io/crates/v/pico-args.svg)](https://crates.io/crates/pico-args) [![Documentation](https://docs.rs/pico-args/badge.svg)](https://docs.rs/pico-args) [![Rust 1.32+](https://img.shields.io/badge/rust-1.31+-orange.svg)](https://www.rust-lang.org) ![](https://img.shields.io/badge/unsafe-forbidden-brightgreen.svg) An ultra simple CLI arguments parser. If you think that this library doesn't support some feature, it's probably intentional. - No help generation - Only flags, options, free arguments and subcommands are supported - Options can be separated by a space, `=` or nothing. See build features - Arguments can be in any order - Non UTF-8 arguments are supported ## Build features - `eq-separator` Allows parsing arguments separated by `=`
This feature adds about 1KiB to the resulting binary - `short-space-opt` Makes the space between short keys and their values optional (e.g. `-w10`)
If `eq-separator` is enabled, then it takes precedence and the '=' is not included.
If `eq-separator` is disabled, then `-K=value` gives an error instead of returning `"=value"`.
The optional space is only applicable for short keys because `--keyvalue` would be ambiguous - `combined-flags` Allows combination of flags, e.g. `-abc` instead of `-a -b -c`
If `short-space-opt` or `eq-separator` are enabled, you must parse flags after values, to prevent ambiguities ## Limitations The main fundamental limitation of `pico-args` is that it parses arguments in an arbitrary order. This is because we have a sort of "steaming" API and we don't know all the keys/arguments beforehand. This could lead to some unexpected behaviors. Specifically, let's say you have a following arguments: ``` --arg1 --arg2 value ``` If your parser tries to parse `--arg1` as key-value first, than its value would be `--arg2` and not `value`, because the parser simply takes the "next" argument. A properer parser would knew that `--arg2` is a key and will return an error, since the value is missing. If your parser tries to parse `--arg2` as a flag first and then `--arg1` as key-value, than its value would be `value`, because `--arg2` was already removed by the parser and the arguments list looks like `--arg1 value` to the parser. If such behavior is unacceptable to your application, then you have to use a more high-level arguments parsing library. ## Alternatives The core idea of `pico-args` is to provide some "sugar" for arguments parsing without a lot of overhead (binary or compilation time wise). There are no point in comparing parsing features since `pico-args` supports only the bare minimum. [Here](https://github.com/rust-cli/argparse-benchmarks-rs) is a great comparison of various arguments parsing libraries. ## License MIT pico-args-0.5.0/examples/app.rs000064400000000000000000000042070072674642500145110ustar 00000000000000#![allow(dead_code)] const HELP: &str = "\ App USAGE: app [OPTIONS] --number NUMBER [INPUT] FLAGS: -h, --help Prints help information OPTIONS: --number NUMBER Sets a number --opt-number NUMBER Sets an optional number --width WIDTH Sets width [default: 10] --output PATH Sets an output path ARGS: "; #[derive(Debug)] struct AppArgs { number: u32, opt_number: Option, width: u32, input: std::path::PathBuf, output: Option, } fn main() { let args = match parse_args() { Ok(v) => v, Err(e) => { eprintln!("Error: {}.", e); std::process::exit(1); } }; println!("{:#?}", args); } fn parse_args() -> Result { let mut pargs = pico_args::Arguments::from_env(); // Help has a higher priority and should be handled separately. if pargs.contains(["-h", "--help"]) { print!("{}", HELP); std::process::exit(0); } let args = AppArgs { // Parses a required value that implements `FromStr`. // Returns an error if not present. number: pargs.value_from_str("--number")?, // Parses an optional value that implements `FromStr`. opt_number: pargs.opt_value_from_str("--opt-number")?, // Parses an optional value from `&str` using a specified function. width: pargs.opt_value_from_fn("--width", parse_width)?.unwrap_or(10), // Parses an optional value from `&OsStr` using a specified function. output: pargs.opt_value_from_os_str("--input", parse_path)?, // Parses a required free-standing/positional argument. input: pargs.free_from_str()?, }; // It's up to the caller what to do with the remaining arguments. let remaining = pargs.finish(); if !remaining.is_empty() { eprintln!("Warning: unused arguments left: {:?}.", remaining); } Ok(args) } fn parse_width(s: &str) -> Result { s.parse().map_err(|_| "not a number") } fn parse_path(s: &std::ffi::OsStr) -> Result { Ok(s.into()) } pico-args-0.5.0/examples/dash_dash.rs000064400000000000000000000023640072674642500156510ustar 00000000000000#![allow(dead_code)] use std::ffi::OsString; #[derive(Debug)] struct Args { forwarded_args: Vec, help: bool, } fn parse_args() -> Result { // `from_vec` takes `OsString`, not `String`. let mut args: Vec<_> = std::env::args_os().collect(); args.remove(0); // remove the executable path. // Find and process `--`. let forwarded_args = if let Some(dash_dash) = args.iter().position(|arg| arg == "--") { // Store all arguments following ... let later_args = args.drain(dash_dash+1..).collect(); // .. then remove the `--` args.pop(); later_args } else { Vec::new() }; // Now pass the remaining arguments through to `pico_args`. let mut args = pico_args::Arguments::from_vec(args); let res = Args { forwarded_args, help: args.contains(["-h", "--help"]), }; // It's up to the caller what to do with the remaining arguments. let remaining = args.finish(); if !remaining.is_empty() { eprintln!("Warning: unused arguments left: {:?}", remaining); } Ok(res) } fn main() { match parse_args() { Ok(args) => println!("{:#?}", args), Err(err) => eprintln!("{}", err), } } pico-args-0.5.0/src/lib.rs000064400000000000000000000632410072674642500134530ustar 00000000000000/*! An ultra simple CLI arguments parser. If you think that this library doesn't support some feature, it's probably intentional. - No help generation - Only flags, options, free arguments and subcommands are supported - No combined flags (like `-vvv` or `-abc`) - Options can be separated by a space, `=` or nothing. See build features - Arguments can be in any order - Non UTF-8 arguments are supported ## Build features - `eq-separator` Allows parsing arguments separated by `=`
This feature adds about 1KiB to the resulting binary - `short-space-opt` Makes the space between short keys and their values optional (e.g. `-w10`)
If `eq-separator` is enabled, then it takes precedence and the '=' is not included.
If `eq-separator` is disabled, then `-K=value` gives an error instead of returning `"=value"`.
The optional space is only applicable for short keys because `--keyvalue` would be ambiguous - `combined-flags` Allows combination of flags, e.g. `-abc` instead of `-a -b -c`.
If `short-space-opt` or `eq-separator` are enabled, you must parse flags after values, to prevent ambiguities. */ #![forbid(unsafe_code)] #![warn(missing_docs)] use std::ffi::{OsString, OsStr}; use std::fmt::{self, Display}; use std::str::FromStr; /// A list of possible errors. #[derive(Clone, Debug)] pub enum Error { /// Arguments must be a valid UTF-8 strings. NonUtf8Argument, /// A missing free-standing argument. MissingArgument, /// A missing option. MissingOption(Keys), /// An option without a value. OptionWithoutAValue(&'static str), /// Failed to parse a UTF-8 free-standing argument. #[allow(missing_docs)] Utf8ArgumentParsingFailed { value: String, cause: String }, /// Failed to parse a raw free-standing argument. #[allow(missing_docs)] ArgumentParsingFailed { cause: String }, } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::NonUtf8Argument => { write!(f, "argument is not a UTF-8 string") } Error::MissingArgument => { write!(f, "free-standing argument is missing") } Error::MissingOption(key) => { if key.second().is_empty() { write!(f, "the '{}' option must be set", key.first()) } else { write!(f, "the '{}/{}' option must be set", key.first(), key.second()) } } Error::OptionWithoutAValue(key) => { write!(f, "the '{}' option doesn't have an associated value", key) } Error::Utf8ArgumentParsingFailed { value, cause } => { write!(f, "failed to parse '{}': {}", value, cause) } Error::ArgumentParsingFailed { cause } => { write!(f, "failed to parse a binary argument: {}", cause) } } } } impl std::error::Error for Error {} #[derive(Clone, Copy, PartialEq)] enum PairKind { #[cfg(any(feature = "eq-separator", feature = "short-space-opt"))] SingleArgument, TwoArguments, } /// An arguments parser. #[derive(Clone, Debug)] pub struct Arguments(Vec); impl Arguments { /// Creates a parser from a vector of arguments. /// /// The executable path **must** be removed. /// /// This can be used for supporting `--` arguments to forward to another program. /// See `examples/dash_dash.rs` for an example. pub fn from_vec(args: Vec) -> Self { Arguments(args) } /// Creates a parser from [`env::args_os`]. /// /// The executable path will be removed. /// /// [`env::args_os`]: https://doc.rust-lang.org/stable/std/env/fn.args_os.html pub fn from_env() -> Self { let mut args: Vec<_> = std::env::args_os().collect(); args.remove(0); Arguments(args) } /// Parses the name of the subcommand, that is, the first positional argument. /// /// Returns `None` when subcommand starts with `-` or when there are no arguments left. /// /// # Errors /// /// - When arguments is not a UTF-8 string. pub fn subcommand(&mut self) -> Result, Error> { if self.0.is_empty() { return Ok(None); } if let Some(s) = self.0[0].to_str() { if s.starts_with('-') { return Ok(None); } } self.0.remove(0) .into_string() .map_err(|_| Error::NonUtf8Argument) .map(Some) } /// Checks that arguments contain a specified flag. /// /// Searches through all arguments, not only the first/next one. /// /// Calling this method "consumes" the flag: if a flag is present `n` /// times then the first `n` calls to `contains` for that flag will /// return `true`, and subsequent calls will return `false`. /// /// When the "combined-flags" feature is used, repeated letters count /// as repeated flags: `-vvv` is treated the same as `-v -v -v`. pub fn contains>(&mut self, keys: A) -> bool { self.contains_impl(keys.into()) } #[inline(never)] fn contains_impl(&mut self, keys: Keys) -> bool { if let Some((idx, _)) = self.index_of(keys) { self.0.remove(idx); true } else { #[cfg(feature = "combined-flags")] // Combined flags only work if the short flag is a single character { if keys.first().len() == 2 { let short_flag = &keys.first()[1..2]; for (n, item) in self.0.iter().enumerate() { if let Some(s) = item.to_str() { if s.starts_with('-') && !s.starts_with("--") && s.contains(short_flag) { if s.len() == 2 { // last flag self.0.remove(n); } else { self.0[n] = s.replacen(short_flag, "", 1).into(); } return true; } } } } } false } } /// Parses a key-value pair using `FromStr` trait. /// /// This is a shorthand for `value_from_fn("--key", FromStr::from_str)` pub fn value_from_str(&mut self, keys: A) -> Result where A: Into, T: FromStr, ::Err: Display, { self.value_from_fn(keys, FromStr::from_str) } /// Parses a key-value pair using a specified function. /// /// Searches through all argument, not only the first/next one. /// /// When a key-value pair is separated by a space, the algorithm /// will threat the next argument after the key as a value, /// even if it has a `-/--` prefix. /// So a key-value pair like `--key --value` is not an error. /// /// Must be used only once for each option. /// /// # Errors /// /// - When option is not present. /// - When key or value is not a UTF-8 string. Use [`value_from_os_str`] instead. /// - When value parsing failed. /// - When key-value pair is separated not by space or `=`. /// /// [`value_from_os_str`]: struct.Arguments.html#method.value_from_os_str pub fn value_from_fn, T, E: Display>( &mut self, keys: A, f: fn(&str) -> Result, ) -> Result { let keys = keys.into(); match self.opt_value_from_fn(keys, f) { Ok(Some(v)) => Ok(v), Ok(None) => Err(Error::MissingOption(keys)), Err(e) => Err(e), } } /// Parses an optional key-value pair using `FromStr` trait. /// /// This is a shorthand for `opt_value_from_fn("--key", FromStr::from_str)` pub fn opt_value_from_str(&mut self, keys: A) -> Result, Error> where A: Into, T: FromStr, ::Err: Display, { self.opt_value_from_fn(keys, FromStr::from_str) } /// Parses an optional key-value pair using a specified function. /// /// The same as [`value_from_fn`], but returns `Ok(None)` when option is not present. /// /// [`value_from_fn`]: struct.Arguments.html#method.value_from_fn pub fn opt_value_from_fn, T, E: Display>( &mut self, keys: A, f: fn(&str) -> Result, ) -> Result, Error> { self.opt_value_from_fn_impl(keys.into(), f) } #[inline(never)] fn opt_value_from_fn_impl( &mut self, keys: Keys, f: fn(&str) -> Result, ) -> Result, Error> { match self.find_value(keys)? { Some((value, kind, idx)) => { match f(value) { Ok(value) => { // Remove only when all checks are passed. self.0.remove(idx); if kind == PairKind::TwoArguments { self.0.remove(idx); } Ok(Some(value)) } Err(e) => { Err(Error::Utf8ArgumentParsingFailed { value: value.to_string(), cause: error_to_string(e), }) } } } None => Ok(None), } } // The whole logic must be type-independent to prevent monomorphization. #[cfg(any(feature = "eq-separator", feature = "short-space-opt"))] #[inline(never)] fn find_value( &mut self, keys: Keys, ) -> Result, Error> { if let Some((idx, key)) = self.index_of(keys) { // Parse a `--key value` pair. let value = match self.0.get(idx + 1) { Some(v) => v, None => return Err(Error::OptionWithoutAValue(key)), }; let value = os_to_str(value)?; Ok(Some((value, PairKind::TwoArguments, idx))) } else if let Some((idx, key)) = self.index_of2(keys) { // Parse a `--key=value` or `-Kvalue` pair. let value = &self.0[idx]; // Only UTF-8 strings are supported in this method. let value = value.to_str().ok_or_else(|| Error::NonUtf8Argument)?; let mut value_range = key.len()..value.len(); if value.as_bytes().get(value_range.start) == Some(&b'=') { #[cfg(feature = "eq-separator")] { value_range.start += 1; } #[cfg(not(feature = "eq-separator"))] return Err(Error::OptionWithoutAValue(key)); } else { // Key must be followed by `=` if not `short-space-opt` #[cfg(not(feature = "short-space-opt"))] return Err(Error::OptionWithoutAValue(key)); } // Check for quoted value. if let Some(c) = value.as_bytes().get(value_range.start).cloned() { if c == b'"' || c == b'\'' { value_range.start += 1; // A closing quote must be the same as an opening one. if ends_with(&value[value_range.start..], c) { value_range.end -= 1; } else { return Err(Error::OptionWithoutAValue(key)); } } } // Check length, otherwise String::drain will panic. if value_range.end - value_range.start == 0 { return Err(Error::OptionWithoutAValue(key)); } // Extract `value` from `--key="value"`. let value = &value[value_range]; if value.is_empty() { return Err(Error::OptionWithoutAValue(key)); } Ok(Some((value, PairKind::SingleArgument, idx))) } else { Ok(None) } } // The whole logic must be type-independent to prevent monomorphization. #[cfg(not(any(feature = "eq-separator", feature = "short-space-opt")))] #[inline(never)] fn find_value( &mut self, keys: Keys, ) -> Result, Error> { if let Some((idx, key)) = self.index_of(keys) { // Parse a `--key value` pair. let value = match self.0.get(idx + 1) { Some(v) => v, None => return Err(Error::OptionWithoutAValue(key)), }; let value = os_to_str(value)?; Ok(Some((value, PairKind::TwoArguments, idx))) } else { Ok(None) } } /// Parses multiple key-value pairs into the `Vec` using `FromStr` trait. /// /// This is a shorthand for `values_from_fn("--key", FromStr::from_str)` pub fn values_from_str(&mut self, keys: A) -> Result, Error> where A: Into, T: FromStr, ::Err: Display, { self.values_from_fn(keys, FromStr::from_str) } /// Parses multiple key-value pairs into the `Vec` using a specified function. /// /// This functions can be used to parse arguments like:
/// `--file /path1 --file /path2 --file /path3`
/// But not `--file /path1 /path2 /path3`. /// /// Arguments can also be separated: `--file /path1 --some-flag --file /path2` /// /// This method simply executes [`opt_value_from_fn`] multiple times. /// /// An empty `Vec` is not an error. /// /// [`opt_value_from_fn`]: struct.Arguments.html#method.opt_value_from_fn pub fn values_from_fn, T, E: Display>( &mut self, keys: A, f: fn(&str) -> Result, ) -> Result, Error> { let keys = keys.into(); let mut values = Vec::new(); loop { match self.opt_value_from_fn(keys, f) { Ok(Some(v)) => values.push(v), Ok(None) => break, Err(e) => return Err(e), } } Ok(values) } /// Parses a key-value pair using a specified function. /// /// Unlike [`value_from_fn`], parses `&OsStr` and not `&str`. /// /// Must be used only once for each option. /// /// # Errors /// /// - When option is not present. /// - When value parsing failed. /// - When key-value pair is separated not by space. /// Only [`value_from_fn`] supports `=` separator. /// /// [`value_from_fn`]: struct.Arguments.html#method.value_from_fn pub fn value_from_os_str, T, E: Display>( &mut self, keys: A, f: fn(&OsStr) -> Result, ) -> Result { let keys = keys.into(); match self.opt_value_from_os_str(keys, f) { Ok(Some(v)) => Ok(v), Ok(None) => Err(Error::MissingOption(keys)), Err(e) => Err(e), } } /// Parses an optional key-value pair using a specified function. /// /// The same as [`value_from_os_str`], but returns `Ok(None)` when option is not present. /// /// [`value_from_os_str`]: struct.Arguments.html#method.value_from_os_str pub fn opt_value_from_os_str, T, E: Display>( &mut self, keys: A, f: fn(&OsStr) -> Result, ) -> Result, Error> { self.opt_value_from_os_str_impl(keys.into(), f) } #[inline(never)] fn opt_value_from_os_str_impl( &mut self, keys: Keys, f: fn(&OsStr) -> Result, ) -> Result, Error> { if let Some((idx, key)) = self.index_of(keys) { // Parse a `--key value` pair. let value = match self.0.get(idx + 1) { Some(v) => v, None => return Err(Error::OptionWithoutAValue(key)), }; match f(value) { Ok(value) => { // Remove only when all checks are passed. self.0.remove(idx); self.0.remove(idx); Ok(Some(value)) } Err(e) => { Err(Error::ArgumentParsingFailed { cause: error_to_string(e) }) } } } else { Ok(None) } } /// Parses multiple key-value pairs into the `Vec` using a specified function. /// /// This method simply executes [`opt_value_from_os_str`] multiple times. /// /// Unlike [`values_from_fn`], parses `&OsStr` and not `&str`. /// /// An empty `Vec` is not an error. /// /// [`opt_value_from_os_str`]: struct.Arguments.html#method.opt_value_from_os_str /// [`values_from_fn`]: struct.Arguments.html#method.values_from_fn pub fn values_from_os_str, T, E: Display>( &mut self, keys: A, f: fn(&OsStr) -> Result, ) -> Result, Error> { let keys = keys.into(); let mut values = Vec::new(); loop { match self.opt_value_from_os_str(keys, f) { Ok(Some(v)) => values.push(v), Ok(None) => break, Err(e) => return Err(e), } } Ok(values) } #[inline(never)] fn index_of(&self, keys: Keys) -> Option<(usize, &'static str)> { // Do not unroll loop to save space, because it creates a bigger file. // Which is strange, since `index_of2` actually benefits from it. for key in &keys.0 { if !key.is_empty() { if let Some(i) = self.0.iter().position(|v| v == key) { return Some((i, key)); } } } None } #[cfg(any(feature = "eq-separator", feature = "short-space-opt"))] #[inline(never)] fn index_of2(&self, keys: Keys) -> Option<(usize, &'static str)> { // Loop unroll to save space. if !keys.first().is_empty() { if let Some(i) = self.0.iter().position(|v| index_predicate(v, keys.first())) { return Some((i, keys.first())); } } if !keys.second().is_empty() { if let Some(i) = self.0.iter().position(|v| index_predicate(v, keys.second())) { return Some((i, keys.second())); } } None } /// Parses a free-standing argument using `FromStr` trait. /// /// This is a shorthand for `free_from_fn(FromStr::from_str)` pub fn free_from_str(&mut self) -> Result where T: FromStr, ::Err: Display, { self.free_from_fn(FromStr::from_str) } /// Parses a free-standing argument using a specified function. /// /// Parses the first argument from the list of remaining arguments. /// Therefore, it's up to the caller to check if the argument is actually /// a free-standing one and not an unused flag/option. /// /// Sadly, there is no way to automatically check for flag/option. /// `-`, `--`, `-1`, `-0.5`, `--.txt` - all of this arguments can have different /// meaning depending on the caller requirements. /// /// Must be used only once for each argument. /// /// # Errors /// /// - When argument is not a UTF-8 string. Use [`free_from_os_str`] instead. /// - When argument parsing failed. /// - When argument is not present. /// /// [`free_from_os_str`]: struct.Arguments.html#method.free_from_os_str #[inline(never)] pub fn free_from_fn( &mut self, f: fn(&str) -> Result, ) -> Result { self.opt_free_from_fn(f)?.ok_or(Error::MissingArgument) } /// Parses a free-standing argument using a specified function. /// /// The same as [`free_from_fn`], but parses `&OsStr` instead of `&str`. /// /// [`free_from_fn`]: struct.Arguments.html#method.free_from_fn #[inline(never)] pub fn free_from_os_str( &mut self, f: fn(&OsStr) -> Result, ) -> Result { self.opt_free_from_os_str(f)?.ok_or(Error::MissingArgument) } /// Parses an optional free-standing argument using `FromStr` trait. /// /// The same as [`free_from_str`], but returns `Ok(None)` when argument is not present. /// /// [`free_from_str`]: struct.Arguments.html#method.free_from_str pub fn opt_free_from_str(&mut self) -> Result, Error> where T: FromStr, ::Err: Display, { self.opt_free_from_fn(FromStr::from_str) } /// Parses an optional free-standing argument using a specified function. /// /// The same as [`free_from_fn`], but returns `Ok(None)` when argument is not present. /// /// [`free_from_fn`]: struct.Arguments.html#method.free_from_fn #[inline(never)] pub fn opt_free_from_fn( &mut self, f: fn(&str) -> Result, ) -> Result, Error> { if self.0.is_empty() { Ok(None) } else { let value = self.0.remove(0); let value = os_to_str(value.as_os_str())?; match f(&value) { Ok(value) => Ok(Some(value)), Err(e) => Err(Error::Utf8ArgumentParsingFailed { value: value.to_string(), cause: error_to_string(e), }), } } } /// Parses a free-standing argument using a specified function. /// /// The same as [`free_from_os_str`], but returns `Ok(None)` when argument is not present. /// /// [`free_from_os_str`]: struct.Arguments.html#method.free_from_os_str #[inline(never)] pub fn opt_free_from_os_str( &mut self, f: fn(&OsStr) -> Result, ) -> Result, Error> { if self.0.is_empty() { Ok(None) } else { let value = self.0.remove(0); match f(value.as_os_str()) { Ok(value) => Ok(Some(value)), Err(e) => Err(Error::ArgumentParsingFailed { cause: error_to_string(e) }), } } } /// Returns a list of remaining arguments. /// /// It's up to the caller what to do with them. /// One can report an error about unused arguments, /// other can use them for further processing. pub fn finish(self) -> Vec { self.0 } } // Display::to_string() is usually inlined, so by wrapping it in a non-inlined // function we are reducing the size a bit. #[inline(never)] fn error_to_string(e: E) -> String { e.to_string() } #[cfg(feature = "eq-separator")] #[inline(never)] fn starts_with_plus_eq(text: &OsStr, prefix: &str) -> bool { if let Some(s) = text.to_str() { if s.get(0..prefix.len()) == Some(prefix) { if s.as_bytes().get(prefix.len()) == Some(&b'=') { return true; } } } false } #[cfg(feature = "short-space-opt")] #[inline(never)] fn starts_with_short_prefix(text: &OsStr, prefix: &str) -> bool { if prefix.starts_with("--") { return false; // Only works for short keys } if let Some(s) = text.to_str() { if s.get(0..prefix.len()) == Some(prefix) { return true; } } false } #[cfg(all(feature = "eq-separator", feature = "short-space-opt"))] #[inline] fn index_predicate(text: &OsStr, prefix: &str) -> bool { starts_with_plus_eq(text, prefix) || starts_with_short_prefix(text, prefix) } #[cfg(all(feature = "eq-separator", not(feature = "short-space-opt")))] #[inline] fn index_predicate(text: &OsStr, prefix: &str) -> bool { starts_with_plus_eq(text, prefix) } #[cfg(all(feature = "short-space-opt", not(feature = "eq-separator")))] #[inline] fn index_predicate(text: &OsStr, prefix: &str) -> bool { starts_with_short_prefix(text, prefix) } #[cfg(any(feature = "eq-separator", feature = "short-space-opt"))] #[inline] fn ends_with(text: &str, c: u8) -> bool { if text.is_empty() { false } else { text.as_bytes()[text.len() - 1] == c } } #[inline] fn os_to_str(text: &OsStr) -> Result<&str, Error> { text.to_str().ok_or_else(|| Error::NonUtf8Argument) } /// A keys container. /// /// Should not be used directly. #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct Keys([&'static str; 2]); impl Keys { #[inline] fn first(&self) -> &'static str { self.0[0] } #[inline] fn second(&self) -> &'static str { self.0[1] } } impl From<[&'static str; 2]> for Keys { #[inline] fn from(v: [&'static str; 2]) -> Self { debug_assert!(v[0].starts_with("-"), "an argument should start with '-'"); validate_shortflag(v[0]); debug_assert!( !v[0].starts_with("--"), "the first argument should be short" ); debug_assert!(v[1].starts_with("--"), "the second argument should be long"); Keys(v) } } fn validate_shortflag(short_key: &'static str) { let mut chars = short_key[1..].chars(); if let Some(first) = chars.next() { debug_assert!(short_key.len() == 2 || chars.all(|c| c == first), "short keys should be a single character or a repeated character"); } } impl From<&'static str> for Keys { #[inline] fn from(v: &'static str) -> Self { debug_assert!(v.starts_with("-"), "an argument should start with '-'"); if !v.starts_with("--") { validate_shortflag(v); } Keys([v, ""]) } } pico-args-0.5.0/tests/tests.rs000064400000000000000000000355710072674642500144270ustar 00000000000000use std::str::FromStr; use std::ffi::OsString; use pico_args::*; fn to_vec(args: &[&str]) -> Vec { args.iter().map(|s| s.to_string().into()).collect() } #[test] fn no_args() { let _ = Arguments::from_vec(to_vec(&[])); } #[test] fn single_short_contains() { let mut args = Arguments::from_vec(to_vec(&["-V"])); assert!(args.contains("-V")); } #[test] fn single_long_contains() { let mut args = Arguments::from_vec(to_vec(&["--version"])); assert!(args.contains("--version")); } #[test] fn contains_two_01() { let mut args = Arguments::from_vec(to_vec(&["--version"])); assert!(args.contains(["-v", "--version"])); } #[test] fn contains_two_02() { let mut args = Arguments::from_vec(to_vec(&["-v"])); assert!(args.contains(["-v", "--version"])); } #[test] fn contains_two_03() { let mut args = Arguments::from_vec(to_vec(&["-v", "--version"])); assert!(args.contains(["-v", "--version"])); } #[test] #[should_panic] fn invalid_flag_01() { let mut args = Arguments::from_vec(to_vec(&["-v", "--version"])); assert!(args.contains("v")); } #[cfg(debug_assertions)] #[test] #[should_panic] fn invalid_flag_02() { let mut args = Arguments::from_vec(to_vec(&["-v", "--version"])); assert!(args.contains(["v", "--version"])); } #[cfg(debug_assertions)] #[test] #[should_panic] fn invalid_flag_03() { let mut args = Arguments::from_vec(to_vec(&["-v", "--version"])); assert!(args.contains(["-v", "-version"])); } #[cfg(debug_assertions)] #[test] #[should_panic] fn invalid_flag_04() { let mut args = Arguments::from_vec(to_vec(&["-v", "--version"])); assert!(args.contains(["-v", "version"])); } #[test] fn option_01() { let mut args = Arguments::from_vec(to_vec(&["-w", "10"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), 10); } #[test] fn option_02() { let mut args = Arguments::from_vec(to_vec(&["--width", "10"])); let value: Option = args.opt_value_from_str("--width").unwrap(); assert_eq!(value.unwrap(), 10); } #[test] fn option_03() { let mut args = Arguments::from_vec(to_vec(&["--name", "test"])); let value: Option = args.opt_value_from_str("--name").unwrap(); assert_eq!(value.unwrap(), "test"); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_01() { let mut args = Arguments::from_vec(to_vec(&["-w=10"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_02() { let mut args = Arguments::from_vec(to_vec(&["-w='10'"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_03() { let mut args = Arguments::from_vec(to_vec(&["-w=\"10\""])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_04() { let mut args = Arguments::from_vec(to_vec(&["--width2=15", "--width=10"])); let value: Option = args.opt_value_from_str("--width").unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_01() { let mut args = Arguments::from_vec(to_vec(&["-w="])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option doesn't have an associated value"); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_02() { let mut args = Arguments::from_vec(to_vec(&["-w='"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option doesn't have an associated value"); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_03() { let mut args = Arguments::from_vec(to_vec(&["-w=''"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option doesn't have an associated value"); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_04() { let mut args = Arguments::from_vec(to_vec(&["-w='\""])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option doesn't have an associated value"); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_05() { let mut args = Arguments::from_vec(to_vec(&["-w='10\""])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option doesn't have an associated value"); } #[cfg(all(feature = "eq-separator", not(feature = "short-space-opt")))] #[test] fn eq_option_err_06() { let mut args = Arguments::from_vec(to_vec(&["-w-10"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap(), None); } #[cfg(feature = "eq-separator")] #[test] fn eq_option_err_07() { let mut args = Arguments::from_vec(to_vec(&["-w=a"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "failed to parse 'a': invalid digit found in string"); } #[cfg(not(any(feature = "eq-separator", feature = "short-space-opt")))] #[test] fn no_eq_separator_01() { let mut args = Arguments::from_vec(to_vec(&["-w=a"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap(), None); } #[cfg(feature = "combined-flags")] #[test] fn combined_flags_01() { let mut args = Arguments::from_vec(to_vec(&["-ab"])); assert!(args.contains("-b")); assert!(args.contains("-a")); } #[cfg(feature = "combined-flags")] #[test] fn combined_flags_repeated_01() { let mut args = Arguments::from_vec(to_vec(&["-aa"])); assert!(args.contains("-a")); assert!(args.contains("-a")); assert!(!args.contains("-a")); } #[cfg(feature = "combined-flags")] #[test] fn combined_flags_repeated_02() { let mut args = Arguments::from_vec(to_vec(&["-aaa", "-a"])); assert!(args.contains("-aaa")); assert!(args.contains("-a")); } #[cfg(feature = "combined-flags")] #[test] fn combined_flags_leftover() { let mut args = Arguments::from_vec(to_vec(&["-ab"])); assert!(args.contains("-a")); assert_eq!(args.finish(), vec![OsString::from("-b")]); } #[test] fn long_flag_with_character_from_short_flag() { let mut args = Arguments::from_vec(to_vec(&["--version"])); assert!(!args.contains("-s")); assert!(args.contains("--version")); } #[cfg(feature = "combined-flags")] #[test] fn combined_long_flag_with_character_from_short_flag() { let mut args = Arguments::from_vec(to_vec(&["--version"])); assert!(!args.contains("-s")); assert!(args.contains("--version")); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_01() { let mut args = Arguments::from_vec(to_vec(&["-w10"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_02() { let mut args = Arguments::from_vec(to_vec(&["-w--width"])); let value: Option = args.opt_value_from_str(["-w", "--width"]).unwrap(); assert_eq!(value.unwrap(), "--width"); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_03() { let mut args = Arguments::from_vec(to_vec(&["-w'10'"])); let value: Option = args.opt_value_from_str(["-w", "--width"]).unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_04() { let mut args = Arguments::from_vec(to_vec(&["-w\"10\""])); let value: Option = args.opt_value_from_str(["-w", "--width"]).unwrap(); assert_eq!(value.unwrap(), 10); } #[cfg(all(feature = "short-space-opt", not(feature = "eq-separator")))] #[test] fn space_not_eq_option_err_01() { let mut args = Arguments::from_vec(to_vec(&["-w=10"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the \'-w\' option doesn\'t have an associated value"); } #[cfg(all(feature = "short-space-opt", not(feature = "eq-separator")))] #[test] fn space_not_eq_option_err_02() { let mut args = Arguments::from_vec(to_vec(&["--width=10"])); let value: Option = args.opt_value_from_str("--width").unwrap(); assert_eq!(value, None); } #[cfg(all(feature = "short-space-opt", feature = "eq-separator"))] #[test] fn space_eq_option_01() { let mut args = Arguments::from_vec(to_vec(&["-w=10"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), "10"); } #[cfg(all(feature = "short-space-opt", feature = "eq-separator"))] #[test] fn space_eq_option_02() { let mut args = Arguments::from_vec(to_vec(&["-w'=10'"])); let value: Option = args.opt_value_from_str("-w").unwrap(); assert_eq!(value.unwrap(), "=10"); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_err_01() { let mut args = Arguments::from_vec(to_vec(&["--width10"])); let value: Option = args.opt_value_from_str("--width").unwrap(); assert_eq!(value, None); } #[cfg(feature = "short-space-opt")] #[test] fn space_option_err_02() { let mut args = Arguments::from_vec(to_vec(&["-w'10"])); let value: Result, Error> = args.opt_value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the \'-w\' option doesn\'t have an associated value"); } #[test] fn duplicated_options_01() { let mut args = Arguments::from_vec(to_vec(&["--name", "test1", "--name", "test2"])); let value1: Option = args.opt_value_from_str("--name").unwrap(); let value2: Option = args.opt_value_from_str("--name").unwrap(); assert_eq!(value1.unwrap(), "test1"); assert_eq!(value2.unwrap(), "test2"); } #[test] fn option_from_os_str_01() { use std::path::PathBuf; fn parse_path(s: &std::ffi::OsStr) -> Result { Ok(s.into()) } let mut args = Arguments::from_vec(to_vec(&["--input", "text.txt"])); let value: Result, Error> = args.opt_value_from_os_str("--input", parse_path); assert_eq!(value.unwrap().unwrap().display().to_string(), "text.txt"); } #[test] fn missing_option_value_01() { let mut args = Arguments::from_vec(to_vec(&["--value"])); let value: Result, Error> = args.opt_value_from_str("--value"); assert_eq!(value.unwrap_err().to_string(), "the '--value' option doesn't have an associated value"); } #[test] fn missing_option_value_02() { let mut args = Arguments::from_vec(to_vec(&["--value"])); let value: Result, Error> = args.opt_value_from_str("--value"); assert!(value.is_err()); // ignore error // the `--value` flag should not be removed by the previous command assert_eq!(args.finish(), vec![OsString::from("--value")]); } #[test] fn missing_option_value_03() { let mut args = Arguments::from_vec(to_vec(&["--value", "q"])); let value: Result, Error> = args.opt_value_from_str("--value"); assert!(value.is_err()); // ignore error // the `--value` flag should not be removed by the previous command assert_eq!(args.finish(), vec![OsString::from("--value"), OsString::from("q")]); } #[test] fn multiple_options_01() { let mut args = Arguments::from_vec(to_vec(&["-w", "10", "-w", "20"])); let value: Vec = args.values_from_str("-w").unwrap(); assert_eq!(value, &[10, 20]); } #[test] fn multiple_options_02() { // No values is not an error. let mut args = Arguments::from_vec(to_vec(&[])); let value: Vec = args.values_from_str("-w").unwrap(); assert_eq!(value, &[]); } #[test] fn multiple_options_03() { // Argument can be split. let mut args = Arguments::from_vec(to_vec(&["-w", "10", "--other", "-w", "20"])); let value: Vec = args.values_from_str("-w").unwrap(); assert_eq!(value, &[10, 20]); } #[test] fn free_from_str_01() { let mut args = Arguments::from_vec(to_vec(&["5"])); let value: u32 = args.free_from_str().unwrap(); assert_eq!(value, 5); } #[test] fn opt_free_from_fn_01() { let mut args = Arguments::from_vec(to_vec(&["5"])); assert_eq!(args.opt_free_from_fn(u32::from_str).unwrap(), Some(5)); } #[test] fn opt_free_from_fn_02() { let mut args = Arguments::from_vec(to_vec(&[])); assert_eq!(args.opt_free_from_fn(u32::from_str).unwrap(), None); } #[test] fn opt_free_from_fn_03() { let mut args = Arguments::from_vec(to_vec(&["-h"])); assert_eq!(args.opt_free_from_fn(u32::from_str).unwrap_err().to_string(), "failed to parse '-h': invalid digit found in string"); } #[test] fn opt_free_from_fn_04() { let mut args = Arguments::from_vec(to_vec(&["a"])); assert_eq!(args.opt_free_from_fn(u32::from_str).unwrap_err().to_string(), "failed to parse 'a': invalid digit found in string"); } #[test] fn opt_free_from_fn_05() { let mut args = Arguments::from_vec(to_vec(&["-5"])); assert_eq!(args.opt_free_from_fn(i32::from_str).unwrap(), Some(-5)); } #[test] fn opt_free_from_fn_06() { let mut args = Arguments::from_vec(to_vec(&["-3.14"])); assert_eq!(args.opt_free_from_fn(f32::from_str).unwrap(), Some(-3.14f32)); } #[test] fn opt_free_from_str_01() { let mut args = Arguments::from_vec(to_vec(&["5"])); let value: Result, Error> = args.opt_free_from_str(); assert_eq!(value.unwrap(), Some(5)); } #[test] fn required_option_01() { let mut args = Arguments::from_vec(to_vec(&["--width", "10"])); let value: u32 = args.value_from_str("--width").unwrap(); assert_eq!(value, 10); } #[test] fn missing_required_option_01() { let mut args = Arguments::from_vec(to_vec(&[])); let value: Result = args.value_from_str("-w"); assert_eq!(value.unwrap_err().to_string(), "the '-w' option must be set"); } #[test] fn missing_required_option_02() { let mut args = Arguments::from_vec(to_vec(&[])); let value: Result = args.value_from_str("--width"); assert_eq!(value.unwrap_err().to_string(), "the '--width' option must be set"); } #[test] fn missing_required_option_03() { let mut args = Arguments::from_vec(to_vec(&[])); let value: Result = args.value_from_str(["-w", "--width"]); assert_eq!(value.unwrap_err().to_string(), "the '-w/--width' option must be set"); } #[test] fn subcommand() { let mut args = Arguments::from_vec(to_vec(&["toolchain", "install", "--help"])); let cmd = args.subcommand().unwrap(); assert_eq!(cmd, Some("toolchain".to_string())); let cmd = args.subcommand().unwrap(); assert_eq!(cmd, Some("install".to_string())); let cmd = args.subcommand().unwrap(); assert_eq!(cmd, None); }