1 unstable release

new 0.1.0 Dec 16, 2024

#475 in Command-line interface

Download history 124/week @ 2024-12-12

124 downloads per month

MIT/Apache

590KB
15K SLoC

serde_args

GitHub Workflow Status crates.io docs.rs License

Command line argument parsing with serde.

This library allows parsing command line arguments into types implementing Deserialize.

Features

  • Help generation.
  • ANSI color support.
  • Integration with serde_derive, including attributes like serde(alias).

Usage

Basic usage of serde_args simply involves calling the from_env() function using a type implemented Deserialize. The type you provide defines your program's argument format. On success, the type is returned; on failure, a printable Error is returned.

Here is a simple example, created using serde's #[derive(Deserialize)] macro:

use serde::Deserialize;
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
#[serde(expecting = "An example program")]
struct Args {
    path: PathBuf,
    #[serde(alias = "f")]
    force: bool,
}

fn main() {
    let args = match serde_args::from_env::<Args>() {
        Ok(args) => args,
        Err(error) => {
            println!("{error}");
            return;
        }
    };
    println!("{args:?}");
}

Running the above program with no provided arguments will display the following help output:

An example program

USAGE: serde_args.exe [options] <path>

Required Arguments:
  <path>

Global Options:
  -f --force

Override Options:
  -h --help  Display this message.

Running the program with example arguments of README.md -f will show the parsed arguments:

Args { path: "README.md", force: true }

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~2MB
~29K SLoC