class Boilerpl8::CommandOptionParser

Attributes

optdefs[R]

Public Class Methods

new(optdef_strs) click to toggle source
# File lib/boilerpl8.rb, line 301
def initialize(optdef_strs)
  @optdef_strs = optdef_strs
  @optdefs = []
  optdef_strs.each do |optdef_str|
    case optdef_str
    when /-(\w), --(\w[-\w]*)(?:=(\S+))?\s*:\s*(\S.*)?/ ; t = [$1, $2, $3, $4]
    when /-(\w)(?:\s+(\S+))?\s*:\s*(\S.*)?/             ; t = [$1, nil, $2, $3]
    when /--(\w[-\w]*)(?:=(\S+))?\s*:\s*(\S.*)?/        ; t = [nil, $1, $2, $3]
    else
      raise "unexpected option definition: #{optdef_str}"
    end
    short, long, param, desc = t
    @optdefs << CommandOptionDefinition.new(short, long, param, desc)
  end
end

Public Instance Methods

parse(args) click to toggle source
# File lib/boilerpl8.rb, line 319
def parse(args)
  options = {}
  while ! args.empty? && args[0].start_with?('-')
    argstr = args.shift
    if argstr.start_with?('--')
      rexp = /\A--([-\w]+)(?:=(.*))?\z/
      argstr =~ rexp                   or err("#{argstr}: invalid option format.")
      name, value = $1, $2
      optdef = find_by(:long, name)    or err("--#{name}: unknown option.")
      optdef.param.nil? || value       or err("#{argstr}: argument required.")
      optdef.param      || value.nil?  or err("#{argstr}: unexpected argument.")
      options[optdef.long] = value || true
    else
      n = argstr.length
      i = 0
      while (i += 1) < n
        ch = argstr[i]
        optdef = find_by(:short, ch)   or err("-#{ch}: unknown option.")
        if optdef.param.nil?   # no arguments
          options[optdef.long || optdef.short] = true
        else                   # argument required
          param = argstr[(i+1)..-1]
          param = args.shift if param.empty?
          param  or err("-#{ch}: argument required.")
          options[optdef.long || optdef.short] = param
          break
        end
      end
    end
  end
  return options
end

Private Instance Methods

err(msg) click to toggle source
# File lib/boilerpl8.rb, line 358
def err(msg)
  raise CommandOptionError.new(msg)
end
find_by(key, value) click to toggle source
# File lib/boilerpl8.rb, line 354
def find_by(key, value)
  return @optdefs.find {|x| x.__send__(key) == value }
end