Method: CommandLine::OptionParser#parse_posix_argv

Defined in:
lib/commandline/optionparser/optionparser.rb

#parse_posix_argv(argv) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/commandline/optionparser/optionparser.rb', line 311

def parse_posix_argv(argv)
  re = @posix ? get_posix_re : Option::GENERAL_OPT_EQ_ARG_RE
  p re if $DEBUG
  tagged = []

  #
  # A Posix command line must have all the options precede
  # non option arguments. For example
  # :names => -h -e -l -p -s
  # where -p can take an argument
  # Command line can read:
  #   -helps  => -h -e -l -p s
  #   -p fred non-opt-arg
  #   -p fred non-opt-arg -h   # not ok
  #   -he -popt-arg1 -popt-arg2 non-opt-arg
  #   -p=fred  # this is not legal?
  #   -pfred  === -p fred
  #

  #"-helps" "-pfred" "-p" "fred"
  #-h -e -l -p [s] -p [fred] -p [fred]
  #[-h, []], [-e []], [-l, []], [-p, [s]], -p

  argv.each { |e| 
    m = re.match(e)
    if m.nil?
      tagged << [:arg, e]
    else
      raise "houston, we have a problem" if m.nil?
      unless m[1].empty?
        m[1].split(//).each { |e| tagged << [:opt, "-#{e}"] }
      end

      unless m[2].empty?
        tagged << [:opt, "-#{m[2]}"]
        tagged << [:arg, m[3]] unless m[3].empty?
      end
    end
  }

if $DEBUG
print "Tagged:" 
p tagged
end
  #
  # Now, combine any adjacent args such that
  #   [[:arg, "arg1"], [:arg, "arg2"]]
  # becomes
  #   [[:args, ["arg1", "arg2"]]]
  # and the final result should be
  #   [ "--file", ["arg1", "arg2"]]
  #

  parsed = []
  @args  = []
  tagged.each { |e|
    if :opt == e[0]
      parsed << [e[1], []]
    else
      if Array === parsed[-1] 
        parsed[-1][-1] += [e[1]]
      else
        @args << e[1]
      end
    end
  }
  parsed.each { |e| yield e }
end