1 ## lib/trollop.rb -- trollop command-line processing library
2 ## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net)
3 ## Copyright:: Copyright 2007 William Morgan
4 ## License:: the same terms as ruby itself
12 ## Thrown by Parser in the event of a commandline error. Not needed if
13 ## you're using the Trollop::options entry.
14 class CommandlineError < StandardError; end
16 ## Thrown by Parser if the user passes in '-h' or '--help'. Handled
17 ## automatically by Trollop#options.
18 class HelpNeeded < StandardError; end
20 ## Thrown by Parser if the user passes in '-h' or '--version'. Handled
21 ## automatically by Trollop#options.
22 class VersionNeeded < StandardError; end
24 ## Regex for floating point numbers
25 FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/
27 ## Regex for parameters
28 PARAM_RE = /^-(-|\.$|[^\d\.])/
30 ## The commandline parser. In typical usage, the methods in this class
31 ## will be handled internally by Trollop::options. In this case, only the
32 ## #opt, #banner and #version, #depends, and #conflicts methods will
33 ## typically be called.
35 ## If you want to instantiate this class yourself (for more complicated
36 ## argument-parsing logic), call #parse to actually produce the output hash,
37 ## and consider calling it from within
38 ## Trollop::with_standard_exception_handling.
41 ## The set of values that indicate a flag option when passed as the
42 ## +:type+ parameter of #opt.
43 FLAG_TYPES = [:flag, :bool, :boolean]
45 ## The set of values that indicate a single-parameter (normal) option when
46 ## passed as the +:type+ parameter of #opt.
48 ## A value of +io+ corresponds to a readable IO resource, including
49 ## a filename, URI, or the strings 'stdin' or '-'.
50 SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date]
52 ## The set of values that indicate a multiple-parameter option (i.e., that
53 ## takes multiple space-separated values on the commandline) when passed as
54 ## the +:type+ parameter of #opt.
55 MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
57 ## The complete set of legal values for the +:type+ parameter of #opt.
58 TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
60 INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc:
62 ## The values from the commandline that were not interpreted by #parse.
63 attr_reader :leftovers
65 ## The complete configuration hashes for each option. (Mainly useful
69 ## Initializes the parser, and instance-evaluates any block given.
79 @stop_on_unknown = false
81 #instance_eval(&b) if b # can't take arguments
82 cloaker(&b).bind(self).call(*a) if b
85 ## Define an option. +name+ is the option name, a unique identifier
86 ## for the option that you will use internally, which should be a
87 ## symbol or a string. +desc+ is a string description which will be
88 ## displayed in help messages.
90 ## Takes the following optional arguments:
92 ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
93 ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
94 ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
95 ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
96 ## [+:required+] If set to +true+, the argument must be provided on the commandline.
97 ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
99 ## Note that there are two types of argument multiplicity: an argument
100 ## can take multiple values, e.g. "--arg 1 2 3". An argument can also
101 ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
103 ## Arguments that take multiple values should have a +:type+ parameter
104 ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
105 ## value of an array of the correct type (e.g. [String]). The
106 ## value of this argument will be an array of the parameters on the
109 ## Arguments that can occur multiple times should be marked with
110 ## +:multi+ => +true+. The value of this argument will also be an array.
111 ## In contrast with regular non-multi options, if not specified on
112 ## the commandline, the default value will be [], not nil.
114 ## These two attributes can be combined (e.g. +:type+ => +:strings+,
115 ## +:multi+ => +true+), in which case the value of the argument will be
116 ## an array of arrays.
118 ## There's one ambiguous case to be aware of: when +:multi+: is true and a
119 ## +:default+ is set to an array (of something), it's ambiguous whether this
120 ## is a multi-value argument as well as a multi-occurrence argument.
121 ## In thise case, Trollop assumes that it's not a multi-value argument.
122 ## If you want a multi-value, multi-occurrence argument with a default
123 ## value, you must specify +:type+ as well.
125 def opt name, desc="", opts={}
126 raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
129 opts[:type] = # normalize
131 when :boolean, :bool; :flag
133 when :integers; :ints
135 when :doubles; :floats
137 case opts[:type].name
138 when 'TrueClass', 'FalseClass'; :flag
139 when 'String'; :string
145 raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
149 raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
153 ## for options with :multi => true, an array default doesn't imply
154 ## a multi-valued argument. for that you have to specify a :type
155 ## as well. (this is how we disambiguate an ambiguous situation;
156 ## see the docs for Parser#opt for details.)
157 disambiguated_default = if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
164 case disambiguated_default
167 when TrueClass, FalseClass; :flag
172 if opts[:default].empty?
173 raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
175 case opts[:default][0] # the first element determines the types
177 when Numeric; :floats
178 when String; :strings
182 raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
186 raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
189 raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default
191 opts[:type] = opts[:type] || type_from_default || :flag
194 opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
195 opts[:long] = case opts[:long]
196 when /^--([^-].*)$/; $1
197 when /^[^-]/; opts[:long]
198 else; raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
200 raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
203 opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
204 opts[:short] = case opts[:short]
206 when nil, :none, /^.$/; opts[:short]
207 else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
211 raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
212 raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
215 ## fill in :default for flags
216 opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
218 ## autobox :default for :multi (multi-occurrence) arguments
219 opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
222 opts[:multi] ||= false
225 @long[opts[:long]] = name
226 @short[opts[:short]] = name if opts[:short] && opts[:short] != :none
228 @order << [:opt, name]
231 ## Sets the version string. If set, the user can request the version
232 ## on the commandline. Should probably be of the form "<program name>
233 ## <version number>".
234 def version s=nil; @version = s if s; @version end
236 ## Adds text to the help display. Can be interspersed with calls to
237 ## #opt to build a multi-section help page.
238 def banner s; @order << [:text, s] end
241 ## Marks two (or more!) options as requiring each other. Only handles
242 ## undirected (i.e., mutual) dependencies. Directed dependencies are
243 ## better modeled with Trollop::die.
245 syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
246 @constraints << [:depends, syms]
249 ## Marks two (or more!) options as conflicting.
251 syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
252 @constraints << [:conflicts, syms]
255 ## Defines a set of words which cause parsing to terminate when
256 ## encountered, such that any options to the left of the word are
257 ## parsed as usual, and options to the right of the word are left
260 ## A typical use case would be for subcommand support, where these
261 ## would be set to the list of subcommands. A subsequent Trollop
262 ## invocation would then be used to parse subcommand options, after
263 ## shifting the subcommand off of ARGV.
265 @stop_words = [*words].flatten
268 ## Similar to #stop_on, but stops on any unknown word when encountered
269 ## (unless it is a parameter for an argument). This is useful for
270 ## cases where you don't know the set of subcommands ahead of time,
271 ## i.e., without first parsing the global options.
273 @stop_on_unknown = true
276 ## Parses the commandline. Typically called by Trollop::options,
277 ## but you can call it directly if you need more control.
279 ## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
280 def parse cmdline=ARGV
284 opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
285 opt :help, "Show this message" unless @specs[:help] || @long["help"]
287 @specs.each do |sym, opts|
288 required[sym] = true if opts[:required]
289 vals[sym] = opts[:default]
290 vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
293 resolve_default_short_options!
297 @leftovers = each_arg cmdline do |arg, params|
298 ## handle --no- forms
299 arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
306 when /^-([^-])$/; @short[$1]
307 when /^--([^-]\S*)$/; @long[$1] || @long["no-#{$1}"]
308 else; raise CommandlineError, "invalid argument syntax: '#{arg}'"
311 sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments
313 raise CommandlineError, "unknown argument '#{arg}'" unless sym
315 if given_args.include?(sym) && !@specs[sym][:multi]
316 raise CommandlineError, "option '#{arg}' specified multiple times"
319 given_args[sym] ||= {}
320 given_args[sym][:arg] = arg
321 given_args[sym][:negative_given] = negative_given
322 given_args[sym][:params] ||= []
324 # The block returns the number of parameters taken.
328 if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
329 given_args[sym][:params] << params[0, 1] # take the first parameter
331 elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
332 given_args[sym][:params] << params # take all the parameters
333 num_params_taken = params.size
340 ## check for version and help args
341 raise VersionNeeded if given_args.include? :version
342 raise HelpNeeded if given_args.include? :help
344 ## check constraint satisfaction
345 @constraints.each do |type, syms|
346 constraint_sym = syms.find { |sym| given_args[sym] }
347 next unless constraint_sym
351 syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
353 syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
357 required.each do |sym, val|
358 raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
362 given_args.each do |sym, given_data|
363 arg, params, negative_given = given_data.values_at :arg, :params, :negative_given
366 raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
368 vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
372 vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
374 vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
376 vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
377 when :string, :strings
378 vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
380 vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
382 vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
385 if SINGLE_ARG_TYPES.include?(opts[:type])
386 unless opts[:multi] # single parameter
387 vals[sym] = vals[sym][0][0]
388 else # multiple options, each with a single parameter
389 vals[sym] = vals[sym].map { |p| p[0] }
391 elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
392 vals[sym] = vals[sym][0] # single option, with multiple parameters
394 # else: multiple options, with multiple parameters
397 ## modify input in place with only those
398 ## arguments we didn't process
400 @leftovers.each { |l| cmdline << l }
402 ## allow openstruct-style accessors
404 def method_missing(m, *args)
405 self[m] || self[m.to_s]
411 def parse_date_parameter param, arg #:nodoc:
414 time = Chronic.parse(param)
416 # chronic is not available
418 time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
420 raise CommandlineError, "option '#{arg}' needs a date"
424 ## Print the help message to +stream+.
425 def educate stream=$stdout
426 width # hack: calculate it now; otherwise we have to be careful not to
427 # call this unless the cursor's at the beginning of a line.
429 @specs.each do |name, spec|
430 left[name] = "--#{spec[:long]}" +
431 (spec[:type] == :flag && spec[:default] ? ", --no-#{spec[:long]}" : "") +
432 (spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
438 when :strings; " <s+>"
440 when :floats; " <f+>"
441 when :io; " <filename/uri>"
442 when :ios; " <filename/uri+>"
443 when :date; " <date>"
444 when :dates; " <date+>"
448 leftcol_width = left.values.map { |s| s.length }.max || 0
449 rightcol_start = leftcol_width + 6 # spaces
451 unless @order.size > 0 && @order.first.first == :text
452 stream.puts "#@version\n" if @version
453 stream.puts "Options:"
456 @order.each do |what, opt|
458 stream.puts wrap(opt)
463 stream.printf " %#{leftcol_width}s: ", left[opt]
464 desc = spec[:desc] + begin
465 default_s = case spec[:default]
466 when $stdout; "<stdout>"
467 when $stdin; "<stdin>"
468 when $stderr; "<stderr>"
470 spec[:default].join(", ")
476 if spec[:desc] =~ /\.$/
477 " (Default: #{default_s})"
479 " (default: #{default_s})"
485 stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
490 @width ||= if $stdout.tty?
505 def wrap str, opts={} # :nodoc:
509 str.split("\n").map { |s| wrap_line s, opts }.flatten
513 ## The per-parser version of Trollop::die (see that for documentation).
516 $stderr.puts "Error: argument --#{@specs[arg][:long]} #{msg}."
518 $stderr.puts "Error: #{arg}."
520 $stderr.puts "Try --help for help."
526 ## yield successive arg, parameter pairs
531 until i >= args.length
532 if @stop_words.member? args[i]
533 remains += args[i .. -1]
537 when /^--$/ # arg terminator
538 remains += args[(i + 1) .. -1]
540 when /^--(\S+?)=(.*)$/ # long argument with equals
541 yield "--#{$1}", [$2]
543 when /^--(\S+)$/ # long argument
544 params = collect_argument_parameters(args, i + 1)
546 num_params_taken = yield args[i], params
547 unless num_params_taken
549 remains += args[i + 1 .. -1]
555 i += 1 + num_params_taken
556 else # long argument no parameter
560 when /^-(\S+)$/ # one or more short arguments
561 shortargs = $1.split(//)
562 shortargs.each_with_index do |a, j|
563 if j == (shortargs.length - 1)
564 params = collect_argument_parameters(args, i + 1)
566 num_params_taken = yield "-#{a}", params
567 unless num_params_taken
569 remains += args[i + 1 .. -1]
575 i += 1 + num_params_taken
576 else # argument no parameter
586 remains += args[i .. -1]
598 def parse_integer_parameter param, arg
599 raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^\d+$/
603 def parse_float_parameter param, arg
604 raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
608 def parse_io_parameter param, arg
610 when /^(stdin|-)$/i; $stdin
615 rescue SystemCallError => e
616 raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
621 def collect_argument_parameters args, start_at
624 while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
631 def resolve_default_short_options!
632 @order.each do |type, name|
633 next unless type == :opt
637 c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
638 if c # found a character to use
645 def wrap_line str, opts={}
646 prefix = opts[:prefix] || 0
647 width = opts[:width] || (self.width - 1)
650 until start > str.length
652 if start + width >= str.length
655 x = str.rindex(/\s/, start + width)
656 x = str.index(/\s/, start) if x && x < start
659 ret << (ret.empty? ? "" : " " * prefix) + str[start ... nextt]
665 ## instance_eval but with ability to handle block arguments
666 ## thanks to _why: http://redhanded.hobix.com/inspect/aBlockCostume.html
668 (class << self; self; end).class_eval do
669 define_method :cloaker_, &b
670 meth = instance_method :cloaker_
671 remove_method :cloaker_
677 ## The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
678 ## passes the block to it, then parses +args+ with it, handling any errors or
679 ## requests for help or version information appropriately (and then exiting).
680 ## Modifies +args+ in place. Returns a hash of option values.
682 ## The block passed in should contain zero or more calls to +opt+
683 ## (Parser#opt), zero or more calls to +text+ (Parser#text), and
684 ## probably a call to +version+ (Parser#version).
686 ## The returned block contains a value for every option specified with
687 ## +opt+. The value will be the value given on the commandline, or the
688 ## default value if the option was not specified on the commandline. For
689 ## every option specified on the commandline, a key "<option
690 ## name>_given" will also be set in the hash.
695 ## opts = Trollop::options do
696 ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
697 ## opt :name, "Monkey name", :type => :string # a string --name <s>, defaulting to nil
698 ## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
701 ## ## if called with no arguments
702 ## p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false}
704 ## ## if called with --monkey
705 ## p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true}
707 ## See more examples at http://trollop.rubyforge.org.
708 def options args=ARGV, *a, &b
709 @last_parser = Parser.new(*a, &b)
710 with_standard_exception_handling(@last_parser) { @last_parser.parse args }
713 ## If Trollop::options doesn't do quite what you want, you can create a Parser
714 ## object and call Parser#parse on it. That method will throw CommandlineError,
715 ## HelpNeeded and VersionNeeded exceptions when necessary; if you want to
716 ## have these handled for you in the standard manner (e.g. show the help
717 ## and then exit upon an HelpNeeded exception), call your code from within
718 ## a block passed to this method.
720 ## Note that this method will call System#exit after handling an exception!
725 ## p = Trollop::Parser.new do
726 ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
727 ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
730 ## opts = Trollop::with_standard_exception_handling p do
732 ## raise Trollop::HelpNeeded if ARGV.empty? # show help screen
736 ## Requires passing in the parser object.
738 def with_standard_exception_handling parser
741 rescue CommandlineError => e
742 $stderr.puts "Error: #{e.message}."
743 $stderr.puts "Try --help for help."
754 ## Informs the user that their usage of 'arg' was wrong, as detailed by
755 ## 'msg', and dies. Example:
758 ## opt :volume, :default => 0.0
761 ## die :volume, "too loud" if opts[:volume] > 10.0
762 ## die :volume, "too soft" if opts[:volume] < 0.1
764 ## In the one-argument case, simply print that message, a notice
765 ## about -h, and die. Example:
768 ## opt :whatever # ...
771 ## Trollop::die "need at least one filename" if ARGV.empty?
774 @last_parser.die arg, msg
776 raise ArgumentError, "Trollop::die can only be called after Trollop::options"
780 module_function :options, :die, :with_standard_exception_handling