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.0"

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: [])

    arguments



29
30
31
32
33
34
# File 'lib/pargser.rb', line 29

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

Instance Method Details

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

Register key handler. When #parse handler blocks will be called in order of appearance in arguments array

Parameters:

  • name (String)

    key name

  • aliases (Array(String))

    for the key

  • :needs_value (Boolean)

    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)

    value. if set, needs_value parameter can be omitted - the handler block will be passed either with this value or with one specified in args.

  • :doc (String)

    optional documentation string that will be used in #keys_doc

Yields:

  • block if the key is found with optional value argument



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/pargser.rb', line 56

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



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/pargser.rb', line 131

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) (defaults to: nil)

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

Yields:

  • (String)

    non keys argumenrs (same as returned)

Returns:

  • (Array)

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



95
96
97
98
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
# File 'lib/pargser.rb', line 95

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