Class: XOptionParser

Inherits:
OptionParser
  • Object
show all
Defined in:
lib/xoptparse.rb,
lib/xoptparse/version.rb

Defined Under Namespace

Classes: Switch

Constant Summary collapse

VERSION =
'0.3.0'

Instance Method Summary collapse

Constructor Details

#initialize(description = nil, *args, &block) ⇒ XOptionParser



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/xoptparse.rb', line 7

def initialize(description = nil, *args, &block)
  @commands = {}
  @banner_usage = 'Usage: '
  @banner_options = '[options]'
  @banner_command = '<command>'
  super(nil, *args) do |opt|
    if description
      opt.separator ''
      opt.separator description
    end
    block&.call(opt)
  end
end

Instance Method Details



33
34
35
36
37
38
39
40
41
42
# File 'lib/xoptparse.rb', line 33

def banner
  return @banner if @banner

  banner = +"#{@banner_usage}#{program_name}"
  banner << " #{@banner_options}" unless no_options
  visit(:add_banner, banner)
  banner << " #{@banner_command}" unless @commands.empty?

  banner
end

#command(name, desc = nil, *args, &block) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
# File 'lib/xoptparse.rb', line 147

def command(name, desc = nil, *args, &block)
  sw0 = Switch::SummarizeArgument.new(nil, nil, nil, nil, name.to_s, desc ? [desc] : [], nil) do
    self.class.new(desc, *args) do |opt|
      opt.program_name = "#{program_name} #{name}"
      block&.call(opt)
    end
  end
  top.append(sw0, nil, [sw0.arg])
  @commands[name.to_s] = sw0
  nil
end

#make_switch(opts, block = nil) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/xoptparse.rb', line 64

def make_switch(opts, block = nil)
  sw = super(opts, block || proc {})
  sw0 = sw[0]
  return sw if sw0.short || sw0.long

  sw0 = fix_arg_switch(sw0)
  long = sw0.arg_parameters.map(&:first)
  [sw0, nil, long]
end

#order!(*args, into: nil, **kwargs) ⇒ Object

rubocop:disable Metrics/AbcSize



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/xoptparse.rb', line 129

def order!(*args, into: nil, **kwargs) # rubocop:disable Metrics/AbcSize
  return super(*args, into: into, **kwargs) if @commands.empty?

  argv = super(*args, into: into, **kwargs, &nil)
  return argv if argv.empty?

  name = argv.shift
  sw = @commands[name]
  if sw
    into = into[name.to_sym] = {} if into
    return sw.block.call.send(block_given? ? :permute! : :order!, *args, into: into, **kwargs)
  end

  puts "#{program_name}:" \
       "'#{name}' is not a #{program_name} command. See '#{program_name} --help'."
  exit
end