home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / ruby / 1.8 / optparse.rb < prev    next >
Encoding:
Ruby Source  |  2006-08-04  |  45.3 KB  |  1,728 lines

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