Module: DocoptNG

Defined in:
lib/docopt_ng.rb,
lib/docopt_ng/either.rb,
lib/docopt_ng/option.rb,
lib/docopt_ng/command.rb,
lib/docopt_ng/pattern.rb,
lib/docopt_ng/version.rb,
lib/docopt_ng/argument.rb,
lib/docopt_ng/optional.rb,
lib/docopt_ng/required.rb,
lib/docopt_ng/exceptions.rb,
lib/docopt_ng/any_options.rb,
lib/docopt_ng/one_or_more.rb,
lib/docopt_ng/token_stream.rb,
lib/docopt_ng/child_pattern.rb,
lib/docopt_ng/parent_pattern.rb

Defined Under Namespace

Classes: AnyOptions, Argument, ChildPattern, Command, DocoptLanguageError, Either, Exit, OneOrMore, Option, Optional, ParentPattern, Pattern, Required, TokenStream

Constant Summary collapse

VERSION =
'0.7.1'

Class Method Summary collapse

Class Method Details

.docopt(doc, params = {}) ⇒ Object

Raises:



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/docopt_ng.rb', line 265

def docopt(doc, params = {})
  default = { version: nil, argv: nil, help: true, options_first: false }
  params = default.merge(params)
  params[:argv] = ARGV unless params[:argv]

  Exit.usage = printable_usage(doc)
  options = parse_defaults(doc)
  pattern = parse_pattern(formal_usage(Exit.usage), options)
  argv = parse_argv(TokenStream.new(params[:argv], Exit), options, params[:options_first])
  pattern_options = pattern.flat(Option).uniq
  pattern.flat(AnyOptions).each do |ao|
    doc_options = parse_defaults(doc)
    ao.children = doc_options.reject { |o| pattern_options.include?(o) }.uniq
  end
  extras(params[:help], params[:version], argv, doc)

  matched, left, collected = pattern.fix.match(argv)
  collected ||= []

  if matched && left.count.zero?
    return (pattern.flat + collected).to_h { |a| [a.name, a.value] }
  end

  raise Exit.new
end

.dump_patterns(pattern, indent = 0) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/docopt_ng.rb', line 226

def dump_patterns(pattern, indent = 0)
  ws = ' ' * 4 * indent
  out = ''
  if pattern.instance_of?(Array)
    if pattern.count.positive?
      out << ws << "[\n"
      pattern.each do |p|
        out << dump_patterns(p, indent + 1).rstrip << "\n"
      end
      out << ws << "]\n"
    else
      out << ws << "[]\n"
    end

  elsif pattern.class.ancestors.include?(ParentPattern)
    out << ws << pattern.class.name << "(\n"
    pattern.children.each do |p|
      out << dump_patterns(p, indent + 1).rstrip << "\n"
    end
    out << ws << ")\n"

  else
    out << ws << pattern.inspect
  end
  out
end

.extras(help, version, options, doc) ⇒ Object

Raises:

  • (Exit.new(exit_code: 0))


253
254
255
256
257
258
259
260
261
262
263
# File 'lib/docopt_ng.rb', line 253

def extras(help, version, options, doc)
  help_flags = ['-h', '--help']
  if help && options.any? { |o| help_flags.include?(o.name) && o.value }
    Exit.usage = nil
    raise Exit.new(exit_code: 0), doc.strip
  end
  return unless version && options.any? { |o| o.name == '--version' && o.value }

  Exit.usage = nil
  raise Exit.new(exit_code: 0), version
end

.formal_usage(printable_usage) ⇒ Object



216
217
218
219
220
221
222
223
224
# File 'lib/docopt_ng.rb', line 216

def formal_usage(printable_usage)
  pu = printable_usage[/usage:(.*)/mi, 1]

  lines = pu.lines(chomp: true).reject(&:empty?).map do |a|
    "( #{a.split.drop(1).join(' ')} )"
  end

  lines.join ' | '
end

.parse_argv(tokens, options, options_first = false) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/docopt_ng.rb', line 182

def parse_argv(tokens, options, options_first = false)
  parsed = []
  until tokens.current.nil?
    if tokens.current == '--' || options_first
      return parsed + tokens.map { |v| Argument.new(nil, v) }
    elsif tokens.current.start_with?('--')
      parsed += parse_long(tokens, options)
    elsif tokens.current.start_with?('-') && (tokens.current != '-')
      parsed += parse_shorts(tokens, options)
    else
      parsed << Argument.new(nil, tokens.move)
    end
  end
  parsed
end

.parse_atom(tokens, options) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/docopt_ng.rb', line 148

def parse_atom(tokens, options)
  token = tokens.current

  if ['(', '['].include? token
    tokens.move
    if token == '('
      matching = ')'
      pattern = Required
    else
      matching = ']'
      pattern = Optional
    end

    result = pattern.new(*parse_expr(tokens, options))

    if tokens.move != matching
      raise tokens.error, "unmatched '#{token}'"
    end

    [result]
  elsif token == 'options'
    tokens.move
    [AnyOptions.new]
  elsif token.start_with?('--') && (token != '--')
    parse_long(tokens, options)
  elsif token.start_with?('-') && !['-', '--'].include?(token)
    parse_shorts(tokens, options)
  elsif (token.start_with?('<') && token.end_with?('>')) || (token.upcase == token && token.match(/[A-Z]/))
    [Argument.new(tokens.move)]
  else
    [Command.new(tokens.move)]
  end
end

.parse_defaults(doc) ⇒ Object



198
199
200
201
202
# File 'lib/docopt_ng.rb', line 198

def parse_defaults(doc)
  split = doc.split(/^ *(<\S+?>|-\S+?)/).drop(1)
  split = split.each_slice(2).select { |pair| pair.count == 2 }.map { |s1, s2| s1 + s2 }
  split.select { |s| s.start_with?('-') }.map { |s| Option.parse(s) }
end

.parse_expr(tokens, options) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/docopt_ng.rb', line 118

def parse_expr(tokens, options)
  seq = parse_seq(tokens, options)
  if tokens.current != '|'
    return seq
  end

  result = seq.count > 1 ? [Required.new(*seq)] : seq

  while tokens.current == '|'
    tokens.move
    seq = parse_seq(tokens, options)
    result += seq.count > 1 ? [Required.new(*seq)] : seq
  end
  result.count > 1 ? [Either.new(*result)] : result
end

.parse_long(tokens, options) ⇒ Object

Raises:

  • (RuntimeError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/docopt_ng.rb', line 18

def parse_long(tokens, options)
  long, eq, value = tokens.move.partition('=')

  raise RuntimeError unless long.start_with?('--')

  value = nil if (eq == value) && (eq == '')
  similar = options.select { |o| o.long and o.long == long }

  if (tokens.error == Exit) && (similar == [])
    similar = options.select { |o| o.long and o.long.start_with?(long) }
  end

  if similar.count > 1
    ostr = similar.map(&:long).join(', ')
    raise tokens.error, "#{long} is not a unique prefix: #{ostr}?"
  elsif similar.count < 1
    argcount = (eq == '=' ? 1 : 0)
    o = Option.new(nil, long, argcount)
    options << o
    if tokens.error == Exit
      o = Option.new(nil, long, argcount, (argcount == 1 ? value : true))
    end
  else
    s0 = similar[0]
    o = Option.new(s0.short, s0.long, s0.argcount, s0.value)
    if o.argcount.zero?
      unless value.nil?
        raise tokens.error, "#{o.long} must not have an argument"
      end
    elsif value.nil?
      if tokens.current.nil?
        raise tokens.error, "#{o.long} requires argument"
      end

      value = tokens.move
    end
    if tokens.error == Exit
      o.value = (value.nil? ? true : value)
    end
  end
  [o]
end

.parse_pattern(source, options) ⇒ Object



107
108
109
110
111
112
113
114
115
116
# File 'lib/docopt_ng.rb', line 107

def parse_pattern(source, options)
  tokens = TokenStream.new(source.gsub(/([\[\]()|]|\.\.\.)/, ' \1 '), DocoptLanguageError)

  result = parse_expr(tokens, options)
  unless tokens.current.nil?
    raise tokens.error, "unexpected ending: #{tokens.join(' ')}"
  end

  Required.new(*result)
end

.parse_seq(tokens, options) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/docopt_ng.rb', line 134

def parse_seq(tokens, options)
  result = []
  stop = [nil, ']', ')', '|']
  until stop.include?(tokens.current)
    atom = parse_atom(tokens, options)
    if tokens.current == '...'
      atom = [OneOrMore.new(*atom)]
      tokens.move
    end
    result += atom
  end
  result
end

.parse_shorts(tokens, options) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/docopt_ng.rb', line 61

def parse_shorts(tokens, options)
  token = tokens.move
  unless token.start_with?('-') && !token.start_with?('--')
    raise RuntimeError
  end

  left = token[1..]
  parsed = []
  while left != ''
    short = "-#{left[0]}"
    left = left[1..]
    similar = options.select { |o| o.short == short }
    if similar.count > 1
      raise tokens.error, "#{short} is specified ambiguously #{similar.count} times"
    elsif similar.count < 1
      o = Option.new(short, nil, 0)
      options << o
      if tokens.error == Exit
        o = Option.new(short, nil, 0, true)
      end
    else
      s0 = similar[0]
      o = Option.new(short, s0.long, s0.argcount, s0.value)
      value = nil
      if o.argcount != 0
        if left == ''
          if tokens.current.nil?
            raise tokens.error, "#{short} requires argument"
          end

          value = tokens.move
        else
          value = left
          left = ''
        end
      end
      if tokens.error == Exit
        o.value = (value.nil? ? true : value)
      end
    end

    parsed << o
  end
  parsed
end

.printable_usage(doc) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
# File 'lib/docopt_ng.rb', line 204

def printable_usage(doc)
  usage_split = doc.split(/([Uu][Ss][Aa][Gg][Ee]:)/)
  if usage_split.count < 3
    raise DocoptLanguageError, '"usage:" (case-insensitive) not found.'
  end
  if usage_split.count > 3
    raise DocoptLanguageError, 'More than one "usage:" (case-insensitive).'
  end

  usage_split.drop(1).join.split(/\n\s*\n/)[0].strip
end