Sha256: a62360fca25353b35139ff409c4080aa226d087310ba05cb3a330828bfab561c

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

require 'cxxproject/utils/printer'
require 'cxxproject/utils/exit_helper'

module Cxxproject


class Option
  attr_reader :param, :arg, :block
  def initialize(param, arg, &f)
    @param = param
    @arg = arg # true / false
    @block = f
    f
    
  end
end


class Parser
  
  def initialize(argv)
    @options = {}
    @argv = argv
    @default = nil
  end
  
  def add_option(opt)
    @options[opt.param] = opt
  end
  
  def add_default(opt)
    @default = opt
  end
  
  def parse_internal(ignoreInvalid = true)
    pos = 0
    begin
      while pos < @argv.length do
        if not @options.include?@argv[pos]
          if @default
            res = @default.call(@argv[pos])
            if (not res and not ignoreInvalid)
              raise "Option #{@argv[pos]} unknown"
            end
          end
        else
          option = @options[@argv[pos]]
          if option.arg
            if pos+1 < @argv.length and @argv[pos+1][0] != "-"
              option.block.call(@argv[pos+1])
              pos = pos + 1
            else
              raise "Argument for option #{@argv[pos]} missing" 
            end
          else
            option.block.call()
          end
        end
        pos = pos + 1
      end
    rescue SystemExit => e
      raise
    rescue Exception => e
      Printer.printError e.message
      ExitHelper.exit(1)
    end
    
  end

end


end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bake-toolkit-1.0.13 lib/option/parser.rb
bake-toolkit-1.0.12 lib/option/parser.rb