Class: Moister::SubcommandOptionParser

Inherits:
OptionParserExtra show all
Defined in:
lib/moister.rb

Instance Method Summary collapse

Methods inherited from OptionParserExtra

#on

Constructor Details

#initializeSubcommandOptionParser

Returns a new instance of SubcommandOptionParser.



27
28
29
30
31
32
# File 'lib/moister.rb', line 27

def initialize
  # options applicable to all subcommands
  @for_all = []
  @subcommands = {}
  super
end

Instance Method Details

#for_all(&block) ⇒ Object

add a block to configure every subcommand



39
40
41
# File 'lib/moister.rb', line 39

def for_all &block
  @for_all.push block
end

#parse(args = ARGV) ⇒ Object



79
80
81
# File 'lib/moister.rb', line 79

def parse(args = ARGV)
  parse! args.clone
end

#parse!(args = ARGV) ⇒ Object



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

def parse!(args = ARGV)
  apply_for_all self
  order! args
  if args.empty?
    ParseResults.new(nil, [], @config)
  else
    cmd = args.first
    subcmd_meta = @subcommands[cmd]
    raise "invalid subcommand: #{cmd}" unless @subcommands.has_key? cmd
    args.shift

    positionals = OptionParserExtra.new(@config) do |subop|
      apply_for_all subop
      subop.banner = subcmd_meta[:banner]
      parse_cmdline = subcmd_meta[:parse_cmdline]
      parse_cmdline.call(subop) if parse_cmdline
    end.order! args

    ParseResults.new(cmd, positionals, @config)
  end
end

#subcommand(name, banner, &block) ⇒ Object



34
35
36
# File 'lib/moister.rb', line 34

def subcommand name, banner, &block
  @subcommands[name] = { name: name, banner: banner, parse_cmdline: block }
end

#to_sObject Also known as: help



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/moister.rb', line 43

def to_s
  ret = super
  max_len = @subcommands.values.map { |subcmd| subcmd[:name].length }.max
  ret += "\ncommands:\n"
  @subcommands.values.each do |subcmd|
    prefix = subcmd[:name]
    prefix += ' ' * (max_len - prefix.length + 2)
    ret += "    #{prefix}  #{subcmd[:banner]}\n"
  end
  ret
end