Tuesday, January 27, 2009

Option parsing and documentation

After all this time programming, I am still dissatisfied with every command-line-option parsing and processing module/api/method available.

I've tried dozens in Perl, a handful in Python, a smattering in C, several in Java, and all fail to satisfy me in one or more ways.

The thing I find most dissatisfying is the API and usage of these option parsers. After that it's the ability (or lack thereof) to declare documentation and usage info in the same place where you define your option processing. After that, it's just that nothing seems to have all the features I want in one place.

I won't go into a tirade about everything I've tried and which system has what features and how awful or great each one is... I'll just work on explaining what I think would make up an ideal option parser and then try to lay out some ideas for API and/or implementation.

Example of usage of an option parser I'd like:

my $opt_parser = OptParser->new();
$opt_parser->add_option(
name => "foo" # name used to refer to this option
short => "f" # use as -f
long => "foo" # use as --foo
depends => "bar|baz" # option only valid if bar or baz is specified. using
# an array to list depends may be simpler... or not
conflicts => "buh" # option conflicts with option buh.
required => "yes" # option is required (if depends are specified, only
# check after depends passes)
type => "string" # data type (string|flag)
default => "wibble" # default value if none specified
help => "..." # text to show when -h is used to display help
error => "..." # text to show if option does not validate
multi => "no" # allow option to be specified multiple times
# (no|yes|group)
group => "fuh" # When showing help, group this option with others
# who are assigned to group fuh
validate => \&sub # ref to a sub that can validate the option
after => [qw(baz)] # only validate *after* baz
);
# Sometimes in the help, usage and docs you want certain options to be
# grouped together. You may also want to apply validation to all the
# options in a group together.
$opt_parser->add_group(
name => "fuh" # name of the option group
validate => \&sub # ref to a sub that can validate all the
# options in the group
help => "..." # text describing the group when displaying help
members => [qw(foo baz)] # options belonging to this group.
);
view raw gistfile1.pl hosted with ❤ by GitHub


Presumably, this module would automagically generate --help output, usage docs, do basic error checking, and even output a man page or HTML or POD.