PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/optparse.rb

https://github.com/EarthJem/ruby
Ruby | 1943 lines | 1028 code | 177 blank | 738 comment | 128 complexity | fa101a29fd5be340f825a1e77c1dfd54 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file