Expand description
§Capture the Flag
Capture the Flag is a command-line flag parsing library aimed at producing well
documented command-line interfaces with minimal boiler-plate.
Flags are defined on the command-line as key-value string pairs which are parsed
according to their key name and associated type.
Flags can have the form --key=value
or --key value
. If the flag is of type
bool
, the flag can simply use --key
, which implies --key=true
.
If specified, a flag can have a short form which begins with a single -
.
§How to use
Define a struct where each field represents a flag to parse.
The parsing code is generated by deriving the trait ctflag::Flags
.
#[derive(Flags)]
struct MyFlags {
enable_floopy: bool,
output: Option<String>,
}
Parsing the command-line arguments is done by calling the relevant methods of the
ctflag::Flags
trait.
let (flags, other_args) = MyFlags::from_args(std::env::args())?;
A description of the flags, suitable for use in a help message, can be obtained
by calling the ctflag::Flags::description()
method.
The behaviour of each flag can be changed using the #[flag(...)]
attribute.
desc = "..."
: Provides a description of the flag, displayed in the help text by thectflag::Flags::description()
method.placeholder = "..."
: Provides the text that appears in place of the flag’s value in the help text. Defaults to “VALUE”.default = ...
: For types other thanOptional
, provides a default value if the flag is not set on the command-line. This only works with type literals (bool, i64, str, etc.).short = '...'
: A short, single character alias for the flag name.
#[derive(Flags)]
struct MyFlags {
#[flag(desc = "The floopy floops the whoop")]
enable_floopy: bool,
#[flag(short = 'o', desc = "Output file", placeholder = "PATH")]
output: Option<String>,
#[flag(
desc = "How many slomps to include",
placeholder = "INTEGER",
default = 34
)]
slomps: i64,
}
The type of each field must implement the ctflag::FromArg
trait. A blanket
implementation of this trait exists for any type implementing the FromStr
trait.
// A custom type.
enum Fruit {
Apple,
Orange,
}
impl FromArg for Fruit {
fn from_arg(s: &str) -> FromArgResult<Self> {
match s {
"apple" => Ok(Fruit::Apple),
"orange" => Ok(Fruit::Orange),
_ => Err(FromArgError::with_message("bad fruit")),
}
}
}
impl Default for Fruit {
fn default() -> Self {
Fruit::Apple
}
}
#[derive(Flags)]
struct MyFlags {
fruit: Fruit,
}
Structs§
Enums§
Traits§
- Flags
- Provides a command-line argument parsing implementation when derived for a named-struct.
- FromArg
- Any type declared in a struct that derives
ctflag::Flags
must implement this trait. A blanket implementation exists for types implementingFromStr
. Custom types can implement this trait directly.