Class: Cl::Parser

Inherits:
OptionParser
  • Object
show all
Defined in:
lib/cl/parser.rb,
lib/cl/parser/format.rb

Defined Under Namespace

Classes: Format

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, args) ⇒ Parser

Returns a new instance of Parser.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/cl/parser.rb', line 8

def initialize(cmd, args)
  @cmd = cmd
  @opts = {}
  opts = cmd.class.opts

  super do
    opts.each do |opt|
      Format.new(opt).strs.each do |str|
        on(str) { |value| set(opt, str, value) }
      end
    end
  end

  @args = parse!(normalize(opts, args))
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



6
7
8
# File 'lib/cl/parser.rb', line 6

def args
  @args
end

#cmdObject (readonly)

Returns the value of attribute cmd.



6
7
8
# File 'lib/cl/parser.rb', line 6

def cmd
  @cmd
end

#optsObject (readonly)

Returns the value of attribute opts.



6
7
8
# File 'lib/cl/parser.rb', line 6

def opts
  @opts
end

Instance Method Details

#long?(str) ⇒ Boolean

DASHERIZE = /^–([^= ])*/

def dasherize(strs)

strs.map do |str|
  str.is_a?(String) ? str.gsub(DASHERIZE) { |opt| opt.gsub('_', '-') } : str
end

end

Returns:

  • (Boolean)


62
63
64
# File 'lib/cl/parser.rb', line 62

def long?(str)
  str.start_with?('--')
end

#negation(opts, arg) ⇒ Object



47
48
49
50
51
52
# File 'lib/cl/parser.rb', line 47

def negation(opts, arg)
  opts.select(&:flag?).detect do |opt|
    str = opt.negate.detect { |str| arg =~ /^--#{str}[-_]+#{opt.name}/ }
    break str if str
  end
end

#noize(opts, args) ⇒ Object



40
41
42
43
44
45
# File 'lib/cl/parser.rb', line 40

def noize(opts, args)
  args.map do |arg|
    str = negation(opts, arg)
    str ? arg.sub(/^--#{str}[-_]+/, '--no-') : arg
  end
end

#normalize(opts, args) ⇒ Object



34
35
36
37
38
# File 'lib/cl/parser.rb', line 34

def normalize(opts, args)
  args = noize(opts, args)
  # dasherize(args)
  args
end

#opt_name(str) ⇒ Object



66
67
68
# File 'lib/cl/parser.rb', line 66

def opt_name(str)
  str.split(' ').first.sub(/--(\[no[_\-]\])?/, '').to_sym
end

#set(opt, str, value) ⇒ Object

should consider negative arities (e.g. |one, *two|)



25
26
27
28
29
30
31
32
# File 'lib/cl/parser.rb', line 25

def set(opt, str, value)
  name = long?(str) ? opt_name(str) : opt.name
  value = true if value.nil? && opt.flag?
  args = [opts, opt.type, name, value]
  args = args[-opt.block.arity, opt.block.arity]
  instance_exec(*args, &opt.block)
  cmd.deprecations.update([opt.deprecated].to_h) if opt.deprecated?(name)
end