Skip to main content

argparse

Macro argparse 

Source
macro_rules! argparse {
    (
        $( #[$meta:meta] )*
        $vis:vis struct $name:ident {
            $( ($field:ident, $type:ty, $sho:expr, $lon:expr, $has:expr, $desc:expr $(, @$special:ident)? ) ),* $(,)?
        }
    ) => { ... };
}
Expand description

argparse macro

This macro provides a convenient way to define command line options, a configuration struct, and a parser at once. It automatically generates the required sorted tables and parsing logic.

For large-scale projects with a massive number of options (e.g., hundreds of flags), it is recommended to continue using flood-tide-gen to keep your source code clean and maintain the definitions in external files.

ยงExamples

use flood_tide::{argparse, Arg, HelpVersion};

argparse! {
    pub struct MyConf {
        // (field_name, type, short_char, long_name, has_arg, description, [@special])
        (help,    bool, b'h', "help",    Arg::No,  "display help", @help),
        (version, bool, b'V', "version", Arg::No,  "display version", @version),
        (verbose, bool, b'v', "verbose", Arg::No,  "verbose mode"),
        (count,   u32,  b'c', "count",   Arg::Yes, "count value"),
        (name,    String, b'n', "name",  Arg::Yes, "name value"),
    }
}

fn main() {
    #[cfg(any(feature = "stop_at_mm", feature = "dox"))]
    {
        #[cfg(any(feature = "option_argument", feature = "dox"))]
        #[cfg(not(feature = "long_only"))]
        let args = ["-vv", "--count=42", "-n", "foo", "extra"];
        #[cfg(any(feature = "option_argument", feature = "dox"))]
        #[cfg(feature = "long_only")]
        let args = ["-v", "-v", "-count=42", "-n", "foo", "extra"];

        #[cfg(not(any(feature = "option_argument", feature = "dox")))]
        #[cfg(not(feature = "long_only"))]
        let args = ["-vv", "extra"];
        #[cfg(not(any(feature = "option_argument", feature = "dox")))]
        #[cfg(feature = "long_only")]
        let args = ["-v", "-v", "extra"];

        let conf = MyConf::parse(&args).unwrap();

        if conf.is_help() {
            // print help...
            return;
        }

        assert!(conf.verbose);
        #[cfg(any(feature = "option_argument", feature = "dox"))]
        {
            assert_eq!(conf.count, 42);
            assert_eq!(conf.name, "foo");
        }
        assert_eq!(conf.arg_params, vec!["extra".to_string()]);
    }
}