Expand description
This crate is a library to parse command line arguments.
This crate provides the following functionalities:
- Supports POSIX & GNU like short and long options.
- This crate supports
--
option. - This library doesn’t support numeric short option.
- This library supports not
-ofoo
but-o=foo
as an alternative to-o foo
for short option.
- This crate supports
§Install
In Cargo.toml
, write this crate as a dependency.
[dependencies]
cliargs = "0.2.0"
§Usage
This crate provides the Cmd
strcut to parse command line arguments.
The usage of this Cmd
struct is as follows:
§Creates a Cmd
instance
The Cmd::new
function creates a Cmd
instance with original command line
arguments.
This function uses std::env::arg_os
and OsString#into_string
to read
command line arguments in order to avoid panic!
call that the user cannot
control.
use cliargs::Cmd;
use cliargs::errors::InvalidOsArg;
let cmd = match Cmd::new() {
Ok(cmd) => cmd,
Err(InvalidOsArg::OsArgsContainInvalidUnicode { index, os_arg }) => {
panic!("Invalid Unicode data: {:?} (index: {})", os_arg, index);
}
};
§Creates a Cmd
instance with the specified String
array
The Cmd::with_strings
function creates a Cmd
instance with the
specified String
array.
use cliargs::Cmd;
use std::env;
let cmd = Cmd::with_strings(env::args());
§Creates a Cmd
instance with the specified OsString
array.
use cliargs::Cmd;
use cliargs::errors::InvalidOsArg;
use std::env;
let cmd = match Cmd::with_os_strings(env::args_os()) {
Ok(cmd) => cmd,
Err(InvalidOsArg::OsArgsContainInvalidUnicode { index, os_arg }) => {
panic!("Invalid Unicode data: {:?} (index: {})", os_arg, index);
}
};
§Parses without configurations
The Cmd
struct has the method which parses command line arguments without
configurations.
This method automatically divides command line arguments to options and
command arguments.
Command line arguments starts with -
or --
are options, and others are
command arguments.
If you want to specify a value to an option, follows "="
and the value
after the option, like foo=123
.
All command line arguments after --
are command arguments, even they
starts with -
or --
.
use cliargs::Cmd;
use cliargs::errors::InvalidOption;
let mut cmd = Cmd::with_strings(vec![ /* ... */ ]);
match cmd.parse() {
Ok(_) => { /* ... */ },
Err(InvalidOption::OptionContainsInvalidChar { option }) => {
panic!("Option contains invalid character: {option}");
},
Err(err) => panic!("Invalid option: {}", err.option()),
}
Modules§
- Enums for errors that can occur when parsing command line arguments.
Structs§
- Parses command line arguments and stores them.
- Represents an option configuration for how to parse command line arguments.
Enums§
- Enables to create a
OptCfg
instance in a manner similar to named parameters.