diff options
Diffstat (limited to 'doc/optparse')
| -rw-r--r-- | doc/optparse/.document | 1 | ||||
| -rw-r--r-- | doc/optparse/argument_converters.rdoc | 92 | ||||
| -rw-r--r-- | doc/optparse/creates_option.rdoc | 4 | ||||
| -rw-r--r-- | doc/optparse/option_params.rdoc | 81 | ||||
| -rw-r--r-- | doc/optparse/ruby/argument_abbreviation.rb | 9 | ||||
| -rw-r--r-- | doc/optparse/ruby/basic.rb | 17 | ||||
| -rw-r--r-- | doc/optparse/ruby/help.rb | 18 | ||||
| -rw-r--r-- | doc/optparse/ruby/help_banner.rb | 7 | ||||
| -rw-r--r-- | doc/optparse/ruby/help_format.rb | 25 | ||||
| -rw-r--r-- | doc/optparse/ruby/help_program_name.rb | 7 | ||||
| -rw-r--r-- | doc/optparse/ruby/match_converter.rb | 9 | ||||
| -rw-r--r-- | doc/optparse/ruby/matched_values.rb | 6 | ||||
| -rw-r--r-- | doc/optparse/ruby/name_abbrev.rb (renamed from doc/optparse/ruby/abbreviation.rb) | 0 | ||||
| -rw-r--r-- | doc/optparse/ruby/parse.rb | 13 | ||||
| -rw-r--r-- | doc/optparse/ruby/parse_bang.rb | 13 | ||||
| -rw-r--r-- | doc/optparse/tutorial.rdoc | 550 |
16 files changed, 732 insertions, 120 deletions
diff --git a/doc/optparse/.document b/doc/optparse/.document new file mode 100644 index 0000000000..96dfc7779f --- /dev/null +++ b/doc/optparse/.document @@ -0,0 +1 @@ +*.rdoc diff --git a/doc/optparse/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc index fc5a0152a3..532729871c 100644 --- a/doc/optparse/argument_converters.rdoc +++ b/doc/optparse/argument_converters.rdoc @@ -1,7 +1,7 @@ == Argument Converters An option can specify that its argument is to be converted -from the default \String to an instance of another class. +from the default +String+ to an instance of another class. === Contents @@ -27,13 +27,13 @@ from the default \String to an instance of another class. === Built-In Argument Converters -\OptionParser has a number of built-in argument converters, ++OptionParser+ has a number of built-in argument converters, which are demonstrated below. -==== \Date +==== +Date+ File +date.rb+ -defines an option whose argument is to be converted to a \Date object. +defines an option whose argument is to be converted to a +Date+ object. The argument is converted by method Date#parse. :include: ruby/date.rb @@ -47,10 +47,10 @@ Executions: $ ruby date.rb --date "3rd Feb 2001" [#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, Date] -==== \DateTime +==== +DateTime+ File +datetime.rb+ -defines an option whose argument is to be converted to a \DateTime object. +defines an option whose argument is to be converted to a +DateTime+ object. The argument is converted by method DateTime#parse. :include: ruby/datetime.rb @@ -64,10 +64,10 @@ Executions: $ ruby datetime.rb --datetime "3rd Feb 2001 04:05:06 PM" [#<DateTime: 2001-02-03T16:05:06+00:00 ((2451944j,57906s,0n),+0s,2299161j)>, DateTime] -==== \Time +==== +Time+ File +time.rb+ -defines an option whose argument is to be converted to a \Time object. +defines an option whose argument is to be converted to a +Time+ object. The argument is converted by method Time#httpdate or Time#parse. :include: ruby/time.rb @@ -79,10 +79,10 @@ Executions: $ ruby time.rb --time 2010-10-31 [2010-10-31 00:00:00 -0500, Time] -==== \URI +==== +URI+ File +uri.rb+ -defines an option whose argument is to be converted to a \URI object. +defines an option whose argument is to be converted to a +URI+ object. The argument is converted by method URI#parse. :include: ruby/uri.rb @@ -96,10 +96,10 @@ Executions: $ ruby uri.rb --uri file://~/var [#<URI::File file://~/var>, URI::File] -==== \Shellwords +==== +Shellwords+ File +shellwords.rb+ -defines an option whose argument is to be converted to an \Array object by method +defines an option whose argument is to be converted to an +Array+ object by method Shellwords#shellwords. :include: ruby/shellwords.rb @@ -111,10 +111,10 @@ Executions: $ ruby shellwords.rb --shellwords "here are 'two words'" [["here", "are", "two words"], Array] -==== \Integer +==== +Integer+ File +integer.rb+ -defines an option whose argument is to be converted to an \Integer object. +defines an option whose argument is to be converted to an +Integer+ object. The argument is converted by method Kernel#Integer. :include: ruby/integer.rb @@ -132,10 +132,10 @@ Executions: $ ruby integer.rb --integer 0b100 [4, Integer] -==== \Float +==== +Float+ File +float.rb+ -defines an option whose argument is to be converted to a \Float object. +defines an option whose argument is to be converted to a +Float+ object. The argument is converted by method Kernel#Float. :include: ruby/float.rb @@ -151,11 +151,11 @@ Executions: $ ruby float.rb --float 1.234E-2 [0.01234, Float] -==== \Numeric +==== +Numeric+ File +numeric.rb+ defines an option whose argument is to be converted to an instance -of \Rational, \Float, or \Integer. +of +Rational+, +Float+, or +Integer+. The argument is converted by method Kernel#Rational, Kernel#Float, or Kernel#Integer. @@ -170,10 +170,10 @@ Executions: $ ruby numeric.rb --numeric 3 [3, Integer] -==== \DecimalInteger +==== +DecimalInteger+ File +decimal_integer.rb+ -defines an option whose argument is to be converted to an \Integer object. +defines an option whose argument is to be converted to an +Integer+ object. The argument is converted by method Kernel#Integer. :include: ruby/decimal_integer.rb @@ -192,10 +192,10 @@ Executions: $ ruby decimal_integer.rb --decimal_integer -0100 [-100, Integer] -==== \OctalInteger +==== +OctalInteger+ File +octal_integer.rb+ -defines an option whose argument is to be converted to an \Integer object. +defines an option whose argument is to be converted to an +Integer+ object. The argument is converted by method Kernel#Integer. :include: ruby/octal_integer.rb @@ -212,11 +212,11 @@ Executions: $ ruby octal_integer.rb --octal_integer 0100 [64, Integer] -==== \DecimalNumeric +==== +DecimalNumeric+ File +decimal_numeric.rb+ -defines an option whose argument is to be converted to an \Integer object. -The argument is converted by method {Kernel#Integer +defines an option whose argument is to be converted to an +Integer+ object. +The argument is converted by method Kernel#Integer :include: ruby/decimal_numeric.rb @@ -232,7 +232,7 @@ Executions: $ ruby decimal_numeric.rb --decimal_numeric 0100 [64, Integer] -==== \TrueClass +==== +TrueClass+ File +true_class.rb+ defines an option whose argument is to be converted to +true+ or +false+. @@ -259,7 +259,7 @@ Executions: $ ruby true_class.rb --true_class nil [false, FalseClass] -==== \FalseClass +==== +FalseClass+ File +false_class.rb+ defines an option whose argument is to be converted to +true+ or +false+. @@ -286,10 +286,10 @@ Executions: $ ruby false_class.rb --false_class + [true, TrueClass] -==== \Object +==== +Object+ File +object.rb+ -defines an option whose argument is not to be converted from \String. +defines an option whose argument is not to be converted from +String+. :include: ruby/object.rb @@ -300,10 +300,10 @@ Executions: $ ruby object.rb --object nil ["nil", String] -==== \String +==== +String+ File +string.rb+ -defines an option whose argument is not to be converted from \String. +defines an option whose argument is not to be converted from +String+. :include: ruby/string.rb @@ -314,10 +314,10 @@ Executions: $ ruby string.rb --string nil ["nil", String] -==== \Array +==== +Array+ File +array.rb+ -defines an option whose argument is to be converted from \String +defines an option whose argument is to be converted from +String+ to an array of strings, based on comma-separated substrings. :include: ruby/array.rb @@ -331,10 +331,10 @@ Executions: $ ruby array.rb --array "foo, bar, baz" [["foo", " bar", " baz"], Array] -==== \Regexp +==== +Regexp+ File +regexp.rb+ -defines an option whose argument is to be converted to a \Regexp object. +defines an option whose argument is to be converted to a +Regexp+ object. :include: ruby/regexp.rb @@ -345,8 +345,14 @@ Executions: === Custom Argument Converters You can create custom argument converters. -To create a custom converter, call OptionParser#accept with a class argument, -along with a block that converts the argument and returns the converted value. +To create a custom converter, call OptionParser#accept with: + +- An identifier, which may be any object. +- An optional match pattern, which defaults to <tt>/.*/m</tt>. +- A block that accepts the argument and returns the converted value. + +This custom converter accepts any argument and converts it, +if possible, to a +Complex+ object. :include: ruby/custom_converter.rb @@ -360,3 +366,15 @@ Executions: [(1+2i), Complex] $ ruby custom_converter.rb --complex 0.3-0.5i [(0.3-0.5i), Complex] + +This custom converter accepts any 1-word argument +and capitalizes it, if possible. + + :include: ruby/match_converter.rb + +Executions: + + $ ruby match_converter.rb --capitalize foo + ["Foo", String] + $ ruby match_converter.rb --capitalize "foo bar" + match_converter.rb:9:in '<main>': invalid argument: --capitalize foo bar (OptionParser::InvalidArgument) diff --git a/doc/optparse/creates_option.rdoc b/doc/optparse/creates_option.rdoc index aaeb72d745..ab672d5124 100644 --- a/doc/optparse/creates_option.rdoc +++ b/doc/optparse/creates_option.rdoc @@ -1,7 +1,7 @@ Creates an option from the given parameters +params+. -See {Parameters for New Options}[./option_params_rdoc.html]. +See {Parameters for New Options}[optparse/option_params.rdoc]. The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. -See {Option Handlers}[./option_params_rdoc.html#label-Option+Handlers]. +See {Option Handlers}[optparse/option_params.rdoc#label-Option+Handlers]. diff --git a/doc/optparse/option_params.rdoc b/doc/optparse/option_params.rdoc index 0d06b41e7d..575ee66cdb 100644 --- a/doc/optparse/option_params.rdoc +++ b/doc/optparse/option_params.rdoc @@ -1,6 +1,6 @@ == Parameters for New Options -Option-creating methods in \OptionParser +Option-creating methods in +OptionParser+ accept arguments that determine the behavior of a new option: - OptionParser#on @@ -31,7 +31,7 @@ Contents: - {Long Names with Optional Arguments}[#label-Long+Names+with+Optional+Arguments] - {Long Names with Negation}[#label-Long+Names+with+Negation] - {Mixed Names}[#label-Mixed+Names] -- {Argument Styles}[#label-Argument+Styles] +- {Argument Strings}[#label-Argument+Strings] - {Argument Values}[#label-Argument+Values] - {Explicit Argument Values}[#label-Explicit+Argument+Values] - {Explicit Values in Array}[#label-Explicit+Values+in+Array] @@ -43,7 +43,6 @@ Contents: - {Handler Blocks}[#label-Handler+Blocks] - {Handler Procs}[#label-Handler+Procs] - {Handler Methods}[#label-Handler+Methods] -- {Terminators}[#label-Terminators] === Option Names @@ -92,7 +91,7 @@ Executions: Usage: short_required [options] -xXXX Short name with required argument $ ruby short_required.rb -x - short_required.rb:6:in `<main>': missing argument: -x (OptionParser::MissingArgument) + short_required.rb:6:in '<main>': missing argument: -x (OptionParser::MissingArgument) $ ruby short_required.rb -x FOO ["-x", "FOO"] @@ -182,7 +181,7 @@ Executions: Usage: long_required [options] --xxx XXX Long name with required argument $ ruby long_required.rb --xxx - long_required.rb:6:in `<main>': missing argument: --xxx (OptionParser::MissingArgument) + long_required.rb:6:in '<main>': missing argument: --xxx (OptionParser::MissingArgument) $ ruby long_required.rb --xxx FOO ["--xxx", "FOO"] @@ -244,11 +243,11 @@ Usage: mixed_names [options] $ ruby mixed_names.rb --xxx ["--xxx", true] $ ruby mixed_names.rb -y - mixed_names.rb:12:in `<main>': missing argument: -y (OptionParser::MissingArgument) + mixed_names.rb:12:in '<main>': missing argument: -y (OptionParser::MissingArgument) $ ruby mixed_names.rb -y FOO ["--yyy", "FOO"] $ ruby mixed_names.rb --yyy - mixed_names.rb:12:in `<main>': missing argument: --yyy (OptionParser::MissingArgument) + mixed_names.rb:12:in '<main>': missing argument: --yyy (OptionParser::MissingArgument) $ ruby mixed_names.rb --yyy BAR ["--yyy", "BAR"] $ ruby mixed_names.rb -z @@ -280,7 +279,7 @@ Executions: Usage: argument_keywords [options] -x, --xxx Required argument $ ruby argument_styles.rb --xxx - argument_styles.rb:6:in `<main>': missing argument: --xxx (OptionParser::MissingArgument) + argument_styles.rb:6:in '<main>': missing argument: --xxx (OptionParser::MissingArgument) $ ruby argument_styles.rb --xxx FOO ["--xxx", "FOO"] @@ -299,7 +298,7 @@ Executions: Usage: argument_strings [options] -x, --xxx=XXX Required argument $ ruby argument_strings.rb --xxx - argument_strings.rb:9:in `<main>': missing argument: --xxx (OptionParser::MissingArgument) + argument_strings.rb:9:in '<main>': missing argument: --xxx (OptionParser::MissingArgument) $ ruby argument_strings.rb --xxx FOO ["--xxx", "FOO"] @@ -319,7 +318,7 @@ You can specify argument values in either of two ways: ===== Explicit Values in Array You can specify explicit argument values in an array of strings. -The argument value must be one of those strings. +The argument value must be one of those strings, or an unambiguous abbreviation. File +explicit_array_values.rb+ defines options with explicit argument values. @@ -332,20 +331,24 @@ Executions: -xXXX Values for required argument -y [YYY] Values for optional argument $ ruby explicit_array_values.rb -x - explicit_array_values.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) + explicit_array_values.rb:9:in '<main>': missing argument: -x (OptionParser::MissingArgument) $ ruby explicit_array_values.rb -x foo ["-x", "foo"] + $ ruby explicit_array_values.rb -x f + ["-x", "foo"] $ ruby explicit_array_values.rb -x bar ["-x", "bar"] + $ ruby explicit_array_values.rb -y ba + explicit_array_values.rb:9:in '<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) $ ruby explicit_array_values.rb -x baz - explicit_array_values.rb:9:in `<main>': invalid argument: -x baz (OptionParser::InvalidArgument) + explicit_array_values.rb:9:in '<main>': invalid argument: -x baz (OptionParser::InvalidArgument) ===== Explicit Values in Hash You can specify explicit argument values in a hash with string keys. -The value passed must be one of those keys, -and the value yielded will be the value for that key. +The value passed must be one of those keys, or an unambiguous abbreviation; +the value yielded will be the value for that key. File +explicit_hash_values.rb+ defines options with explicit argument values. @@ -358,26 +361,31 @@ Executions: -xXXX Values for required argument -y [YYY] Values for optional argument $ ruby explicit_hash_values.rb -x - explicit_hash_values.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) + explicit_hash_values.rb:9:in '<main>': missing argument: -x (OptionParser::MissingArgument) $ ruby explicit_hash_values.rb -x foo ["-x", 0] + $ ruby explicit_hash_values.rb -x f + ["-x", 0] $ ruby explicit_hash_values.rb -x bar ["-x", 1] $ ruby explicit_hash_values.rb -x baz - explicit_hash_values.rb:9:in `<main>': invalid argument: -x baz (OptionParser::InvalidArgument) + explicit_hash_values.rb:9:in '<main>': invalid argument: -x baz (OptionParser::InvalidArgument) $ ruby explicit_hash_values.rb -y ["-y", nil] $ ruby explicit_hash_values.rb -y baz ["-y", 2] $ ruby explicit_hash_values.rb -y bat ["-y", 3] + $ ruby explicit_hash_values.rb -y ba + explicit_hash_values.rb:9:in '<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) $ ruby explicit_hash_values.rb -y bam ["-y", nil] ==== Argument Value Patterns You can restrict permissible argument values -by specifying a Regexp that the given argument must match. +by specifying a +Regexp+ that the given argument must match, +or a +Range+ or +Array+ that the converted value must be included in. File +matched_values.rb+ defines options with matched argument values. @@ -388,22 +396,32 @@ Executions: $ ruby matched_values.rb --help Usage: matched_values [options] --xxx XXX Matched values + --yyy YYY Check by range + --zzz ZZZ Check by list $ ruby matched_values.rb --xxx foo ["--xxx", "foo"] $ ruby matched_values.rb --xxx FOO ["--xxx", "FOO"] $ ruby matched_values.rb --xxx bar - matched_values.rb:6:in `<main>': invalid argument: --xxx bar (OptionParser::InvalidArgument) + matched_values.rb:12:in '<main>': invalid argument: --xxx bar (OptionParser::InvalidArgument) + $ ruby matched_values.rb --yyy 1 + ["--yyy", 1] + $ ruby matched_values.rb --yyy 4 + matched_values.rb:12:in '<main>': invalid argument: --yyy 4 (OptionParser::InvalidArgument) + $ ruby matched_values.rb --zzz 1 + ["--zzz", 1] + $ ruby matched_values.rb --zzz 2 + matched_values.rb:12:in '<main>': invalid argument: --zzz 2 (OptionParser::InvalidArgument) === Argument Converters An option can specify that its argument is to be converted -from the default \String to an instance of another class. +from the default +String+ to an instance of another class. There are a number of built-in converters. You can also define custom converters. -See {Argument Converters}[./argument_converters_rdoc.html]. +See {Argument Converters}[./argument_converters.rdoc]. === Descriptions @@ -411,7 +429,7 @@ A description parameter is any string parameter that is not recognized as an {option name}[#label-Option+Names] or a {terminator}[#label-Terminators]; -in other words, it does not begin with a hypnen. +in other words, it does not begin with a hyphen. You may give any number of description parameters; each becomes a line in the text generated by option <tt>--help</tt>. @@ -446,7 +464,7 @@ when the option is encountered. The handler may be: ==== Handler Blocks -An option hadler may be a block. +An option handler may be a block. File +block.rb+ defines an option that has a handler block. @@ -500,22 +518,3 @@ Executions: ["Handler method for -xxx called with value:", true] $ ruby method.rb --yyy FOO ["Handler method for -yyy called with value:", "FOO"] - -=== Terminators - -And finally, the terminator parameter <tt>--</tt> tells the options parser -to ignore any options farther to the right. -This can be useful if there are options not meant for the current program. - -File +terminator.rb+ defines one option <tt>--my_option</tt>. - - :include: ruby/terminator.rb - -The first execution fails because <tt>--nosuch</tt> is not a defined option; -the second succeeds because <tt>--</tt> causes that option to be ignored: - - $ ruby terminator.rb --my_option FOO --other_option BAR - ["FOO", String] - terminator.rb:6:in `<main>': invalid option: --other_option (OptionParser::InvalidOption) - $ ruby terminator.rb --my_option FOO -- --other_option BAR - ["FOO", String] diff --git a/doc/optparse/ruby/argument_abbreviation.rb b/doc/optparse/ruby/argument_abbreviation.rb new file mode 100644 index 0000000000..49007ebe69 --- /dev/null +++ b/doc/optparse/ruby/argument_abbreviation.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx=VALUE', %w[ABC def], 'Argument abbreviations') do |value| + p ['--xxx', value] +end +parser.on('-y', '--yyy=VALUE', {"abc"=>"XYZ", def: "FOO"}, 'Argument abbreviations') do |value| + p ['--yyy', value] +end +parser.parse! diff --git a/doc/optparse/ruby/basic.rb b/doc/optparse/ruby/basic.rb new file mode 100644 index 0000000000..91d37627c0 --- /dev/null +++ b/doc/optparse/ruby/basic.rb @@ -0,0 +1,17 @@ +# Require the OptionParser code. +require 'optparse' +# Create an OptionParser object. +parser = OptionParser.new +# Define one or more options. +parser.on('-x', 'Whether to X') do |value| + p ['x', value] +end +parser.on('-y', 'Whether to Y') do |value| + p ['y', value] +end +parser.on('-z', 'Whether to Z') do |value| + p ['z', value] +end +# Parse the command line and return pared-down ARGV. +p parser.parse! + diff --git a/doc/optparse/ruby/help.rb b/doc/optparse/ruby/help.rb new file mode 100644 index 0000000000..95bcde1d77 --- /dev/null +++ b/doc/optparse/ruby/help.rb @@ -0,0 +1,18 @@ +require 'optparse' +parser = OptionParser.new +parser.on( + '-x', '--xxx', + 'Adipiscing elit. Aenean commodo ligula eget.', + 'Aenean massa. Cum sociis natoque penatibus', + ) +parser.on( + '-y', '--yyy YYY', + 'Lorem ipsum dolor sit amet, consectetuer.' +) +parser.on( + '-z', '--zzz [ZZZ]', + 'Et magnis dis parturient montes, nascetur', + 'ridiculus mus. Donec quam felis, ultricies', + 'nec, pellentesque eu, pretium quis, sem.', + ) +parser.parse! diff --git a/doc/optparse/ruby/help_banner.rb b/doc/optparse/ruby/help_banner.rb new file mode 100644 index 0000000000..0943a3e029 --- /dev/null +++ b/doc/optparse/ruby/help_banner.rb @@ -0,0 +1,7 @@ +require 'optparse' +parser = OptionParser.new +parser.banner = "Usage: ruby help_banner.rb" +parser.parse! + + + diff --git a/doc/optparse/ruby/help_format.rb b/doc/optparse/ruby/help_format.rb new file mode 100644 index 0000000000..a2f1e85b00 --- /dev/null +++ b/doc/optparse/ruby/help_format.rb @@ -0,0 +1,25 @@ +require 'optparse' +parser = OptionParser.new( + 'ruby help_format.rb [options]', # Banner + 20, # Width of options field + ' ' * 2 # Indentation +) +parser.on( + '-x', '--xxx', + 'Adipiscing elit. Aenean commodo ligula eget.', + 'Aenean massa. Cum sociis natoque penatibus', + ) +parser.on( + '-y', '--yyy YYY', + 'Lorem ipsum dolor sit amet, consectetuer.' +) +parser.on( + '-z', '--zzz [ZZZ]', + 'Et magnis dis parturient montes, nascetur', + 'ridiculus mus. Donec quam felis, ultricies', + 'nec, pellentesque eu, pretium quis, sem.', + ) +parser.parse! + + + diff --git a/doc/optparse/ruby/help_program_name.rb b/doc/optparse/ruby/help_program_name.rb new file mode 100644 index 0000000000..7b3fbff067 --- /dev/null +++ b/doc/optparse/ruby/help_program_name.rb @@ -0,0 +1,7 @@ +require 'optparse' +parser = OptionParser.new +parser.program_name = 'help_program_name.rb' +parser.parse! + + + diff --git a/doc/optparse/ruby/match_converter.rb b/doc/optparse/ruby/match_converter.rb new file mode 100644 index 0000000000..13dc5fcb51 --- /dev/null +++ b/doc/optparse/ruby/match_converter.rb @@ -0,0 +1,9 @@ +require 'optparse/date' +parser = OptionParser.new +parser.accept(:capitalize, /\w*/) do |value| + value.capitalize +end +parser.on('--capitalize XXX', :capitalize) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/optparse/ruby/matched_values.rb b/doc/optparse/ruby/matched_values.rb index f184ca8474..a1aba140e6 100644 --- a/doc/optparse/ruby/matched_values.rb +++ b/doc/optparse/ruby/matched_values.rb @@ -3,4 +3,10 @@ parser = OptionParser.new parser.on('--xxx XXX', /foo/i, 'Matched values') do |value| p ['--xxx', value] end +parser.on('--yyy YYY', Integer, 'Check by range', 1..3) do |value| + p ['--yyy', value] +end +parser.on('--zzz ZZZ', Integer, 'Check by list', [1, 3, 4]) do |value| + p ['--zzz', value] +end parser.parse! diff --git a/doc/optparse/ruby/abbreviation.rb b/doc/optparse/ruby/name_abbrev.rb index b438c1b3dd..b438c1b3dd 100644 --- a/doc/optparse/ruby/abbreviation.rb +++ b/doc/optparse/ruby/name_abbrev.rb diff --git a/doc/optparse/ruby/parse.rb b/doc/optparse/ruby/parse.rb new file mode 100644 index 0000000000..a5d4329484 --- /dev/null +++ b/doc/optparse/ruby/parse.rb @@ -0,0 +1,13 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx') do |value| + p ['--xxx', value] +end +parser.on('--yyy YYY') do |value| + p ['--yyy', value] +end +parser.on('--zzz [ZZZ]') do |value| + p ['--zzz', value] +end +ret = parser.parse(ARGV) +puts "Returned: #{ret} (#{ret.class})" diff --git a/doc/optparse/ruby/parse_bang.rb b/doc/optparse/ruby/parse_bang.rb new file mode 100644 index 0000000000..567bc733cf --- /dev/null +++ b/doc/optparse/ruby/parse_bang.rb @@ -0,0 +1,13 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx') do |value| + p ['--xxx', value] +end +parser.on('--yyy YYY') do |value| + p ['--yyy', value] +end +parser.on('--zzz [ZZZ]') do |value| + p ['--zzz', value] +end +ret = parser.parse! +puts "Returned: #{ret} (#{ret.class})" diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index 7721dc60a2..1134f94ddf 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -1,10 +1,10 @@ == Tutorial -=== Why OptionParser? +=== Why +OptionParser+? When a Ruby program executes, it captures its command-line arguments and options into variable ARGV. -This simple program just prints its \ARGV: +This simple program just prints its +ARGV+: :include: ruby/argv.rb @@ -18,7 +18,7 @@ the command-line options. OptionParser offers methods for parsing and handling those options. -With \OptionParser, you can define options so that for each option: +With +OptionParser+, you can define options so that for each option: - The code that defines the option and code that handles that option are in the same place. @@ -27,32 +27,95 @@ With \OptionParser, you can define options so that for each option: - The argument may be restricted to specified _forms_. - The argument may be restricted to specified _values_. -The class also has: - -- Method #summarize: returns a text summary of the options. -- Method #help: displays automatically-generated help text. +The class also has method #help, which displays automatically-generated help text. === Contents +- {To Begin With}[#label-To+Begin+With] - {Defining Options}[#label-Defining+Options] - {Option Names}[#label-Option+Names] - {Short Option Names}[#label-Short+Option+Names] - {Long Option Names}[#label-Long+Option+Names] - {Mixing Option Names}[#label-Mixing+Option+Names] - - {Command-Line Abbreviations}[#label-Command-Line+Abbreviations] + - {Option Name Abbreviations}[#label-Option+Name+Abbreviations] - {Option Arguments}[#label-Option+Arguments] - {Option with No Argument}[#label-Option+with+No+Argument] - {Option with Required Argument}[#label-Option+with+Required+Argument] - {Option with Optional Argument}[#label-Option+with+Optional+Argument] -- {Keyword Argument <tt>into<tt>}[#label-Keyword+Argument+into] + - {Argument Abbreviations}[#label-Argument+Abbreviations] +- {Argument Values}[#label-Argument+Values] + - {Explicit Argument Values}[#label-Explicit+Argument+Values] + - {Explicit Values in Array}[#label-Explicit+Values+in+Array] + - {Explicit Values in Hash}[#label-Explicit+Values+in+Hash] + - {Argument Value Patterns}[#label-Argument+Value+Patterns] +- {Keyword Argument into}[#label-Keyword+Argument+into] - {Collecting Options}[#label-Collecting+Options] - {Checking for Missing Options}[#label-Checking+for+Missing+Options] - {Default Values for Options}[#label-Default+Values+for+Options] - {Argument Converters}[#label-Argument+Converters] +- {Help}[#label-Help] +- {Top List and Base List}[#label-Top+List+and+Base+List] +- {Methods for Defining Options}[#label-Methods+for+Defining+Options] +- {Parsing}[#label-Parsing] + - {Method parse!}[#label-Method+parse-21] + - {Method parse}[#label-Method+parse] + - {Method order!}[#label-Method+order-21] + - {Method order}[#label-Method+order] + - {Method permute!}[#label-Method+permute-21] + - {Method permute}[#label-Method+permute] + +=== To Begin With + +To use +OptionParser+: + +1. Require the +OptionParser+ code. +2. Create an +OptionParser+ object. +3. Define one or more options. +4. Parse the command line. + +File +basic.rb+ defines three options, <tt>-x</tt>, +<tt>-y</tt>, and <tt>-z</tt>, each with a descriptive string, +and each with a block. + + :include: ruby/basic.rb + +From these defined options, the parser automatically builds help text: + + $ ruby basic.rb --help + Usage: basic [options] + -x Whether to X + -y Whether to Y + -z Whether to Z + +When an option is found during parsing, +the block defined for the option is called with the argument value. +An invalid option raises an exception. + +Method #parse!, which is used most often in this tutorial, +removes from +ARGV+ the options and arguments it finds, +leaving other non-option arguments for the program to handle on its own. +The method returns the possibly-reduced +ARGV+ array. + +Executions: + + $ ruby basic.rb -x -z + ["x", true] + ["z", true] + [] + $ ruby basic.rb -z -y -x + ["z", true] + ["y", true] + ["x", true] + [] + $ ruby basic.rb -x input_file.txt output_file.txt + ["x", true] + ["input_file.txt", "output_file.txt"] + $ ruby basic.rb -a + basic.rb:16:in '<main>': invalid option: -a (OptionParser::InvalidOption) === Defining Options -A common way to define an option in \OptionParser +A common way to define an option in +OptionParser+ is with instance method OptionParser#on. The method may be called with any number of arguments @@ -107,11 +170,6 @@ Multiple short names can "share" a hyphen: ["-1 or -%", true] ["-1 or -%", true] -This is a good time to note that giving an undefined option raises an exception: - - $ ruby short_names.rb -z - short_names.rb:9:in `<main>': invalid option: -z (OptionParser::InvalidOption) - ==== Long Option Names A long option name consists of two hyphens and a one or more characters @@ -174,11 +232,11 @@ Executions: $ ruby mixed_names.rb --xxx ["--xxx", true] $ ruby mixed_names.rb -y - mixed_names.rb:12:in `<main>': missing argument: -y (OptionParser::MissingArgument) + mixed_names.rb:12:in '<main>': missing argument: -y (OptionParser::MissingArgument) $ ruby mixed_names.rb -y FOO ["--yyy", "FOO"] $ ruby mixed_names.rb --yyy - mixed_names.rb:12:in `<main>': missing argument: --yyy (OptionParser::MissingArgument) + mixed_names.rb:12:in '<main>': missing argument: --yyy (OptionParser::MissingArgument) $ ruby mixed_names.rb --yyy BAR ["--yyy", "BAR"] $ ruby mixed_names.rb -z @@ -190,34 +248,34 @@ Executions: $ ruby mixed_names.rb --zzz BAT ["--zzz", "BAT"] -==== Command-Line Abbreviations +==== Option Name Abbreviations -By default, abbreviations for command-line option names are allowed. -An abbreviated option is valid if it is unique among abbreviated option names. +By default, abbreviated option names on the command-line are allowed. +An abbreviated name is valid if it is unique among abbreviated option names. - :include: ruby/abbreviation.rb + :include: ruby/name_abbrev.rb Executions: - $ ruby abbreviation.rb --help - Usage: abbreviation [options] + $ ruby name_abbrev.rb --help + Usage: name_abbrev [options] -n, --dry-run -d, --draft - $ ruby abbreviation.rb -n + $ ruby name_abbrev.rb -n ["--dry-run", true] - $ ruby abbreviation.rb --dry-run + $ ruby name_abbrev.rb --dry-run ["--dry-run", true] - $ ruby abbreviation.rb -d + $ ruby name_abbrev.rb -d ["--draft", true] - $ ruby abbreviation.rb --draft + $ ruby name_abbrev.rb --draft ["--draft", true] - $ ruby abbreviation.rb --d - abbreviation.rb:9:in `<main>': ambiguous option: --d (OptionParser::AmbiguousOption) - $ ruby abbreviation.rb --dr - abbreviation.rb:9:in `<main>': ambiguous option: --dr (OptionParser::AmbiguousOption) - $ ruby abbreviation.rb --dry + $ ruby name_abbrev.rb --d + name_abbrev.rb:9:in '<main>': ambiguous option: --d (OptionParser::AmbiguousOption) + $ ruby name_abbrev.rb --dr + name_abbrev.rb:9:in '<main>': ambiguous option: --dr (OptionParser::AmbiguousOption) + $ ruby name_abbrev.rb --dry ["--dry-run", true] - $ ruby abbreviation.rb --dra + $ ruby name_abbrev.rb --dra ["--draft", true] You can disable abbreviation using method +require_exact+. @@ -227,7 +285,7 @@ You can disable abbreviation using method +require_exact+. Executions: $ ruby no_abbreviation.rb --dry-ru - no_abbreviation.rb:10:in `<main>': invalid option: --dry-ru (OptionParser::InvalidOption) + no_abbreviation.rb:10:in '<main>': invalid option: --dry-ru (OptionParser::InvalidOption) $ ruby no_abbreviation.rb --dry-run ["--dry-run", true] @@ -265,7 +323,7 @@ Executions: Omitting a required argument raises an error: $ ruby required_argument.rb -x - required_argument.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) + required_argument.rb:9:in '<main>': missing argument: -x (OptionParser::MissingArgument) ==== Option with Optional Argument @@ -293,6 +351,129 @@ Executions: Omitting an optional argument does not raise an error. +==== Argument Abbreviations + +Specify an argument list as an Array or a Hash. + + :include: ruby/argument_abbreviation.rb + +When an argument is abbreviated, the expanded argument yielded. + +Executions: + + $ ruby argument_abbreviation.rb --help + Usage: argument_abbreviation [options] + Usage: argument_abbreviation [options] + -x, --xxx=VALUE Argument abbreviations + -y, --yyy=VALUE Argument abbreviations + $ ruby argument_abbreviation.rb --xxx A + ["--xxx", "ABC"] + $ ruby argument_abbreviation.rb --xxx c + argument_abbreviation.rb:9:in '<main>': invalid argument: --xxx c (OptionParser::InvalidArgument) + $ ruby argument_abbreviation.rb --yyy a --yyy d + ["--yyy", "XYZ"] + ["--yyy", "FOO"] + +=== Argument Values + +Permissible argument values may be restricted +either by specifying explicit values +or by providing a pattern that the given value must match. + +==== Explicit Argument Values + +You can specify argument values in either of two ways: + +- Specify values an array of strings. +- Specify values a hash. + +===== Explicit Values in Array + +You can specify explicit argument values in an array of strings. +The argument value must be one of those strings, or an unambiguous abbreviation. + +File +explicit_array_values.rb+ defines options with explicit argument values. + + :include: ruby/explicit_array_values.rb + +Executions: + + $ ruby explicit_array_values.rb --help + Usage: explicit_array_values [options] + -xXXX Values for required argument + -y [YYY] Values for optional argument + $ ruby explicit_array_values.rb -x + explicit_array_values.rb:9:in '<main>': missing argument: -x (OptionParser::MissingArgument) + $ ruby explicit_array_values.rb -x foo + ["-x", "foo"] + $ ruby explicit_array_values.rb -x f + ["-x", "foo"] + $ ruby explicit_array_values.rb -x bar + ["-x", "bar"] + $ ruby explicit_array_values.rb -y ba + explicit_array_values.rb:9:in '<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) + $ ruby explicit_array_values.rb -x baz + explicit_array_values.rb:9:in '<main>': invalid argument: -x baz (OptionParser::InvalidArgument) + + +===== Explicit Values in Hash + +You can specify explicit argument values in a hash with string keys. +The value passed must be one of those keys, or an unambiguous abbreviation; +the value yielded will be the value for that key. + +File +explicit_hash_values.rb+ defines options with explicit argument values. + + :include: ruby/explicit_hash_values.rb + +Executions: + + $ ruby explicit_hash_values.rb --help + Usage: explicit_hash_values [options] + -xXXX Values for required argument + -y [YYY] Values for optional argument + $ ruby explicit_hash_values.rb -x + explicit_hash_values.rb:9:in '<main>': missing argument: -x (OptionParser::MissingArgument) + $ ruby explicit_hash_values.rb -x foo + ["-x", 0] + $ ruby explicit_hash_values.rb -x f + ["-x", 0] + $ ruby explicit_hash_values.rb -x bar + ["-x", 1] + $ ruby explicit_hash_values.rb -x baz + explicit_hash_values.rb:9:in '<main>': invalid argument: -x baz (OptionParser::InvalidArgument) + $ ruby explicit_hash_values.rb -y + ["-y", nil] + $ ruby explicit_hash_values.rb -y baz + ["-y", 2] + $ ruby explicit_hash_values.rb -y bat + ["-y", 3] + $ ruby explicit_hash_values.rb -y ba + explicit_hash_values.rb:9:in '<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) + $ ruby explicit_hash_values.rb -y bam + ["-y", nil] + +==== Argument Value Patterns + +You can restrict permissible argument values +by specifying a Regexp that the given argument must match. + +File +matched_values.rb+ defines options with matched argument values. + + :include: ruby/matched_values.rb + +Executions: + + $ ruby matched_values.rb --help + Usage: matched_values [options] + --xxx XXX Matched values + $ ruby matched_values.rb --xxx foo + ["--xxx", "foo"] + $ ruby matched_values.rb --xxx FOO + ["--xxx", "FOO"] + $ ruby matched_values.rb --xxx bar + matched_values.rb:6:in '<main>': invalid argument: --xxx bar (OptionParser::InvalidArgument) + === Keyword Argument +into+ In parsing options, you can add keyword option +into+ with a hash-like argument; @@ -343,7 +524,7 @@ Executions: -y, --yyyYYY Short and long, required argument -z, --zzz [ZZZ] Short and long, optional argument $ ruby missing_options.rb --yyy FOO - missing_options.rb:11:in `<main>': Missing required options: [:xxx, :zzz] (RuntimeError) + missing_options.rb:11:in '<main>': Missing required options: [:xxx, :zzz] (RuntimeError) ==== Default Values for Options @@ -361,15 +542,14 @@ Executions: $ ruby default_values.rb --yyy FOO {:yyy=>"FOO", :zzz=>"BBB"} - === Argument Converters An option can specify that its argument is to be converted -from the default \String to an instance of another class. +from the default +String+ to an instance of another class. There are a number of built-in converters. Example: File +date.rb+ -defines an option whose argument is to be converted to a \Date object. +defines an option whose argument is to be converted to a +Date+ object. The argument is converted by method Date#parse. :include: ruby/date.rb @@ -384,5 +564,295 @@ Executions: [#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, Date] You can also define custom converters. -See {Argument Converters}[./argument_converters_rdoc.html] +See {Argument Converters}[./argument_converters.rdoc] for both built-in and custom converters. + +=== Help + ++OptionParser+ makes automatically generated help text available. + +The help text consists of: + +- A banner, showing the usage. +- Option short and long names. +- Option dummy argument names. +- Option descriptions. + +Example code: + + :include: ruby/help.rb + +The option names and dummy argument names are defined as described above. + +The option description consists of the strings that are not themselves option names; +An option can have more than one description string. +Execution: + + Usage: help [options] + -x, --xxx Adipiscing elit. Aenean commodo ligula eget. + Aenean massa. Cum sociis natoque penatibus + -y, --yyy YYY Lorem ipsum dolor sit amet, consectetuer. + -z, --zzz [ZZZ] Et magnis dis parturient montes, nascetur + ridiculus mus. Donec quam felis, ultricies + nec, pellentesque eu, pretium quis, sem. + +The program name is included in the default banner: +<tt>Usage: #{program_name} [options]</tt>; +you can change the program name. + + :include: ruby/help_program_name.rb + +Execution: + + $ ruby help_program_name.rb --help + Usage: help_program_name.rb [options] + +You can also change the entire banner. + + :include: ruby/help_banner.rb + +Execution: + + $ ruby help_banner.rb --help + Usage: ruby help_banner.rb + +By default, the option names are indented 4 spaces +and the width of the option-names field is 32 spaces. + +You can change these values, along with the banner, +by passing parameters to OptionParser.new. + + :include: ruby/help_format.rb + +Execution: + + $ ruby help_format.rb --help + ruby help_format.rb [options] + -x, --xxx Adipiscing elit. Aenean commodo ligula eget. + Aenean massa. Cum sociis natoque penatibus + -y, --yyy YYY Lorem ipsum dolor sit amet, consectetuer. + -z, --zzz [ZZZ] Et magnis dis parturient montes, nascetur + ridiculus mus. Donec quam felis, ultricies + nec, pellentesque eu, pretium quis, sem. + +=== Top List and Base List + +An +OptionParser+ object maintains a stack of OptionParser::List objects, +each of which has a collection of zero or more options. +It is unlikely that you'll need to add or take away from that stack. + +The stack includes: + +- The <em>top list</em>, given by OptionParser#top. +- The <em>base list</em>, given by OptionParser#base. + +When +OptionParser+ builds its help text, the options in the top list +precede those in the base list. + +=== Methods for Defining Options + +Option-defining methods allow you to create an option, and also append/prepend it +to the top list or append it to the base list. + +Each of these next three methods accepts a sequence of parameter arguments and a block, +creates an option object using method OptionParser#make_switch (see below), +and returns the created option: + +- \Method OptionParser#define appends the created option to the top list. + +- \Method OptionParser#define_head prepends the created option to the top list. + +- \Method OptionParser#define_tail appends the created option to the base list. + +These next three methods are identical to the three above, +except for their return values: + +- \Method OptionParser#on is identical to method OptionParser#define, + except that it returns the parser object +self+. + +- \Method OptionParser#on_head is identical to method OptionParser#define_head, + except that it returns the parser object +self+. + +- \Method OptionParser#on_tail is identical to method OptionParser#define_tail, + except that it returns the parser object +self+. + +Though you may never need to call it directly, +here's the core method for defining an option: + +- \Method OptionParser#make_switch accepts an array of parameters and a block. + See {Parameters for New Options}[optparse/option_params.rdoc]. + This method is unlike others here in that it: + - Accepts an <em>array of parameters</em>; + others accept a <em>sequence of parameter arguments</em>. + - Returns an array containing the created option object, + option names, and other values; + others return either the created option object + or the parser object +self+. + +=== Parsing + ++OptionParser+ has six instance methods for parsing. + +Three have names ending with a "bang" (<tt>!</tt>): + +- parse! +- order! +- permute! + +Each of these methods: + +- Accepts an optional array of string arguments +argv+; + if not given, +argv+ defaults to the value of OptionParser#default_argv, + whose initial value is ARGV. +- Accepts an optional keyword argument +into+ + (see {Keyword Argument into}[#label-Keyword+Argument+into]). +- Returns +argv+, possibly with some elements removed. + +The three other methods have names _not_ ending with a "bang": + +- parse +- order +- permute + +Each of these methods: + +- Accepts an array of string arguments + _or_ zero or more string arguments. +- Accepts an optional keyword argument +into+ and its value _into_. + (see {Keyword Argument into}[#label-Keyword+Argument+into]). +- Returns +argv+, possibly with some elements removed. + +==== \Method +parse!+ + +\Method +parse!+: + +- Accepts an optional array of string arguments +argv+; + if not given, +argv+ defaults to the value of OptionParser#default_argv, + whose initial value is ARGV. +- Accepts an optional keyword argument +into+ + (see {Keyword Argument into}[#label-Keyword+Argument+into]). +- Returns +argv+, possibly with some elements removed. + +The method processes the elements in +argv+ beginning at <tt>argv[0]</tt>, +and ending, by default, at the end. + +Otherwise processing ends and the method returns when: + +- The terminator argument <tt>--</tt> is found; + the terminator argument is removed before the return. +- Environment variable +POSIXLY_CORRECT+ is defined + and a non-option argument is found; + the non-option argument is not removed. + Note that the _value_ of that variable does not matter, + as only its existence is checked. + +File +parse_bang.rb+: + + :include: ruby/parse_bang.rb + +Help: + + $ ruby parse_bang.rb --help + Usage: parse_bang [options] + --xxx + --yyy YYY + --zzz [ZZZ] + +Default behavior: + + $ ruby parse_bang.rb input_file.txt output_file.txt --xxx --yyy FOO --zzz BAR + ["--xxx", true] + ["--yyy", "FOO"] + ["--zzz", "BAR"] + Returned: ["input_file.txt", "output_file.txt"] (Array) + +Processing ended by terminator argument: + + $ ruby parse_bang.rb input_file.txt output_file.txt --xxx --yyy FOO -- --zzz BAR + ["--xxx", true] + ["--yyy", "FOO"] + Returned: ["input_file.txt", "output_file.txt", "--zzz", "BAR"] (Array) + +Processing ended by non-option found when +POSIXLY_CORRECT+ is defined: + + $ POSIXLY_CORRECT=true ruby parse_bang.rb --xxx input_file.txt output_file.txt -yyy FOO + ["--xxx", true] + Returned: ["input_file.txt", "output_file.txt", "-yyy", "FOO"] (Array) + +==== \Method +parse+ + +\Method +parse+: + +- Accepts an array of string arguments + _or_ zero or more string arguments. +- Accepts an optional keyword argument +into+ and its value _into_. + (see {Keyword Argument into}[#label-Keyword+Argument+into]). +- Returns +argv+, possibly with some elements removed. + +If given an array +ary+, the method forms array +argv+ as <tt>ary.dup</tt>. +If given zero or more string arguments, those arguments are formed +into array +argv+. + +The method calls + + parse!(argv, into: into) + +Note that environment variable +POSIXLY_CORRECT+ +and the terminator argument <tt>--</tt> are honored. + +File +parse.rb+: + + :include: ruby/parse.rb + +Help: + + $ ruby parse.rb --help + Usage: parse [options] + --xxx + --yyy YYY + --zzz [ZZZ] + +Default behavior: + + $ ruby parse.rb input_file.txt output_file.txt --xxx --yyy FOO --zzz BAR + ["--xxx", true] + ["--yyy", "FOO"] + ["--zzz", "BAR"] + Returned: ["input_file.txt", "output_file.txt"] (Array) + +Processing ended by terminator argument: + + $ ruby parse.rb input_file.txt output_file.txt --xxx --yyy FOO -- --zzz BAR + ["--xxx", true] + ["--yyy", "FOO"] + Returned: ["input_file.txt", "output_file.txt", "--zzz", "BAR"] (Array) + +Processing ended by non-option found when +POSIXLY_CORRECT+ is defined: + + $ POSIXLY_CORRECT=true ruby parse.rb --xxx input_file.txt output_file.txt -yyy FOO + ["--xxx", true] + Returned: ["input_file.txt", "output_file.txt", "-yyy", "FOO"] (Array) + +==== \Method +order!+ + +Calling method OptionParser#order! gives exactly the same result as +calling method OptionParser#parse! with environment variable ++POSIXLY_CORRECT+ defined. + +==== \Method +order+ + +Calling method OptionParser#order gives exactly the same result as +calling method OptionParser#parse with environment variable ++POSIXLY_CORRECT+ defined. + +==== \Method +permute!+ + +Calling method OptionParser#permute! gives exactly the same result as +calling method OptionParser#parse! with environment variable ++POSIXLY_CORRECT+ _not_ defined. + +==== \Method +permute+ + +Calling method OptionParser#permute gives exactly the same result as +calling method OptionParser#parse with environment variable ++POSIXLY_CORRECT+ _not_ defined. |
