lib/parsearg.rb


DEFINITIONS

This source file includes following functions.


   1  #
   2  #               parsearg.rb - parse arguments
   3  #                       $Release Version: $
   4  #                       $Revision: 1.2 $
   5  #                       $Date: 2002/07/29 06:14:06 $
   6  #                       by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
   7  #
   8  # --
   9  #
  10  #       
  11  #
  12  
  13  $RCS_ID=%q$Header: /src/ruby/lib/parsearg.rb,v 1.2 2002/07/29 06:14:06 matz Exp $
  14  
  15  require "getopts"
  16  
  17  def printUsageAndExit()
  18    if $USAGE
  19      eval($USAGE)
  20    end
  21    exit()
  22  end
  23  
  24  def setParenthesis(ex, opt, c)
  25    if opt != ""
  26      ex = sprintf("%s$OPT_%s%s", ex, opt, c)
  27    else
  28      ex = sprintf("%s%s", ex, c)
  29    end
  30    return ex
  31  end
  32  
  33  def setOrAnd(ex, opt, c)
  34    if opt != ""
  35      ex = sprintf("%s$OPT_%s %s%s ", ex, opt, c, c)
  36    else
  37      ex = sprintf("%s %s%s ", ex, c, c)
  38    end
  39    return ex
  40  end
  41  
  42  def setExpression(ex, opt, op)
  43    if !op
  44      ex = sprintf("%s$OPT_%s", ex, opt)
  45      return ex
  46    end
  47    case op.chr
  48    when "(", ")"
  49      ex = setParenthesis(ex, opt, op.chr)
  50    when "|", "&"
  51      ex = setOrAnd(ex, opt, op.chr)
  52    else
  53      return nil
  54    end
  55    return ex
  56  end
  57  
  58  def parseArgs(argc, nopt, single_opts, *opts)
  59    if (noOptions = getopts(single_opts, *opts)) == nil
  60      printUsageAndExit()
  61    end
  62    if nopt
  63      ex = nil
  64      pos = 0
  65      for o in nopt.split(/[()|&]/)
  66        pos += o.length
  67        ex = setExpression(ex, o, nopt[pos])
  68        pos += 1
  69      end
  70      begin
  71        if !eval(ex)
  72          printUsageAndExit()
  73        end
  74      rescue
  75        print "Format Error!! : \"" + nopt + "\"\t[parseArgs]\n"
  76        exit!(-1)
  77      end
  78    end
  79    if ARGV.length < argc
  80      printUsageAndExit()
  81    end
  82    return noOptions
  83  end