Class: Pargser

Inherits:
Object
  • Object
show all
Defined in:
lib/pargser.rb

Overview

The Ruby-Style (e,g, nice and laconic) command line parser that easily supports:

  • –keys optional keys with any number of aliases aliases

  • -name value key that wants value (next agrument), optionally with default value

  • – no more keys past double dash

and regular (all other) arguments.

Also supports automatic documentation generation

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.2"

Instance Method Summary collapse

Constructor Details

#initialize(args = []) ⇒ Pargser

Create parser instance with a list of arguments. Otherwise, arguments can be passed to #parse call.

Parameters:

  • args (Array) (defaults to: [])

    optional command line arguments. Usually it is more convenient to pass them to #parse



33
34
35
36
37
38
# File 'lib/pargser.rb', line 33

def initialize args=[]
  @args     = args
  @keys     = {}
  @required = Set.new
  @docs     = []
end

Instance Method Details

#key(name, *aliases, needs_value: false, doc: nil, **kwargs) { ... } ⇒ Pargser

Register a new key handler. When #parse fonds a key (or an alias) the blocks will be called. Invocation order is same as in the command line.

Parameters:

  • name (String)

    key name

  • aliases (Array(String))

    any number of aliases for the key

  • needs_value (Boolean) (defaults to: false)

    if set then the parser wants a value argument after the key which will be passed to block as an argument. if default param is not set and the key will not be detected, Pargser::Error will be raised

  • default (String)

    default value. if set, needs_value parameter can be omitted - the handler block will be invoked with either this value or with one from args.

  • doc (String) (defaults to: nil)

    optional documentation string that will be used in #keys_doc

Yields:

  • block if the key is found with optional value argument

Returns:



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pargser.rb', line 60

def key name, *aliases, needs_value: false, doc: nil, ** kwargs, &block
  k = name.to_s

  default_set = false
  default = nil
  if kwargs.include?(:default)
    default = kwargs[:default]
    needs_value = true
    default_set = true
  end

  @keys.include?(k) and raise Error, "Duplicate key registration #{k}"
  data = @keys[k] = OpenStruct.new required:    false,
                                   needs_value: needs_value,
                                   block:       block,
                                   doc:         doc,
                                   key:         k,
                                   aliases:     aliases,
                                   default:     default,
                                   default_set: default_set
  @docs << data
  aliases.each { |a| @keys[a.to_s] = data }
  @required.add(data) if needs_value
  self
end

#keys_docObject

Generate keys documentation multiline text



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/pargser.rb', line 135

def keys_doc
  res = []
  @docs.each { |d|
    keys = [d.key] + d.aliases
    str = "\t#{keys.join(',')}"
    if d.needs_value
      str += " value"
      if d.default
        str += " (default: #{d.default})" if d.default
      else
        str += ' (optional)'
      end
    end
    res << str
    d.doc and d.doc.split("\n").each { |l| res << "\t\t#{l}" }
  }
  res.join("\n")+"\n"
end

#parse(args = nil) {|String| ... } ⇒ Array

Process command line and call key handlers in the order of appearance. Then call handlers that keys which need values and were not called and have defaults, or raise error.

The rest of arguments (non-keys) are either yielded or returned as an array.

You can optionally set other arguments than specified in constructor

Parameters:

  • args (Array(String)) (defaults to: nil)

    to parse. If specified, arguments passed to constructor will be ignored and lost

Yields:

  • (String)

    non keys arguments in order of appearance (same as returned)

Returns:

  • (Array)

    non-keys arguments (keys after ‘–’ or other arguments)



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/pargser.rb', line 99

def parse args=nil
  @args = args.clone if args
  no_more_keys = false
  rest         = []
  required_keys = @required.clone

  while !@args.empty?
    a = @args.shift
    case
      when no_more_keys
        rest << a
      when (data = @keys[a])
        required_keys.delete data
        if data.needs_value
          value = @args.shift or raise "Value needed for key #{a}"
          data.block.call value
        else
          data.block.call
        end
      when a == '--'
        no_more_keys = true
      when a[0] == '-'
        raise Error, "Unknown key #{a}"
      else
        rest << a
    end
  end
  required_keys.each { |data|
    raise Error, "Required key is missing: #{data.key}" if !data.default_set
    data.block.call data.default
  }
  block_given? and rest.each { |a| yield a }
  rest
end