lib/optparse.rb


DEFINITIONS

This source file includes following functions.


   1  # optparse library, not octopus.
   2  
   3  =begin
   4  = Summary
   5  Library for command line option analysis.
   6  
   7  features:
   8  (1) It is possible <option switch of a short form and a long form> to
   9      exist together. It is also possible in one to bring the switch of
  10      a short form together.
  11  (2) It is possible to write bringing specification and the handler of
  12      the switch together respectively in one place.
  13  (3) The argument of the switch is converted into the class which
  14      automatically specifies it.
  15  (4) The option summary can be made.
  16  (5) The option can be added on the way later.
  17  
  18  =end #'#"#`#
  19  # Not yet (;_;)
  20  =begin
  21  
  22  == Class tree
  23     * ((<OptionParser>)) front end
  24     * ((<OptionParser::Switch>)) each switches
  25     * ((<OptionParser::List>)) options list
  26     * ((<OptionParser::ParseError>)) errors on parsing
  27       * ((<OptionParser::AmbiguousOption>))
  28       * ((<OptionParser::NeedlessArgument>))
  29       * ((<OptionParser::MissingArgument>))
  30       * ((<OptionParser::InvalidOption>))
  31       * ((<OptionParser::InvalidArgument>))
  32         * ((<OptionParser::AmbiguousArgument>))
  33  
  34  == Object relations
  35     +--------------+
  36     | OptionParser |<>-----+
  37     +--------------+       |                      +--------+
  38                            |                    ,-| Switch |
  39          on_head -------->+---------------+    /  +--------+
  40          accept/reject -->| List          |<|>-
  41                           |               |<|>-  +----------+
  42          on ------------->+---------------+    `-| argument |
  43                           :               :      |  class   |
  44                           +---------------+      |==========|
  45          on_tail -------->|               |      |pattern   |
  46                           +---------------+      |----------|
  47     OptionParser.accept ->| DefaultList   |      |converter |
  48                  reject   |(shared between|      +----------+
  49                           | all instances)|
  50                           +---------------+
  51  
  52  =end #'#"#`#
  53  
  54  =begin
  55  = Classes & Modules
  56  =end #'#"#`#
  57  
  58  class OptionParser
  59    RCSID = %w$Id: optparse.rb,v 1.4 2002/08/08 00:38:20 nobu Exp $[1..-1].each {|s| s.freeze}.freeze
  60    Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
  61    LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
  62    Release = RCSID[2]
  63  
  64    NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
  65    RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
  66    OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
  67  
  68  =begin private
  69  == ((:OptionParser::Completion:))
  70  Keyword completion module.
  71  =end #'#"#`#
  72    module Completion
  73  =begin private
  74  --- OptionParser::Completion#complete(key[, pat])
  75      Searches ((|key|)), or ((|pat|)) with completion if not found.
  76      :Parameters:
  77        : ((|key|))
  78          keyword to search.
  79        : ((|pat|))
  80          completion pattern.
  81  =end #'#"#`#
  82      def complete(key, pat = nil)
  83        pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+(?=.)/, '\&\w*'), true)
  84        canon, sw, k, v = nil
  85        each do |k, *v|
  86          (if Regexp === k
  87             k === key
  88           else
  89             pat === (defined?(k.id2name) ? k.id2name : k)
  90           end) or next
  91          v << k if v.empty?
  92          unless canon
  93            canon, sw = k, v
  94          else
  95            throw :ambiguous, key unless sw == v
  96          end
  97        end
  98        if canon
  99          block_given? or return key, *sw
 100          yield(key, *sw)
 101        end
 102      end
 103  
 104  =begin private
 105  --- OptionParser::Completion#convert(opt, *val)
 106      Extracts the first element from result of
 107      ((<OptionParser::Completion#complete>)).
 108  =end #'#"#`#
 109      def convert(opt = nil, val = nil, *)
 110        val
 111      end
 112    end
 113  
 114  =begin private
 115  == ((:OptionParser::OptionMap:))
 116  Map from option/keyword string to object with completion.
 117  === Superclass
 118  (({Hash}))
 119  === Including modules
 120  ((<OptionParser::Completion>))
 121  =end #'#"#`#
 122    class OptionMap < Hash
 123      include Completion
 124    end
 125  
 126  
 127  =begin
 128  == ((:OptionParser::Switch:))
 129  Individual switch class.
 130  =end #'#"#`#
 131    class Switch
 132      attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
 133  
 134  =begin private
 135  === Class methods
 136  =end
 137  =begin private
 138  --- OptionParser::Switch.guess(arg)
 139      Guesses argument style from ((|arg|)).
 140      Returns corresponding ((<OptionParser::Switch>)) subclass.
 141  =end #'#"#`#
 142      def self.guess(arg)
 143        case arg
 144        when ""
 145          self
 146        when /\A[=\s]?\[/
 147          Switch::OptionalArgument
 148        else
 149          Switch::RequiredArgument
 150        end
 151      end
 152  
 153  =begin private
 154  --- OptionParser::Switch.new
 155  =end #'#"#`#
 156      def initialize(pattern = nil, conv = nil,
 157                     short = nil, long = nil, arg = nil,
 158                     desc = ([] if short or long), block = Proc.new)
 159        @pattern, @conv, @short, @long, @arg, @desc, @block =
 160          pattern, conv, short, long, arg, desc, block
 161      end
 162  
 163  =begin
 164  === Instance methods
 165  =end
 166  =begin private
 167  --- OptionParser::Switch#parse_arg(arg) {non-serious error handler}
 168      Parses argument and returns rest of ((|arg|)), and matched portion
 169      to the argument pattern.
 170      :Parameters:
 171        : ((|arg|))
 172          option argument to be parsed.
 173        : (({block}))
 174          yields when the pattern doesn't match sub-string.
 175  =end #'#"#`#
 176      def parse_arg(arg)
 177        pattern or return nil, arg
 178        unless m = pattern.match(arg)
 179          yield(InvalidArgument, arg)
 180          return arg, nil
 181        end
 182        if String === m
 183          m = [s = m]
 184        else
 185          m = m.to_a
 186          s = m[0]
 187          return nil, *m unless String === s
 188        end
 189        raise InvalidArgument, arg unless arg.rindex(s, 0)
 190        return nil, *m if s.length == arg.length
 191        yield(InvalidArgument, arg) # didn't match whole arg
 192        return arg[s.length..-1], *m
 193      end
 194      private :parse_arg
 195  
 196  =begin
 197  --- OptionParser::Switch#parse(arg, val) {semi-error handler}
 198      Parses argument, convert and returns ((|arg|)), ((|block|)) and
 199      result of conversion.
 200      : Arguments to ((|@conv|))
 201        substrings matched to ((|@pattern|)), ((|$&|)), ((|$1|)),
 202        ((|$2|)) and so on.
 203      :Parameters:
 204        : ((|arg|))
 205          argument string follows the switch.
 206        : ((|val|))
 207          following argument.
 208        : (({block}))
 209          (({yields})) at semi-error condition, instead of raises exception.
 210  =end #'#"#`#
 211      def parse(arg, *val)
 212        if block
 213          val = conv.yield(*val) if conv
 214          return arg, block, val
 215        else
 216          return arg, nil
 217        end
 218      end
 219  
 220  =begin private
 221  --- OptionParser::Switch#summarize(sdone, ldone, width, max, indent)
 222      Makes summary strings.
 223      :Parameters:
 224        : ((|sdone|))
 225          already summarized short style options keyed hash.
 226        : ((|ldone|))
 227          already summarized long style options keyed hash.
 228        : ((|width|))
 229          width of left side, option part. in other word, right side,
 230          description part strings start at ((|width|)) column.
 231        : ((|max|))
 232          maximum width of left side, options are filled within ((|max|)) columns.
 233        : ((|indent|))
 234          prefix string indents each summarized lines.
 235        : (({block}))
 236          to be passed each lines(without newline).
 237  =end #'#"#`#
 238      def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
 239        sopts, lopts, s = [], [], nil
 240        @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
 241        @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
 242        return if sopts.empty? and lopts.empty? # completely hidden
 243  
 244        left = [sopts.join(', ')]
 245        right = desc.dup
 246  
 247        while s = lopts.shift
 248          l = left[-1].length + s.length
 249          l += arg.length if left.size == 1 && arg
 250          l < max or left << ''
 251          left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
 252        end
 253  
 254        left[0] << arg if arg
 255        mlen = left.collect {|s| s.length}.max.to_i
 256        while mlen > width and l = left.shift
 257          mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen
 258          yield(indent + l)
 259        end
 260  
 261        while (l = left.shift; r = right.shift; l or r)
 262          l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
 263          yield(indent + l)
 264        end
 265  
 266        self
 267      end
 268  
 269  =begin private
 270  == Switch classes
 271  =end #'#"#`#
 272  
 273  =begin private
 274  === ((:OptionParser::Switch::NoArgument:))
 275  Switch that takes no arguments.
 276  ==== Superclass
 277  ((<OptionParser::Switch>))
 278  ==== Instance methods
 279  --- OptionParser::Switch::NoArgument#parse
 280      Raises an exception if any arguments given.
 281  =end #'#"#`#
 282      class NoArgument < self
 283        def parse(arg, argv, &error)
 284          yield(NeedlessArgument, arg) if arg
 285          super(arg)
 286        end
 287      end
 288  
 289  =begin private
 290  === ((:OptionParser::Switch::RequiredArgument:))
 291  Switch that takes an argument.
 292  ==== Superclass
 293  ((<OptionParser::Switch>))
 294  ==== Instance methods
 295  --- OptionParser::Switch::RequiredArgument#parse
 296      Raises an exception if argument is not present.
 297  =end #'#"#`#
 298      class RequiredArgument < self
 299        def parse(arg, argv, &error)
 300          unless arg
 301            raise MissingArgument if argv.empty?
 302            arg = argv.shift
 303          end
 304          super(*parse_arg(arg, &error))
 305        end
 306        def self.guess(arg)
 307          self >= (t = super) or
 308            raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
 309          t
 310        end
 311      end
 312  
 313  =begin private
 314  === ((:OptionParser::Switch::OptionalArgument:))
 315  Switch that can omit argument.
 316  ==== Superclass
 317  ((<OptionParser::Switch>))
 318  ==== Instance methods
 319  --- OptionParser::Switch::OptionalArgument#parse
 320      Parses argument if given, or uses default value.
 321  =end #'#"#`#
 322      class OptionalArgument < self
 323        def parse(arg, argv, &error)
 324          if arg
 325            super(*parse_arg(arg, &error))
 326          else
 327            super(arg)
 328          end
 329        end
 330        def self.guess(arg)
 331          self >= (t = super) or
 332            raise ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}"
 333          t
 334        end
 335      end
 336    end
 337  
 338  
 339  =begin
 340  == ((:OptionParser::List:))
 341  Simple option list providing mapping from short and/or long option
 342  string to ((<OptionParser::Switch>)), and mapping from acceptable
 343  argument to matching pattern and converter pair.  Also provides
 344  summary feature.
 345  =end #'#"#`#
 346    class List
 347  =begin
 348  === Class methods
 349  =end #'#"#`#
 350  =begin private
 351  --- OptionParser::List.new
 352      Just initializes all instance variables.
 353  =end #'#"#`#
 354      def initialize
 355        @atype = {}
 356        @short = OptionMap.new
 357        @long = OptionMap.new
 358        @list = []
 359      end
 360  
 361  =begin
 362  === Instance methods
 363  =end #'#"#`#
 364  =begin
 365  --- OptionParser::List#atype
 366      Map from acceptable argument types to pattern and converter pairs.
 367  --- OptionParser::List#short
 368      Map from short style option switches to actual switch objects.
 369  --- OptionParser::List#long
 370      Map from long style option switches to actual switch objects.
 371  --- OptionParser::List#list
 372      List of all switches and summary string.
 373  =end #'#"#`#
 374      attr_reader :atype, :short, :long, :list
 375  
 376  =begin private
 377  --- OptionParser::List#accept(type[, pattern]) {...}
 378      see ((<OptionParser.accept>)).
 379  --- OptionParser::List#reject(type)
 380      see ((<OptionParser.reject>)).
 381  =end #'#"#`#
 382      def accept(t, pat = nil, &block)
 383        if pat
 384          pat.respond_to?(:match) or raise TypeError, "has no `match'"
 385        else
 386          pat = t if t.respond_to?(:match)
 387        end
 388        unless block
 389          block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
 390        end
 391        @atype[t] = [pat, block]
 392      end
 393  
 394      def reject(t)
 395        @atype.delete(t)
 396      end
 397  
 398  =begin private
 399  --- OptionParser::List#update(sw, sopts, lopts, nlopts = nil)
 400      Adds ((|sw|)) according to ((|sopts|)), ((|lopts|)) and
 401      ((|nlopts|)).
 402      :Parameters:
 403        : ((|sw|))
 404          ((<OptionParser::Switch>)) instance to be added.
 405        : ((|sopts|))
 406          short style options list.
 407        : ((|lopts|))
 408          long style options list.
 409        : ((|nlopts|))
 410          negated long style options list.
 411  =end #'#"#`#
 412      def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
 413        o = nil
 414        sopts.each {|o| @short[o] = sw} if sopts
 415        lopts.each {|o| @long[o] = sw} if lopts
 416        nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
 417        used = @short.invert.update(@long.invert)
 418        @list.delete_if {|o| Switch === o and !used[o]}
 419      end
 420      private :update
 421  
 422  =begin
 423  --- OptionParser::List#prepend(switch, short_opts, long_opts, nolong_opts)
 424      Inserts ((|switch|)) at head of the list, and associates short,
 425      long and negated long options.
 426  --- OptionParser::List#append(switch, short_opts, long_opts, nolong_opts)
 427      Appends ((|switch|)) at tail of the list, and associates short,
 428      long and negated long options.
 429      :Parameters:
 430        : ((|switch|))
 431          ((<OptionParser::Switch>)) instance to be inserted.
 432        : ((|short_opts|))
 433          list of short style options.
 434        : ((|long_opts|))
 435          list of long style options.
 436        : ((|nolong_opts|))
 437          list of long style options with (({"no-"})) prefix.
 438  =end #'#"#`#
 439      def prepend(*args)
 440        update(*args)
 441        @list.unshift(args[0])
 442      end
 443  
 444      def append(*args)
 445        update(*args)
 446        @list.push(args[0])
 447      end
 448  
 449  =begin
 450  --- OptionParser::List#search(id, key) [{block}]
 451      Searches ((|key|)) in ((|id|)) list.
 452      :Parameters:
 453        : ((|id|))
 454          searching list.
 455        : ((|k|))
 456          searching key.
 457        : (({Block}))
 458          yielded with the found value when succeeded.
 459  =end #'#"#`#
 460      def search(id, key)
 461        if list = __send__(id)
 462          val = list.fetch(key) {return nil}
 463          return val unless block_given?
 464          yield(val)
 465        end
 466      end
 467  
 468  =begin
 469  --- OptionParser::List#complete(id, opt, *pat, &block)
 470      Searches list ((|id|)) for ((|opt|)) and ((|*pat|)).
 471      :Parameters:
 472        : ((|id|))
 473          searching list.
 474        : ((|opt|))
 475          searching key.
 476        : ((|*pat|))
 477          optional pattern for completion.
 478        : (({Block}))
 479          yielded with the found value when succeeded.
 480  =end #'#"#`#
 481      def complete(id, opt, *pat, &block)
 482        __send__(id).complete(opt, *pat, &block)
 483      end
 484  
 485  =begin
 486  --- OptionParser::List#summarize(*args) {...}
 487      Making summary table, yields the (({block})) with each lines.
 488      Each elements of (({@list})) should be able to (({summarize})).
 489      :Parameters:
 490        : ((|args|))
 491          passed to elements#summarize through.
 492        : (({block}))
 493          to be passed each lines(without newline).
 494  =end #'#"#`#
 495      def summarize(*args, &block)
 496        list.each do |opt|
 497          if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
 498            opt.summarize(*args, &block)
 499          elsif opt.empty?
 500            yield("")
 501          else
 502            opt.each(&block)
 503          end
 504        end
 505      end
 506    end
 507  
 508  
 509  =begin private
 510  == ((:OptionParser::CompletingHash:))
 511  (({Hash})) with completion search feature.
 512  === Superclass
 513  (({Hash}))
 514  === Including modules
 515  ((<OptionParser::Completion>))
 516  =end #'#"#`#
 517    class CompletingHash < Hash
 518      include Completion
 519  
 520  =begin private
 521  === Instance methods
 522  --- OptionParser::CompletingHash#match(key)
 523      Completion for hash key.
 524  =end #'#"#`#
 525      def match(key)
 526        return key, *fetch(key) {
 527          raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
 528        }.to_a
 529      end
 530    end
 531  
 532  
 533  =begin
 534  == ((:OptionParser:))
 535  The front-end of (({OptionParser})).
 536  =end #'#"#`#
 537  
 538  =begin
 539  === Constants
 540  =end #'#"#`#
 541  
 542  =begin
 543  --- OptionParser::ArgumentStyle
 544      Enumeration of acceptable argument styles; possible values are:
 545      : OptionParser::NO_ARGUMENT
 546        the switch takes no arguments. ((({:NONE}))) 
 547      : OptionParser::REQUIRED_ARGUMENT
 548        the switch requires an argument. ((({:REQUIRED})))
 549      : OptionParser::OPTIONAL_ARGUMENT
 550        the switch requires an optional argument, that is, may take or
 551        not. ((({:OPTIONAL})))
 552  
 553      Use like (({--switch=argument}))(long style) or
 554      (({-Xargument}))(short style). For short style, only portion
 555      matched to ((<argument pattern>)) is dealed as argument.
 556  =end #'#"#`#
 557    ArgumentStyle = {}
 558    NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
 559    RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
 560    OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
 561    ArgumentStyle.freeze
 562  
 563  =begin private
 564  --- OptionParser::DefaultList
 565      Switches common used such as '--', and also provides default
 566      argument classes
 567  =end #'#"#`#
 568    DefaultList = List.new
 569    DefaultList.short['-'] = Switch::NoArgument.new {}
 570    DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
 571  
 572  =begin undocumented
 573  === Default options
 574  Default options, which never appear in option summary.
 575  --- --help
 576      Shows option summary.
 577  --- --version
 578      Shows version string if (({::Version})) is defined.
 579  =end #'#"#`#
 580    DefaultList.long['help'] = Switch::NoArgument.new do
 581      puts ARGV.options
 582      exit
 583    end
 584    DefaultList.long['version'] = Switch::NoArgument.new do
 585      if v = ARGV.options.ver
 586        puts v
 587        exit
 588      end
 589    end
 590  
 591  =begin
 592  === Class methods
 593  =end #'#"#`#
 594  
 595  =begin
 596  --- OptionParser.with([banner[, width[, indent]]]) [{...}]
 597      Initializes new instance, and evaluates the block in context of
 598      the instance if called as iterator.  This behavior is equivalent
 599      to older (({new})).  This is ((*deprecated*)) method.
 600      
 601      cf. ((<OptionParser.new>))
 602      :Parameters:
 603        : ((|banner|))
 604          banner message.
 605        : ((|width|))
 606          summary width.
 607        : ((|indent|))
 608          summary indent.
 609        : (({Block}))
 610          to be evaluated in the new instance context.
 611  =end #'#"#`#
 612    def self.with(*args, &block)
 613      opts = new(*args)
 614      opts.instance_eval(&block)
 615      opts
 616    end
 617  
 618  =begin
 619  --- OptionParser.inc(arg[, default])
 620  --- OptionParser#inc(arg[, default])
 621      Returns incremented value of ((|default|)) according to ((|arg|)).
 622  =end
 623    def self.inc(arg, default = nil)
 624      case arg
 625      when Integer
 626        arg.nonzero?
 627      when nil
 628        default.to_i + 1
 629      end
 630    end
 631    def inc(*args)
 632      type.inc(*args)
 633    end
 634  
 635  =begin
 636  --- OptionParser.new([banner[, width[, indent]]]) [{...}]
 637      Initializes the instance, and yields itself if called as iterator.
 638      :Parameters:
 639        : ((|banner|))
 640          banner message.
 641        : ((|width|))
 642          summary width.
 643        : ((|indent|))
 644          summary indent.
 645        : (({Block}))
 646          to be evaluated in the new instance context.
 647  =end #'#"#`#
 648    def initialize(banner = nil, width = 32, indent = ' ' * 4)
 649      @stack = [DefaultList, List.new, List.new]
 650      @program_name = nil
 651      @banner = banner
 652      @summary_width = width
 653      @summary_indent = indent
 654      yield self if block_given?
 655    end
 656  
 657  =begin
 658  --- OptionParser.terminate([arg])
 659      Terminates option parsing. Optional parameter ((|arg|)) would be
 660      pushed back if given.
 661      :Parameters:
 662        : ((|arg|))
 663          string pushed back to be first non-option argument
 664  =end #'#"#`#
 665    def terminate(arg = nil)
 666      type.terminate(arg)
 667    end
 668    def self.terminate(arg = nil)
 669      throw :terminate, arg
 670    end
 671  
 672    @stack = [DefaultList]
 673    def self.top() DefaultList end
 674  
 675  =begin
 676  --- OptionParser.accept(t, [pat]) {...}
 677  --- OptionParser#accept(t, [pat]) {...}
 678      Directs to accept specified class argument.
 679      :Parameters:
 680        : ((|t|))
 681          argument class specifier, any object including Class.
 682        : ((|pat|))
 683          pattern for argument, defaulted to ((|t|)) if it respond to (({match})).
 684        : (({Block}))
 685          receives argument string and should be convert to desired class.
 686  =end #'#"#`#
 687    def accept(*args, &blk) top.accept(*args, &blk) end
 688    def self.accept(*args, &blk) top.accept(*args, &blk) end
 689  
 690  =begin
 691  --- OptionParser.reject(t)
 692  --- OptionParser#reject(t)
 693      Directs to reject specified class argument.
 694      :Parameters:
 695        : ((|t|))
 696          argument class specifier, any object including Class.
 697  =end #'#"#`#
 698    def reject(*args, &blk) top.reject(*args, &blk) end
 699    def self.reject(*args, &blk) top.reject(*args, &blk) end
 700  
 701  
 702  =begin
 703  === Instance methods
 704  =end #'#"#`#
 705  
 706  =begin
 707  --- OptionParser#banner
 708  --- OptionParser#banner=(heading)
 709      Heading banner preceding summary.
 710  --- OptionParser#summary_width
 711  --- OptionParser#summary_width=(width)
 712      Width for option list portion of summary. Must be (({Numeric})).
 713  --- OptionParser#summary_indent
 714  --- OptionParser#summary_indent=(indent)
 715      Indentation for summary. Must be (({String})) (or have (({+ String}))).
 716  --- OptionParser#program_name
 717  --- OptionParser#program_name=(name)
 718      Program name to be emitted in error message and default banner,
 719      defaulted to (({$0})).
 720  =end #'#"#`#
 721    attr_writer :banner, :program_name
 722    attr_accessor :summary_width, :summary_indent
 723  
 724    def banner
 725      @banner ||= "Usage: #{program_name} [options]"
 726    end
 727  
 728    def program_name
 729      @program_name || File.basename($0, '.*')
 730    end
 731  
 732  # for experimental cascading :-)
 733    alias set_banner banner=
 734    alias set_program_name program_name=
 735    alias set_summary_width summary_width=
 736    alias set_summary_indent summary_indent=
 737  
 738  =begin
 739  --- OptionParser#version
 740  --- OptionParser#version=(ver)
 741      Version.
 742  --- OptionParser#release
 743  --- OptionParser#release=(rel)
 744      Release code.
 745  --- OptionParser#ver
 746      Returns version string from ((<program_name>)), (({version})) and
 747      (({release})).
 748  =end #'#"#`#
 749    attr_writer :version, :release
 750  
 751    def version
 752      @version || (defined?(::Version) && ::Version)
 753    end
 754  
 755    def release
 756      @release || (defined?(::Release) && ::Release)
 757    end
 758  
 759    def ver
 760      if v = version
 761        str = "#{program_name} #{[v].join('.')}"
 762        str << " (#{v})" if v = release
 763        str
 764      end
 765    end
 766  
 767  =begin
 768  --- OptionParser#top
 769      Subject of ((<on>))/((<on_head>)), ((<accept>))/((<reject>)).
 770  =end #'#"#`#
 771    def top
 772      @stack[-1]
 773    end
 774  
 775  =begin
 776  --- OptionParser#base
 777      Subject of ((<on_tail>)).
 778  =end #'#"#`#
 779    def base
 780      @stack[1]
 781    end
 782  
 783  =begin
 784  --- OptionParser#new
 785      Pushes a new (({List})).
 786  =end #'#"#`#
 787    def new
 788      @stack.push(List.new)
 789      if block_given?
 790        yield self
 791      else
 792        self
 793      end
 794    end
 795  
 796  =begin
 797  --- OptionParser#remove
 798      Removes the last (({List})).
 799  =end #'#"#`#
 800    def remove
 801      @stack.pop
 802    end
 803  
 804  
 805  =begin
 806  --- OptionParser#summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent)
 807      Puts option summary into ((|to|)), and returns ((|to|)).
 808      :Parameters:
 809        : ((|to|))
 810          output destination, which must have method ((|<<|)). Defaulted to (({[]})).
 811        : ((|width|))
 812          width of left side. Defaulted to ((|@summary_width|))
 813        : ((|max|))
 814          maximum length allowed for left side. Defaulted to (({((|width|)) - 1}))
 815        : ((|indent|))
 816          indentation. Defaulted to ((|@summary_indent|))
 817        : (({Block}))
 818          yields with each line if called as iterator.
 819  =end #'#"#`#
 820    def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
 821      visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
 822      to
 823    end
 824  
 825  =begin
 826  --- OptionParser#to_str
 827  --- OptionParser#to_s
 828      Returns option summary string.
 829  =end #'#"#`#
 830    def to_str; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
 831    alias to_s to_str
 832  
 833  =begin
 834  --- OptionParser#to_a
 835      Returns option summary list.
 836  =end #'#"#`#
 837    def to_a; summarize(banner.to_a.dup) end
 838  
 839  
 840  =begin
 841  --- OptionParser#switch
 842      Creates ((<OptionParser::Switch>)).
 843      :Parameters:
 844        : ((|*opts|))
 845          option definition:
 846          : argument style
 847            see ((<OptionParser::ArgumentStyle>))
 848          : argument pattern
 849            acceptable option argument format, must pre-defined with
 850            ((<OptionParser.accept>)) or ((<OptionParser#accept>)), or
 851            (({Regexp})). This can appear once or assigned as (({String}))
 852            if not present, otherwise causes exception (({ArgumentError})).
 853            
 854            cf. ((<Acceptable argument classes>)).
 855          : Hash
 856          : Array
 857            possible argument values.
 858          : Proc
 859          : Method
 860            alternative way to give the ((*handler*)).
 861          : "--switch=MANDATORY", "--switch[=OPTIONAL]", "--switch"
 862            specifies long style switch that takes ((*mandatory*)),
 863            ((*optional*)) and ((*no*)) argument, respectively.
 864          : "-xMANDATORY", "-x[OPTIONAL]", "-x"
 865            specifies short style switch that takes ((*mandatory*)),
 866            ((*optional*)) and ((*no*)) argument, respectively.
 867          : "-[a-z]MANDATORY", "-[a-z][OPTIONAL]", "-[a-z]"
 868            special form short style switch that matches character
 869            range(not fullset of regular expression).
 870          : "=MANDATORY", "=[OPTIONAL]"
 871            argument style and description.
 872          : "description", ...
 873            ((*description*)) for this option.
 874        : (({Block}))
 875          ((*handler*)) to convert option argument to arbitrary (({Class})).
 876  =end #'#"#`#
 877  =begin private
 878  --- OptionParser#notwice(obj, prv, msg)
 879      Checks never given twice an argument.
 880      ((*Called from OptionParser#switch only*))
 881      :Parameters:
 882        : ((|obj|))
 883          new argument.
 884        : ((|prv|))
 885          previously specified argument.
 886        : ((|msg|))
 887          exception message
 888  =end #'#"#`#
 889    def notwice(obj, prv, msg)
 890      unless !prv or prv == obj
 891        begin
 892          raise ArgumentError, "argument #{msg} given twice: #{obj}"
 893        rescue
 894          $@[0, 2] = nil
 895          raise
 896        end
 897      end
 898      obj
 899    end
 900    private :notwice
 901  
 902    def switch(*opts, &block)
 903      short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
 904      ldesc, sdesc, desc, arg = [], [], []
 905      default_style = Switch::NoArgument
 906      default_pattern = nil
 907      klass = nil
 908      o = nil
 909      n, q, a = nil
 910  
 911      opts.each do |o|
 912        # argument class
 913        next if search(:atype, o) do |pat, c|
 914          klass = notwice(o, klass, 'type')
 915          if not_style and not_style != Switch::NoArgument
 916            not_pattern, not_conv = pat, c
 917          else
 918            default_pattern, conv = pat, c
 919          end
 920        end
 921  
 922        # directly specified pattern(any object possible to match)
 923        if !(String === o) and o.respond_to?(:match)
 924          pattern = notwice(o, pattern, 'pattern')
 925          conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
 926          next
 927        end
 928  
 929        # anything others
 930        case o
 931        when Proc, Method
 932          block = notwice(o, block, 'block')
 933        when Array, Hash
 934          case pattern
 935          when CompletingHash
 936          when nil
 937            pattern = CompletingHash.new
 938            conv = (pattern.method(:convert).to_proc if pattern.respond_to?(:convert))
 939          else
 940            raise ArgumentError, "argument pattern given twice"
 941          end
 942          if Array === o
 943            o.each {|o| pattern[(Array === o ? o.shift : o)] = o}
 944          else
 945            pattern.update(o)
 946          end
 947        when Module
 948          raise ArgumentError, "unsupported argument type: #{o}"
 949        when *ArgumentStyle.keys
 950          style = notwice(ArgumentStyle[o], style, 'style')
 951        when /^--no-([^][=\s]*)(.+)?/
 952          q, a = $1, $2
 953          o = notwice(a ? Object : TrueClass, klass, 'type')
 954          not_pattern, not_conv = search(:atype, o) unless not_style
 955          not_style = (not_style || default_style).guess(arg = a) if a
 956          default_style = Switch::NoArgument
 957          default_pattern, conv = search(:atype, FalseClass)
 958          ldesc << "--no-#{q}"
 959          long << 'no-' + (q = q.downcase)
 960          nolong << q
 961        when /^--\[no-\]([^][=\s]*)(.+)?/
 962          q, a = $1, $2
 963          o = notwice(a ? Object : TrueClass, klass, 'type')
 964          default_style = default_style.guess(arg = a) if a
 965          default_pattern, conv = search(:atype, o)
 966          ldesc << "--#{q}"
 967          long << (o = q.downcase)
 968          not_pattern, not_conv = search(:atype, FalseClass) unless not_style
 969          not_style = Switch::NoArgument
 970          nolong << 'no-' + o
 971        when /^--([^][=\s]*)(.+)?/
 972          q, a = $1, $2
 973          o = notwice(a ? NilClass : TrueClass, klass, 'type')
 974          default_style = default_style.guess(arg = a) if a
 975          default_pattern, conv = search(:atype, o)
 976          ldesc << "--#{q}"
 977          long << (o = q.downcase)
 978        when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
 979          q, a = $1, $2
 980          o = notwice(Object, klass, 'type')
 981          default_style = default_style.guess(arg = a) if a
 982          default_pattern, conv = search(:atype, o)
 983          sdesc << "-#{q}"
 984          short << Regexp.new(q)
 985        when /^-(.)(.+)?/
 986          q, a = $1, $2
 987          o = notwice((a ? Object : TrueClass), klass, 'type')
 988          default_style = default_style.guess(arg = a) if a
 989          default_pattern, conv = search(:atype, o)
 990          sdesc << "-#{q}"
 991          short << q
 992        when /^=/
 993          style = notwice(default_style.guess(arg = o), style, 'style')
 994          default_pattern, conv = search(:atype, Object)
 995        else
 996          desc.push(o)
 997        end
 998      end
 999  
1000      s = if short.empty? and long.empty?
1001            raise ArgumentError, "no switch given" if style or pattern or block
1002            desc
1003          else
1004            (style || default_style).new(pattern || default_pattern,
1005                                         conv, sdesc, ldesc, arg, desc, block)
1006          end
1007      return s, short, long,
1008        (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
1009        nolong
1010    end
1011  
1012  =begin
1013  --- OptionParser#on(*opts) [{...}]
1014  --- OptionParser#def_option(*opts) [{...}]
1015  --- OptionParser#on_head(*opts) [{...}]
1016  --- OptionParser#def_head_option(*opts) [{...}]
1017  --- OptionParser#on_tail(*opts) [{...}]
1018  --- OptionParser#def_tail_option(*opts) [{...}]
1019      Defines option switch and handler. (({on_head})), (({def_head_option}))
1020      and (({on_tail})), (({def_tail_option})) put the switch at head
1021      and tail of summary, respectively.
1022  
1023      cf. ((<OptionParser#switch>)).
1024  =end #'#"#`#
1025    def on(*opts, &block)
1026      top.append(*switch(*opts, &block))
1027      self
1028    end
1029    alias def_option on
1030  
1031    def on_head(*opts, &block)
1032      top.prepend(*switch(*opts, &block))
1033      self
1034    end
1035    alias def_head_option on_head
1036  
1037    def on_tail(*opts, &block)
1038      base.append(*switch(*opts, &block))
1039      self
1040    end
1041    alias def_tail_option on_tail
1042  
1043  
1044  =begin
1045  --- OptionParser#order(*argv) [{...}]
1046  --- OptionParser#order!([argv = ARGV]) [{...}]
1047      Parses ((|argv|)) in order. When non-option argument encountered,
1048      yields it if called as iterator, otherwise terminates the parse
1049      process.
1050      Returns rest of ((|argv|)) left unparsed.
1051      
1052      (({order!})) takes argument array itself, and removes switches
1053      destructively.
1054      Defaults to parse ((|ARGV|)).
1055      :Parameters:
1056        : ((|argv|))
1057          command line arguments to be parsed.
1058        : (({Block}))
1059          called with each non-option argument.
1060  =end #'#"#`#
1061    def order(*argv, &block) order!(argv, &block) end
1062  
1063    def order!(argv = ARGV, &nonopt)
1064      opt, arg, sw, val, rest = nil
1065      nonopt ||= proc {|arg| throw :terminate, arg}
1066      argv.unshift(arg) if arg = catch(:terminate) {
1067        while arg = argv.shift
1068          case arg
1069          # long option
1070          when /\A--([^=]*)(?:=(.*))?/
1071            opt, rest = $1, $2
1072            begin
1073              sw, = complete(:long, opt)
1074            rescue ParseError
1075              raise $!.set_option(arg, true)
1076            end
1077            begin
1078              opt, sw, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
1079              sw.yield(val) if sw
1080            rescue ParseError
1081              raise $!.set_option(arg, rest)
1082            end
1083  
1084          # short option
1085          when /\A-(.)((=).*|.+)?/
1086            opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
1087            begin
1088              unless sw = search(:short, opt)
1089                begin
1090                  sw, = complete(:short, opt)
1091                  # short option matched.
1092                  val = arg.sub(/\A-/, '')
1093                  has_arg = true
1094                rescue InvalidOption
1095                  # if no short options match, try completion with long
1096                  # options.
1097                  sw, = complete(:long, opt)
1098                  eq ||= !rest
1099                end
1100              end
1101            rescue ParseError
1102              raise $!.set_option(arg, true)
1103            end
1104            begin
1105              opt, sw, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
1106              raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
1107              argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
1108              sw.yield(val) if sw
1109            rescue ParseError
1110              raise $!.set_option(arg, has_arg)
1111            end
1112  
1113          # non-option argument
1114          else
1115            nonopt.call(arg)
1116          end
1117        end
1118  
1119        nil
1120      }
1121  
1122      argv
1123    end
1124  
1125  =begin
1126  --- OptionParser#permute(*argv)
1127  --- OptionParser#permute!([argv = ARGV])
1128      Parses ((|argv|)) in permutation mode, and returns list of
1129      non-option arguments.
1130      
1131      (({permute!})) takes argument array itself, and removes switches
1132      destructively.
1133      Defaults to parse ((|ARGV|)).
1134      :Parameters:
1135        : ((|argv|))
1136          command line arguments to be parsed.
1137  =end #'#"#`#
1138    def permute(*argv)
1139      permute!(argv)
1140    end
1141  
1142    def permute!(argv = ARGV)
1143      nonopts = []
1144      arg = nil
1145      order!(argv) {|arg| nonopts << arg}
1146      argv[0, 0] = nonopts
1147      argv
1148    end
1149  
1150  =begin
1151  --- OptionParser#parse(*argv)
1152  --- OptionParser#parse!([argv = ARGV])
1153      Parses ((|argv|)) in order when environment variable (({POSIXLY_CORRECT}))
1154      is set, otherwise permutation mode
1155      
1156      (({parse!})) takes argument array itself, and removes switches
1157      destructively.
1158      Defaults to parse ((|ARGV|)).
1159      :Parameters:
1160        : ((|argv|))
1161          command line arguments to be parsed.
1162  =end #'#"#`#
1163    def parse(*argv)
1164      parse!(argv)
1165    end
1166  
1167    def parse!(argv = ARGV)
1168      if ENV.include?('POSIXLY_CORRECT')
1169        order!(argv)
1170      else
1171        permute!(argv)
1172      end
1173    end
1174  
1175  
1176  =begin private
1177  --- OptionParser#visit(id, *args) {block}
1178      Traverses (({stack}))s calling method ((|id|)) with ((|*args|)).
1179      :Parameters:
1180        : ((|id|))
1181          called method in each elements of (({stack}))s.
1182        : ((|*args|))
1183          passed to ((|id|)).
1184        : (({Block}))
1185          passed to ((|id|)).
1186  =end #'#"#`#
1187    def visit(id, *args, &block)
1188      el = nil
1189      @stack.reverse_each do |el|
1190        el.send(id, *args, &block)
1191      end
1192      nil
1193    end
1194    private :visit
1195  
1196  =begin private
1197  --- OptionParser#search(id, k)
1198      Searches ((|k|)) in stack for ((|id|)) hash, and returns it or yielded
1199      value if called as iterator.
1200      :Parameters:
1201        : ((|id|))
1202          searching table.
1203        : ((|k|))
1204          searching key.
1205        : (({Block}))
1206          yielded with the found value when succeeded.
1207  =end #'#"#`#
1208    def search(id, k)
1209      visit(:search, id, k) do |k|
1210        return k unless block_given?
1211        return yield(k)
1212      end
1213    end
1214    private :search
1215  
1216  =begin private
1217  --- OptionParser#complete(typ, opt, *etc)
1218      Completes shortened long style option switch, and returns pair of
1219      canonical switch and switch descriptor((<OptionParser::Switch>)).
1220      :Parameters:
1221        : ((|id|))
1222          searching table.
1223        : ((|opt|))
1224          searching key.
1225        : ((|*pat|))
1226          optional pattern for completion.
1227        : (({Block}))
1228          yielded with the found value when succeeded.
1229  =end #'#"#`#
1230    def complete(typ, opt, *pat)
1231      if pat.empty?
1232        search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1233      end
1234      raise AmbiguousOption, catch(:ambiguous) {
1235        visit(:complete, typ, opt, *pat) {|opt, *sw| return sw}
1236        raise InvalidOption, opt
1237      }
1238    end
1239    private :complete
1240  
1241  =begin undocumented
1242  --- OptionParser#load([filename])
1243      Loads options from file named as ((|filename|)). Does nothing when
1244      the file is not present. Returns whether successfuly loaded.
1245      :Parameters:
1246        : ((|filename|))
1247          option file name.  defaulted to basename of the program without
1248          suffix in a directory ((%~/.options%)).
1249  =end #'#"#`#
1250    def load(filename = nil)
1251      begin
1252        filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
1253      rescue
1254        return false
1255      end
1256      begin
1257        parse(*IO.readlines(filename).each {|s| s.chomp!})
1258        true
1259      rescue Errno::ENOENT, Errno::ENOTDIR
1260        false
1261      end
1262    end
1263  
1264  =begin undocumented
1265  --- OptionParser#environment([env])
1266      Parses environment variable ((|env|)) or its uppercase with spliting
1267      like as shell.
1268      :Parameters:
1269        : ((|env|))
1270          defaulted to basename of the program.
1271  =end #'#"#`#
1272    def environment(env = File.basename($0, '.*'))
1273      env = ENV[env] || ENV[env.upcase] or return
1274      parse(*Shellwords.shellwords(env))
1275    end
1276  
1277  
1278  =begin
1279  = Acceptable argument classes
1280  =end #'#"#`#
1281  
1282  =begin
1283  : Object
1284    any string, and no conversion. this is fall-back.
1285  =end #'#"#`#
1286    accept(Object) {|s|s or s.nil?}
1287  
1288    accept(NilClass) {|s|s}
1289  
1290  =begin
1291  : String
1292    any none-empty string, and no conversion.
1293  =end #'#"#`#
1294    accept(String, /.+/) {|s,*|s}
1295  
1296  =begin
1297  : Integer
1298    Ruby/C-like integer, octal for (({0-7})) sequence, binary for
1299    (({0b})), hexadecimal for (({0x})), and decimal for others; with
1300    optional sign prefix. Converts to (({Integer})).
1301  =end #'#"#`#
1302    decimal = '\d+(?:_\d+)*'
1303    binary = 'b[01]+(?:_[01]+)*'
1304    hex = 'x[\da-f]+(?:_[\da-f]+)*'
1305    octal = "0(?:[0-7]*(?:_[0-7]+)*|#{binary}|#{hex})"
1306    integer = "#{octal}|#{decimal}"
1307    accept(Integer, %r"\A[-+]?(?:#{integer})"io) {|s| Integer(s) if s}
1308  
1309  =begin
1310  : Float
1311    Float number format, and converts to (({Float})).
1312  =end #'#"#`#
1313    float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
1314    floatpat = %r"\A[-+]?#{float}"io
1315    accept(Float, floatpat) {|s| s.to_f if s}
1316  
1317  =begin
1318  : Numeric
1319    Generic numeric format, and converts to (({Integer})) for integer
1320    format, (({Float})) for float format.
1321  =end #'#"#`#
1322    accept(Numeric, %r"\A[-+]?(?:#{octal}|#{float})"io) {|s| eval(s) if s}
1323  
1324  =begin
1325  : OptionParser::DecimalInteger
1326    Decimal integer format, to be converted to (({Integer})).
1327  =end #'#"#`#
1328    DecimalInteger = /\A[-+]?#{decimal}/io
1329    accept(DecimalInteger) {|s| s.to_i if s}
1330  
1331  =begin
1332  : OptionParser::OctalInteger
1333    Ruby/C like octal/hexadecimal/binary integer format, to be converted
1334    to (({Integer})).
1335  =end #'#"#`#
1336    OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
1337    accept(OctalInteger) {|s| s.oct if s}
1338  
1339  =begin
1340  : OptionParser::DecimalNumeric
1341    Decimal integer/float number format, to be converted to
1342    (({Integer})) for integer format, (({Float})) for float format.
1343  =end #'#"#`#
1344    DecimalNumeric = floatpat     # decimal integer is allowed as float also.
1345    accept(DecimalNumeric) {|s| eval(s) if s}
1346  
1347  =begin
1348  : TrueClass
1349    Boolean switch, which means whether it is present or not, whether it
1350    is absent or not with prefix (({no-})), or it takes an argument
1351    (({yes/no/true/false/+/-})).
1352  : FalseClass
1353    Similar to ((<TrueClass>)), but defaulted to (({false})).
1354  =end #'#"#`#
1355    yesno = CompletingHash.new
1356    %w[- no false].each {|el| yesno[el] = false}
1357    %w[+ yes true].each {|el| yesno[el] = true}
1358    yesno['nil'] = false          # shoud be nil?
1359    accept(TrueClass, yesno) {|arg, val| val == nil or val}
1360    accept(FalseClass, yesno) {|arg, val| val != nil and val}
1361  
1362  =begin
1363  : Array
1364    List of strings separated by ","
1365  =end #'#"#`#
1366    accept(Array) do |s|
1367      if s
1368        s = s.split(',').collect {|s| s unless s.empty?}
1369        s.size > 1 or s = [s]     # guard empty or single.
1370      end
1371      s
1372    end
1373  
1374  
1375  =begin
1376  = Exceptions
1377  =end #'#"#`#
1378  
1379  =begin
1380  == ((:OptionParser::ParseError:))
1381  Base class of exceptions from ((<OptionParser>))
1382  === Superclass
1383  (({RuntimeError}))
1384  === Constants
1385  : OptionParser::ParseError::Reason
1386    Reason caused error.
1387  === Instance methods
1388  --- OptionParser::ParseError#recover(argv)
1389      Push backs erred argument(s) to ((|argv|)).
1390  --- OptionParser::ParseError#reason
1391      Returns error reason. Override this to I18N.
1392  --- OptionParser::ParseError#inspect
1393      Returns inspection string.
1394  --- OptionParser::ParseError#message
1395  --- OptionParser::ParseError#to_s
1396  --- OptionParser::ParseError#to_str
1397      Default stringizing method to emit standard error message.
1398  =end #'#"#`#
1399    class ParseError < RuntimeError
1400      Reason = 'parse error'.freeze
1401  
1402      def initialize(*args)
1403        @args = args
1404        @reason = nil
1405      end
1406  
1407      attr_reader :args
1408      attr_writer :reason
1409  
1410      def recover(argv)
1411        argv[0, 0] = @args
1412        argv
1413      end
1414  
1415      def set_option(opt, eq)
1416        if eq
1417          @args[0] = opt
1418        else
1419          @args.unshift(opt)
1420        end
1421        self
1422      end
1423  
1424      def reason
1425        @reason || self.type::Reason
1426      end
1427  
1428      def inspect
1429        '#<' + type.to_s + ': ' + args.join(' ') + '>'
1430      end
1431  
1432      def message
1433        reason + ': ' + args.join(' ')
1434      end
1435  
1436      alias to_s message
1437      alias to_str message
1438    end
1439  
1440  =begin
1441  == ((:OptionParser::AmbiguousOption:))
1442  Raises when encountered ambiguously completable string.
1443  === Superclass
1444  ((<OptionParser::ParseError>))
1445  =end #'#"#`#
1446    class AmbiguousOption < ParseError
1447      const_set(:Reason, 'ambiguous option'.freeze)
1448    end
1449  
1450  =begin
1451  == ((:OptionParser::NeedlessArgument:))
1452  Raises when encountered argument for switch defined as which takes no
1453  argument.
1454  === Superclass
1455  ((<OptionParser::ParseError>))
1456  =end #'#"#`#
1457    class NeedlessArgument < ParseError
1458      const_set(:Reason, 'needles argument'.freeze)
1459    end
1460  
1461  =begin
1462  == ((:OptionParser::MissingArgument:))
1463  Raises when no argument found for switch defined as which needs
1464  argument.
1465  === Superclass
1466  ((<OptionParser::ParseError>))
1467  =end #'#"#`#
1468    class MissingArgument < ParseError
1469      const_set(:Reason, 'missing argument'.freeze)
1470    end
1471  
1472  =begin
1473  == ((:OptionParser::InvalidOption:))
1474  Raises when undefined switch.
1475  === Superclass
1476  ((<OptionParser::ParseError>))
1477  =end #'#"#`#
1478    class InvalidOption < ParseError
1479      const_set(:Reason, 'invalid option'.freeze)
1480    end
1481  
1482  =begin
1483  == ((:OptionParser::InvalidArgument:))
1484  Raises when the given argument does not match required format.
1485  === Superclass
1486  ((<OptionParser::ParseError>))
1487  =end #'#"#`#
1488    class InvalidArgument < ParseError
1489      const_set(:Reason, 'invalid argument'.freeze)
1490    end
1491  
1492  =begin
1493  == ((:OptionParser::AmbiguousArgument:))
1494  Raises when the given argument word can't completed uniquely.
1495  === Superclass
1496  ((<OptionParser::InvalidArgument>))
1497  =end #'#"#`#
1498    class AmbiguousArgument < InvalidArgument
1499      const_set(:Reason, 'ambiguous argument'.freeze)
1500    end
1501  
1502  
1503  =begin
1504  = Miscellaneous
1505  =end #'#"#`#
1506  =begin
1507  == ((:OptionParser::Arguable:))
1508  Extends command line arguments array to parse itself.
1509  =end #'#"#`#
1510    module Arguable
1511  =begin
1512  --- OptionParser::Arguable#options=(opt)
1513      Sets ((<OptionParser>)) object, when ((|opt|)) is (({false})) or
1514      (({nil})), methods ((<OptionParser::Arguable#options>)) and
1515      ((<OptionParser::Arguable#options=>)) are undefined.  Thus, there
1516      is no ways to access the ((<OptionParser>)) object via the
1517      receiver object.
1518  =end #'#"#`#
1519      def options=(opt)
1520        unless @optparse = opt
1521          class << self
1522            undef_method(:options)
1523            undef_method(:options=)
1524          end
1525        end
1526      end
1527  
1528  =begin
1529  --- OptionParser::Arguable#options
1530      Actual ((<OptionParser>)) object, automatically created if not
1531      yet.
1532  
1533      If called as iterator, yields with the ((<OptionParser>)) object
1534      and returns the result of the block. In this case, rescues any
1535      ((<OptionParser::ParseError>)) exceptions in the block, just emits
1536      error message to ((<STDERR>)) and returns (({nil})).
1537  
1538      :Parameters:
1539        : (({block}))
1540          Yielded with the ((<OptionParser>)) instance.
1541  
1542  =end #'#"#`#
1543      def options
1544        @optparse ||= OptionParser.new
1545        block_given? or return @optparse
1546        begin
1547          yield @optparse
1548        rescue ParseError
1549          STDERR.puts @optparse.program_name + ': ' + $!
1550          nil
1551        end
1552      end
1553  
1554  =begin
1555  --- OptionParser::Arguable#order!
1556  --- OptionParser::Arguable#permute!
1557  --- OptionParser::Arguable#parse!
1558      Parses ((|self|)) destructively, and returns ((|self|)) just contains
1559      rest arguments left without parsed.
1560  =end #'#"#`#
1561      def order!(&blk) options.order!(self, &blk) end
1562      def permute!() options.permute!(self) end
1563      def parse!() options.parse!(self) end
1564  
1565  =begin private
1566  Initializes instance variable.
1567  =end #'#"#`#
1568      def self.extend_object(obj)
1569        super
1570        obj.instance_eval {@optparse = nil}
1571      end
1572      def initialize(*args)
1573        super
1574        @optparse = nil
1575      end
1576    end
1577  
1578  =begin
1579  == OptionParser::Acceptables
1580  Acceptable argument classes.  Now contains (({DecimalInteger})),
1581  (({OctalInteger})) and (({DecimalNumeric})).
1582  see ((<Acceptable argument classes>)).
1583  =end #'#"#`#
1584    module Acceptables
1585      const_set(:DecimalInteger, OptionParser::DecimalInteger)
1586      const_set(:OctalInteger, OptionParser::OctalInteger)
1587      const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
1588    end
1589  end
1590  
1591  # ARGV is arguable by OptionParser
1592  ARGV.extend(OptionParser::Arguable)
1593  
1594  
1595  if $0 == __FILE__
1596    Version = OptionParser::Version
1597    ARGV.options {|q|
1598      q.parse!.empty? or puts "what's #{ARGV.join(' ')}?"
1599    } or exit 1
1600  end
1601  __END__
1602  =begin example
1603  = Example
1604  <<< opttest.rb
1605  =end #'#"#`#