Crate bpaf

Source
Expand description

Lightweight and flexible command line argument parser with derive and combinatoric style API

  • Introduction - features, design goals, restrictions
  • Tutorials - practical learning oriented information and examples to get you started
  • How-to and guides - assumes familiarity with the basics and explains how to concrete tasks
  • Explanations - theoretical information about abstractions used by the library, oriented for understanding
  • FAQ - questions from library users

§A quick start

Add bpaf, optionally with derive enabled

$ cargo add bpaf -F derive,dull_color

Use either derive or combinatoric API and try running it

Combinatoric example
use bpaf::*;

#[derive(Debug, Clone)]
pub struct Options {
    message: String,
}

pub fn options() -> OptionParser<Options> {
    let message = positional("MESSAGE").help("Message to print in a big friendly letters");
    construct!(Options { message }).to_options()
}

fn main() {
    println!("{:?}", options().run())
}
Derive example
use bpaf::*;

#[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
pub struct Options {
    /// Message to print in a big friendly letters
    #[bpaf(positional("MESSAGE"))]
    message: String,
}

fn main() {
    println!("{:?}", options().run())
}
Output

With everything in place users should be able to pass their arguments

$ app "Hello world"
Options { message: "Hello world" }

As well as read the help message generated by the library

$ app --help

Usage: app MESSAGE

Available positional items:
MESSAGE
Message to print in a big friendly letters

Available options:
-h, --help
Prints help information

§Consuming items - making Parser

bpaf allows you to describe the parsers using a mix of two APIs: combinatoric and derive. Both APIs can achieve the same results, you can use one that better suits your needs. You can find documentation with more examples following those links.

  • For an argument with a name you define NamedArg using a combination of short, long and env. At the same time you can attach help.
  • NamedArg::switch - simple switch that returns true if it’s present on a command line and false otherwise.
  • NamedArg::flag - a variant of switch that lets you return one of two custom values, for example Color::On and Color::Off.
  • NamedArg::req_flag - a variant of switch that only only succeeds when it’s name is present on a command line
  • NamedArg::argument - named argument containing a value, you can further customize it with adjacent
  • positional - positional argument, you can further customize it with strict
  • OptionParser::command - subcommand parser.
  • any and its specialized version literal are escape hatches that can parse anything not fitting into usual classification.
  • pure and pure_with - a way to generate a value that can be composed without parsing it from the command line.

§Transforming and changing parsers

By default primitive parsers gives you back a single bool, a single PathBuf or a single value produced by FromStr trait, etc. You can further transform it by chaining methods from Parser trait, some of those methods are applied automagically if you are using derive API.

bpaf distinguishes two types of parse failures - “value is absent” and “value is present but invalid”, most parsers listed in this section only handle the first type of failure by default, but you can use their respective catch method to handle the later one.

§Combining multiple parsers together

Once you have parsers for all the primitive fields figured out you can start combining them together to produce a parser for a final result - data type you designed in the step one. For derive API you apply annotations to data types with #[derive(Bpaf)] and #[bpaf(..)], with combinatoric API you use construct! macro.

All fields in a struct needs to be successfully parsed in order for the parser to succeed and only one variant from enum will consume its values at a time.

You can use adjacent annotation to parse multiple flags as an adjacent group allowing for more unusual scenarios such as multiple value arguments or chained commands.

§Improving user experience

bpaf would use doc comments on fields and structures in derive mode and and values passed in various help methods to generate --help documentation, you can further improve it using those methods:

  • hide_usage and hide - hide the parser from generated Usage line or whole generated help
  • group_help and with_group_help - add a common description shared by several parsers
  • custom_usage - customize usage for a primitive or composite parser
  • usage and with_usage lets you to customize whole usage line as a whole either by completely overriding it or by building around it.

By default with completion enabled bpaf would complete names for flags, arguments and commands. You can also generate completion for argument values, possible positionals, etc. This requires enabling autocomplete cargo feature.

And finally you can generate documentation for command line in markdown, html and manpage formats using render_markdown, render_html and render_manpage, for more detailed info see doc module

§Testing your parsers and running them

§Cargo features

  • derive: adds a dependency on bpaf_derive crate and reexport Bpaf derive macro. You need to enable it to use derive API. Disabled by default.

  • batteries: helpers implemented with public bpaf API. Disabled by default.

  • autocomplete: enables support for shell autocompletion. Disabled by default.

  • bright-color, dull-color: use more colors when printing --help and such. Enabling either color feature adds some extra dependencies and might raise MRSV. If you are planning to use this feature in a published app - it’s best to expose them as feature flags:

    [features]
    bright-color = ["bpaf/bright-color"]
    dull-color = ["bpaf/dull-color"]

    Disabled by default.

  • docgen: generate documentation from help declaration, see OptionParser::render_markdown and doc. Disabled by default.

Modules§

_documentationextradocs
Project documentation
batteriesbatteries
Batteries included - helpful parsers that use only public API
doc
Documentation generation system
params
Tools to define primitive parsers
parsers
This module exposes parsers that accept further configuration with builder pattern

Macros§

construct
Compose several parsers to produce a single result

Structs§

Args
All currently present command line parameters with some extra metainfo
Doc
String with styled segments.
OptionParser
Ready to run Parser with additional information attached

Enums§

ParseFailure
Unsuccessful command line parsing outcome, use it for unit tests
ShellCompautocomplete
Shell specific completion

Traits§

Parser
Simple or composed argument parser

Functions§

any
Parse a single arbitrary item from a command line
choice
Choose between several parsers specified at runtime
env
Parse an environment variable
fail
Fail with a fixed error message
literal
A specialized version of any that consumes an arbitrary string
long
Parse a flag/switch/argument that has a long name
positional
Parse a positional argument
pure
Parser that produces a fixed value
pure_with
Wrap a calculated value into a Parser
short
Parse a flag/switch/argument that has a short name

Derive Macros§

Bpafbpaf_derive
Derive macro for bpaf command line parser