module Benry::Cmdopt

Command option parser.

Usage:

## define
cmdopt = Benry::Cmdopt.new
cmdopt.add(:help   , '-h, --help'   , "print help message")
cmdopt.add(:version, '    --version', "print version")
## parse
options = cmdopt.parse(ARGV) do |err|
  $stderr.puts "ERROR: #{err.message}"
  exit(1)
end
p options     # ex: {:help => true, :version => true}
p ARGV        # options are removed from ARGV
## help
if options[:help]
  puts "Usage: foobar [<options>] [<args>...]"
  puts ""
  puts "Options:"
  puts cmdopt.option_help()
  ## or
  #format = "  %-20s : %s"
  #cmdopt.each_option_help {|opt, help| puts format % [opt, help] }
end

Command option parameter:

## required
cmdopt.add(:file, '-f, --file=<FILE>', "filename")
cmdopt.add(:file, '    --file=<FILE>', "filename")
cmdopt.add(:file, '-f <FILE>'        , "filename")
## optional
cmdopt.add(:file, '-f, --file[=<FILE>]', "filename")
cmdopt.add(:file, '    --file[=<FILE>]', "filename")
cmdopt.add(:file, '-f[<FILE>]'         , "filename")

Validation:

## type
cmdopt.add(:indent , '-i <N>', "indent width", type: Integer)
## pattern
cmdopt.add(:indent , '-i <N>', "indent width", pattern: /\A\d+\z/)
## enum
cmdopt.add(:indent , '-i <N>', "indent width", enum: [2, 4, 8])
## callback
cmdopt.add(:indent , '-i <N>', "indent width") {|val|
  val =~ /\A\d+\z/  or
    raise "integer expected."  # raise without exception class.
  val.to_i                     # convert argument value.
}

Available types:

* Integer   (`/\A[-+]?\d+\z/`)
* Float     (`/\A[-+]?(\d+\.\d*\|\.\d+)z/`)
* TrueClass (`/\A(true|on|yes|false|off|no)\z/`)
* Date      (`/\A\d\d\d\d-\d\d?-\d\d?\z/`)

Multiple parameters:

cmdopt.add(:lib , '-I <NAME>', "library name") {|optdict, key, val|
  arr = optdict[key] || []
  arr << val
  arr
}

Hidden option:

### if help string is nil, that option is removed from help message.
require 'benry/cmdopt'
cmdopt = Benry::Cmdopt.new
cmdopt.add(:verbose, '-v, --verbose', "verbose mode")
cmdopt.add(:debug  , '-d[<LEVEL>]'  , nil, type: Integer) # hidden
puts cmdopt.option_help()
### output ('-d' doesn't appear because help string is nil)
#  -v, --verbose        : verbose mode

Not supported:

* default value
* `--no-xxx` style option
* bash/zsh completion

Constants

OPTIONS_CLASS
PARAM_TYPES
PARSER_CLASS
SCHEMA_CLASS
VERSION

Public Class Methods

new() click to toggle source
# File lib/benry/cmdopt.rb, line 99
def self.new
  #; [!7kkqv] creates Facade object.
  return Facade.new
end