home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / ruby164.zip / rbemx164.zip / ruby / share / doc / optparse-0.8.2 / optparse.rb < prev    next >
Text File  |  2001-06-18  |  43KB  |  1,632 lines

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