Module: Docopt

Defined in:
lib/docopt.rb,
lib/docopt.rb

Defined Under Namespace

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

Constant Summary collapse

VERSION =
'0.5.0'

Class Method Summary collapse

Class Method Details

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

Raises:



636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/docopt.rb', line 636

def docopt(doc, params={})
  default = {:version => nil, :argv => nil, :help => true}
  params = default.merge(params)
  params[:argv] = ARGV if !params[:argv]

  Exit.set_usage(printable_usage(doc))
  options = parse_doc_options(doc)
  pattern = parse_pattern(formal_usage(Exit.usage), options)
  argv = parse_argv(params[:argv], options)
  extras(params[:help], params[:version], argv, doc)

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

  if matched and (!left or left.count == 0)
    ret = {}
    for a in pattern.flat + options + collected
      name = a.name
      if name and name != ''
        ret[name] = a.value
      end
    end
    return ret
  end
  raise Exit
end

.dump_patterns(pattern, indent = 0) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/docopt.rb', line 587

def dump_patterns(pattern, indent=0)
  ws = " " * 4 * indent
  out = ""
  if pattern.class == Array
    if pattern.count > 0
      out << ws << "[\n"
      for p in pattern
        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"
    for p in pattern.children
      out << dump_patterns(p, indent+1).rstrip << "\n"
    end
    out << ws << ")\n"

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

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



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'lib/docopt.rb', line 614

def extras(help, version, options, doc)
  ofound = false
  vfound = false
  for o in options
    if o.value and (o.name == '-h' or o.name == '--help')
      ofound = true
    end
    if o.value and (o.name == '--version')
      vfound = true
    end
  end

  if help and ofound
    Exit.set_usage(nil)
    raise Exit, doc.strip
  end
  if version and vfound
    Exit.set_usage(nil)
    raise Exit, version
  end
end

.formal_usage(printable_usage) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/docopt.rb', line 572

def formal_usage(printable_usage)
  pu = printable_usage.split()[1..-1]  # split and drop "usage:"

  ret = []
  for s in pu[1..-1]
    if s == pu[0]
      ret << ') | ('
    else
      ret << s
    end
  end

  return '( ' + ret.join(' ') + ' )'
end

.parse_argv(source, options) ⇒ Object



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/docopt.rb', line 540

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

.parse_atom(tokens, options) ⇒ Object



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/docopt.rb', line 507

def parse_atom(tokens, options)
  token = tokens.current()
  result = []

  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
    return [result]
  elsif token == 'options'
    tokens.move()
    return options
  elsif token.start_with?('--') and token != '--'
    return parse_long(tokens, options)
  elsif token.start_with?('-') and not ['-', '--'].include? token
    return parse_shorts(tokens, options)

  elsif token.start_with?('<') and token.end_with?('>') or token.upcase == token
    return [Argument.new(tokens.move())]
  else
    return [Command.new(tokens.move())]
  end
end

.parse_doc_options(doc) ⇒ Object



557
558
559
# File 'lib/docopt.rb', line 557

def parse_doc_options(doc)
  return doc.split(/^ *-|\n *-/)[1..-1].map { |s| Option.parse('-' + s) }
end

.parse_expr(tokens, options) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/docopt.rb', line 478

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
  return result.count > 1 ? [Either.new(*result)] : result
end

.parse_long(tokens, options) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/docopt.rb', line 374

def parse_long(tokens, options)
  raw, eq, value = tokens.move().partition('=')
  value = (eq == value and eq == '') ? nil : value

  opt = options.select { |o| o.long and o.long == raw }

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

  if opt.count < 1
    if tokens.error == Exit
      raise tokens.error, "#{raw} is not recognized"
    else
      o = Option.new(nil, raw, eq == '=' ? 1 : 0)
      options << o
      return [o]
    end
  end
  if opt.count > 1
    ostr = opt.map { |o| o.long }.join(', ')
    raise tokens.error, "#{raw} is not a unique prefix: #{ostr}?"
  end
  o = opt[0]
  opt = Option.new(o.short, o.long, o.argcount, o.value)
  if opt.argcount == 1
    if value == nil
      if tokens.current() == nil
        raise tokens.error, "#{opt.name} requires argument"
      end
      value = tokens.move()
    end
  elsif value != nil
    raise tokens.error, "#{opt.name} must not have an argument"
  end

  if tokens.error == Exit
    opt.value = value ? value : true
  else
    opt.value = value ? nil : false
  end
  return [opt]
end

.parse_pattern(source, options) ⇒ Object



467
468
469
470
471
472
473
474
475
# File 'lib/docopt.rb', line 467

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

  result = parse_expr(tokens, options)
  if tokens.current() != nil
    raise tokens.error, "unexpected ending: #{tokens.join(" ")}"
  end
  return Required.new(*result)
end

.parse_seq(tokens, options) ⇒ Object



493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/docopt.rb', line 493

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

.parse_shorts(tokens, options) ⇒ Object



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/docopt.rb', line 418

def parse_shorts(tokens, options)
  raw = tokens.move()[1..-1]
  parsed = []
  while raw != ''
    first = raw.slice(0, 1)
    opt = options.select { |o| o.short and o.short.sub(/^-+/, '').start_with?(first) }

    if opt.count > 1
      raise tokens.error, "-#{first} is specified ambiguously #{opt.count} times"
    end

    if opt.count < 1
      if tokens.error == Exit
        raise tokens.error, "-#{first} is not recognized"
      else
        o = Option.new('-' + first, nil)
        options << o
        parsed << o
        raw = raw[1..-1]
        next
      end
    end

    o = opt[0]
    opt = Option.new(o.short, o.long, o.argcount, o.value)
    raw = raw[1..-1]
    if opt.argcount == 0
      value = tokens.error == Exit ? true : false
    else
      if raw == ''
        if tokens.current() == nil
          raise tokens.error, "-#{opt.short.slice(0, 1)} requires argument"
        end
        raw = tokens.move()
      end
      value, raw = raw, ''
    end

    if tokens.error == Exit
      opt.value = value
    else
      opt.value = value ? nil : false
    end
    parsed << opt
  end
  return parsed
end

.printable_usage(doc) ⇒ Object



561
562
563
564
565
566
567
568
569
570
# File 'lib/docopt.rb', line 561

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
  return usage_split[1..-1].join().split(/\n\s*\n/)[0].strip
end