parseOpts

parseOpts is (yes, another) ruby library for parsing commandline options and arguments.

It has the following features:

  • parses options (switches) as well as arguments

  • options and arguments are specified in an easy to read, declarative format

  • automatically generates a usage message if incorrect arguments are given

  • it is small (currently < 300 lines of code)

Description

A specification written in ruby describes the allowable command line inputs.

Individual command line parameters are divided into options and arguments.

Options are command line switches, and start with at least one ‘-’ character. They can occur in any order, and may or may not take an argument. They may occur multiple times if allowed.

Arguments are parameters that may be constrained, either as a choice of options from a list, or by a regular expression. It is possible to specificy how often an argument can occur.

All options are parsed befor any arguments. All mandatory options and arguments must be present in the command line otherwise parsing fails.

Usage

For a simple example, see the following (from examples/example_grep.rb):

require "parseOpts"
opts = ParseOpts.run do
  opt '-v|--invert-match',  'Select non-matching lines'
  opt '-m|--max-count NUM', 'Stop reading a file after NUM matches'
  arg 'pattern',            'Regular expression to match'
  arg 'file+',              'File to search in'
end
$invert_match = opts['-v']
$max_count = opts['-m'] ? opts['-m'].to_i : nil
$pattern = Regexp.new(opts['pattern'])
$files = opts['file']

Running the script with no arguments generates the following usage message:

usage: example_grep.rb options* pattern file+
Options:
  -v, --invert-match: Select non-matching lines
  -m, --max-count NUM: Stop reading a file after NUM matches
Arguments:
  pattern: Regular expression to match
  file: File to search in

Ideas for future work

  • define classes for commonly used types to parse argument strings (eg integer, float, etc)

  • format help so lines wrap nicely

  • allow sets of arguments and options in any order (allows subcommands)

Contact

Please contact jon at coppeard dot net with bug reports and suggestions.