From f209276f79d84578d4e40004ce7768194aae00cc Mon Sep 17 00:00:00 2001 From: BurdetteLamar Date: Mon, 29 Mar 2021 14:03:04 -0500 Subject: [PATCH 01/27] Beginnings of tutorial --- .gitignore | 2 +- doc/ruby/argv.rb | 2 + doc/ruby/long_names.rb | 9 +++ doc/ruby/mixed_names.rb | 9 +++ doc/ruby/short_names.rb | 9 +++ doc/tutorial.rdoc | 125 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 doc/ruby/argv.rb create mode 100644 doc/ruby/long_names.rb create mode 100644 doc/ruby/mixed_names.rb create mode 100644 doc/ruby/short_names.rb create mode 100644 doc/tutorial.rdoc diff --git a/.gitignore b/.gitignore index b9b830f..324a2a3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ /.yardoc /_yardoc/ /coverage/ -/doc/ +/rdoc/ /logs/ /pkg/ /spec/reports/ diff --git a/doc/ruby/argv.rb b/doc/ruby/argv.rb new file mode 100644 index 0000000..12495cf --- /dev/null +++ b/doc/ruby/argv.rb @@ -0,0 +1,2 @@ +p ARGV + diff --git a/doc/ruby/long_names.rb b/doc/ruby/long_names.rb new file mode 100644 index 0000000..e36152d --- /dev/null +++ b/doc/ruby/long_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx') do |option| + p "--xxx #{option}" +end +parser.on('--y1%', '--z2#') do |option| + p "--y1% or --z2# #{option}" +end +parser.parse! diff --git a/doc/ruby/mixed_names.rb b/doc/ruby/mixed_names.rb new file mode 100644 index 0000000..b8f3ac9 --- /dev/null +++ b/doc/ruby/mixed_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx') do |option| + p "--xxx #{option}" +end +parser.on('-y', '--y1%') do |option| + p "--y1% #{option}" +end +parser.parse! diff --git a/doc/ruby/short_names.rb b/doc/ruby/short_names.rb new file mode 100644 index 0000000..0dc35b7 --- /dev/null +++ b/doc/ruby/short_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x') do |option| + p "-x #{option}" +end +parser.on('-1', '-%') do |option| + p "-1 or -% #{option}" +end +parser.parse! diff --git a/doc/tutorial.rdoc b/doc/tutorial.rdoc new file mode 100644 index 0000000..3f60b46 --- /dev/null +++ b/doc/tutorial.rdoc @@ -0,0 +1,125 @@ +== Tutorial + +=== 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: + + :include: ruby/argv.rb + +Execution, with arguments and options: + + $ ruby doc/ruby/argv.rb foo --bar --baz bat bam + ["foo", "--bar", "--baz", "bat", "bam"] + +The executing program is responsible for parsing and handling +the command-line options. + +OptionParser offers methods for parsing and handling those options. + +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. +- The option may take no argument, a required argument, or an optional argument. +- The argument may be automatically converted to a specified class. +- The argument may be restricted to specified _forms_. +- The argument may be restricted to specified _values_. + +The class also has a method #summarize that returns a string summary +of all defined options. + +=== Defining Options + +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 +(whose order does not matter), +and may also have a trailing optional keyword argument +into+. + +The given arguments determine the characteristics of the new option. +These may include: + +- One or more short option names. +- One or more long option names. +- Whether the option takes no argument, an optional argument, or a required argument. +- Acceptable _forms_ for the argument. +- Acceptable _values_ for the argument. +- A proc or method to be called when the parser encounters the option. +- String descriptions for the option. + +=== Option Names + +You can give an option one or more names of two types: + +- Short (1-character) name, beginning with one hyphen (-). +- Long (multi-character) name, beginning with two hyphens (--). + +==== Short Option Names + +A short option name consists of a hyphen and a single character. + +File +short_names.rb+ +defines an option with a short name, -x, +and an option with two short names (aliases, in effect) -y and -z. + + :include: ruby/short_names.rb + +Executions: + + $ ruby doc/ruby/short_names.rb -x + "-x true" + $ ruby doc/ruby/short_names.rb -1 + "-1 or -% true" + $ ruby doc/ruby/short_names.rb -% + "-1 or -% true" + +Multiple short names can "share" a hyphen: + + $ ruby short_names.rb -x1% + "-x true" + "-1 or -% true" + "-1 or -% true" + +==== Long Option Names + +A long option name consists of two hyphens and a one or more characters +(usually two or more characters). + +File +long_names.rb+ +defines an option with a long name, --xxx, +and an option with two long names (aliases, in effect) --y1% and --z2#. + + :include: ruby/long_names.rb + +Executions: + + $ ruby long_names.rb --xxx + "--xxx true" + $ ruby long_names.rb --y1% + "--y1% or -z2# true" + $ ruby long_names.rb --z2# + "--y1% or -z2# true" + +==== Mixing Option Names + +Many developers like to mix short and long option names, +so that a short name is in effect an abbreviation of a long name. + +File +mixed_names.rb+ +defines options that each have both a short and a long name. + + :include: ruby/mixed_names.rb + +Executions: + + $ ruby doc/ruby/mixed_names.rb -x + "--xxx true" + $ ruby doc/ruby/mixed_names.rb --xxx + "--xxx true" + $ ruby doc/ruby/mixed_names.rb -y + "--y1% true" + $ ruby doc/ruby/mixed_names.rb --y1% + "--y1% true" From d14bf830078c2b2c8c8bcbe60aa2a2ebb40e0b6c Mon Sep 17 00:00:00 2001 From: Olle Jonsson Date: Tue, 6 Apr 2021 10:01:37 +0200 Subject: [PATCH 02/27] gemspec: Explicitly list 0 executables This gem exposes no executable files. --- optparse.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/optparse.gemspec b/optparse.gemspec index 831c787..b8ec8cf 100644 --- a/optparse.gemspec +++ b/optparse.gemspec @@ -28,6 +28,6 @@ Gem::Specification.new do |spec| } end spec.bindir = "exe" - spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.executables = [] spec.require_paths = ["lib"] end From 84dfd92d2a7fb75bb40fbb8414bd8b90b7ccbac6 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Tue, 6 Apr 2021 13:55:21 -0500 Subject: [PATCH 03/27] More on tutorial (#9) * More on tutorial * More on tutorial * More on tutorial * More on tutorial: clearer example output --- doc/ruby/long_names.rb | 9 --- doc/ruby/mixed_names.rb | 9 --- doc/ruby/short_names.rb | 9 --- doc/{ruby => tutorial}/argv.rb | 0 doc/tutorial/long_names.rb | 9 +++ doc/tutorial/mixed_names.rb | 9 +++ doc/tutorial/optional_argument.rb | 9 +++ doc/tutorial/required_argument.rb | 9 +++ doc/tutorial/short_names.rb | 9 +++ doc/{ => tutorial}/tutorial.rdoc | 115 +++++++++++++++++++++++------- 10 files changed, 133 insertions(+), 54 deletions(-) delete mode 100644 doc/ruby/long_names.rb delete mode 100644 doc/ruby/mixed_names.rb delete mode 100644 doc/ruby/short_names.rb rename doc/{ruby => tutorial}/argv.rb (100%) create mode 100644 doc/tutorial/long_names.rb create mode 100644 doc/tutorial/mixed_names.rb create mode 100644 doc/tutorial/optional_argument.rb create mode 100644 doc/tutorial/required_argument.rb create mode 100644 doc/tutorial/short_names.rb rename doc/{ => tutorial}/tutorial.rdoc (53%) diff --git a/doc/ruby/long_names.rb b/doc/ruby/long_names.rb deleted file mode 100644 index e36152d..0000000 --- a/doc/ruby/long_names.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'optparse' -parser = OptionParser.new -parser.on('--xxx') do |option| - p "--xxx #{option}" -end -parser.on('--y1%', '--z2#') do |option| - p "--y1% or --z2# #{option}" -end -parser.parse! diff --git a/doc/ruby/mixed_names.rb b/doc/ruby/mixed_names.rb deleted file mode 100644 index b8f3ac9..0000000 --- a/doc/ruby/mixed_names.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'optparse' -parser = OptionParser.new -parser.on('-x', '--xxx') do |option| - p "--xxx #{option}" -end -parser.on('-y', '--y1%') do |option| - p "--y1% #{option}" -end -parser.parse! diff --git a/doc/ruby/short_names.rb b/doc/ruby/short_names.rb deleted file mode 100644 index 0dc35b7..0000000 --- a/doc/ruby/short_names.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'optparse' -parser = OptionParser.new -parser.on('-x') do |option| - p "-x #{option}" -end -parser.on('-1', '-%') do |option| - p "-1 or -% #{option}" -end -parser.parse! diff --git a/doc/ruby/argv.rb b/doc/tutorial/argv.rb similarity index 100% rename from doc/ruby/argv.rb rename to doc/tutorial/argv.rb diff --git a/doc/tutorial/long_names.rb b/doc/tutorial/long_names.rb new file mode 100644 index 0000000..a34b338 --- /dev/null +++ b/doc/tutorial/long_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx') do |value| + p ['-xxx', value] +end +parser.on('--y1%', '--z2#') do |value| + p ['--y1% or --z2#', value] +end +parser.parse! diff --git a/doc/tutorial/mixed_names.rb b/doc/tutorial/mixed_names.rb new file mode 100644 index 0000000..e886049 --- /dev/null +++ b/doc/tutorial/mixed_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx') do |value| + p ['--xxx', value] +end +parser.on('-y', '--y1%') do |value| + p ['--y1%', value] +end +parser.parse! diff --git a/doc/tutorial/optional_argument.rb b/doc/tutorial/optional_argument.rb new file mode 100644 index 0000000..ebff2f4 --- /dev/null +++ b/doc/tutorial/optional_argument.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x [XXX]', '--xxx') do |value| + p ['--xxx', value] +end +parser.on('-y', '--yyy [YYY]') do |value| + p ['--yyy', value] +end +parser.parse! diff --git a/doc/tutorial/required_argument.rb b/doc/tutorial/required_argument.rb new file mode 100644 index 0000000..7a5a868 --- /dev/null +++ b/doc/tutorial/required_argument.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x XXX', '--xxx') do |value| + p ['--xxx', value] +end +parser.on('-y', '--y YYY') do |value| + p ['--yyy', value] +end +parser.parse! diff --git a/doc/tutorial/short_names.rb b/doc/tutorial/short_names.rb new file mode 100644 index 0000000..6581dfe --- /dev/null +++ b/doc/tutorial/short_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x') do |value| + p ['x', value] +end +parser.on('-1', '-%') do |value| + p ['-1 or -%', value] +end +parser.parse! diff --git a/doc/tutorial.rdoc b/doc/tutorial/tutorial.rdoc similarity index 53% rename from doc/tutorial.rdoc rename to doc/tutorial/tutorial.rdoc index 3f60b46..60ead0a 100644 --- a/doc/tutorial.rdoc +++ b/doc/tutorial/tutorial.rdoc @@ -6,11 +6,11 @@ When a Ruby program executes, it captures its command-line arguments and options into variable ARGV. This simple program just prints its \ARGV: - :include: ruby/argv.rb + :include: argv.rb Execution, with arguments and options: - $ ruby doc/ruby/argv.rb foo --bar --baz bat bam + $ ruby argv.rb foo --bar --baz bat bam ["foo", "--bar", "--baz", "bat", "bam"] The executing program is responsible for parsing and handling @@ -27,8 +27,10 @@ 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 a method #summarize that returns a string summary -of all defined options. +The class also has: + +- Method #summarize: returns a text summary of the options. +- Method #help: displays automatically-generated help text. === Defining Options @@ -65,23 +67,28 @@ File +short_names.rb+ defines an option with a short name, -x, and an option with two short names (aliases, in effect) -y and -z. - :include: ruby/short_names.rb + :include: short_names.rb Executions: - $ ruby doc/ruby/short_names.rb -x - "-x true" - $ ruby doc/ruby/short_names.rb -1 - "-1 or -% true" - $ ruby doc/ruby/short_names.rb -% - "-1 or -% true" + $ ruby short_names.rb -x + ["x", true] + $ ruby short_names.rb -1 + ["-1 or -%", true] + $ ruby short_names.rb -% + ["-1 or -%", true] Multiple short names can "share" a hyphen: $ ruby short_names.rb -x1% - "-x true" - "-1 or -% true" - "-1 or -% true" + ["x", true] + ["-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 `
': invalid option: -z (OptionParser::InvalidOption) ==== Long Option Names @@ -92,16 +99,16 @@ File +long_names.rb+ defines an option with a long name, --xxx, and an option with two long names (aliases, in effect) --y1% and --z2#. - :include: ruby/long_names.rb + :include: long_names.rb Executions: $ ruby long_names.rb --xxx - "--xxx true" + ["-xxx", true] $ ruby long_names.rb --y1% - "--y1% or -z2# true" + ["--y1% or --z2#", true] $ ruby long_names.rb --z2# - "--y1% or -z2# true" + ["--y1% or --z2#", true] ==== Mixing Option Names @@ -111,15 +118,69 @@ so that a short name is in effect an abbreviation of a long name. File +mixed_names.rb+ defines options that each have both a short and a long name. - :include: ruby/mixed_names.rb + :include: mixed_names.rb + +Executions: + + $ ruby mixed_names.rb -x + ["--xxx", true] + $ ruby mixed_names.rb --xxx + ["--xxx", true] + $ ruby mixed_names.rb -y + ["--y1%", true] + $ ruby mixed_names.rb --y1% + ["--y1%", true] + +=== Option Arguments + +An option may take no argument, a required argument, or an optional argument. + +==== Option with No Argument + +All the examples above define options with no argument. + +==== Option with Required Argument + +Specify a required argument for an option by adding a dummy word +to its name definition. + +File +required_argument.rb+ defines two options; +each has a required argument because the name definition has a following dummy word. + + :include: required_argument.rb + +When an option is found, the given argument is yielded. Executions: - $ ruby doc/ruby/mixed_names.rb -x - "--xxx true" - $ ruby doc/ruby/mixed_names.rb --xxx - "--xxx true" - $ ruby doc/ruby/mixed_names.rb -y - "--y1% true" - $ ruby doc/ruby/mixed_names.rb --y1% - "--y1% true" + $ ruby required_argument.rb -x AAA + ["--xxx", "AAA"] + $ ruby required_argument.rb -y BBB + ["--yyy", "BBB"] + +Omitting a required argument raises an error: + + $ ruby required_argument.rb -x + required_argument.rb:9:in `
': missing argument: -x (OptionParser::MissingArgument) + +==== Option with Optional Argument + +Specify an optional argument for an option by adding a dummy word +enclosed in square brackets to its name definition. + +File +optional_argument.rb+ defines two options; +each has an optional argument because the name definition has a following dummy word +in square brackets. + + :include: optional_argument.rb + +When an option with an argument is found, the given argument yielded. + +Executions: + + $ ruby optional_argument.rb -x AAA + ["--xxx", "AAA"] + $ ruby optional_argument.rb -y BBB + ["--yyy", "BBB"] + +Omitting an optional argument does not raise an error. From 5618eeb49ee2a316cd5d91a515dbb2734f553027 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Wed, 7 Apr 2021 09:01:52 -0500 Subject: [PATCH 04/27] Enhanced doc for option parameters (#11) --- doc/option_params/argument_keywords.rb | 6 + doc/option_params/argument_strings.rb | 6 + doc/option_params/array.rb | 6 + doc/option_params/block.rb | 9 + doc/option_params/date.rb | 6 + doc/option_params/datetime.rb | 6 + doc/option_params/decimal_integer.rb | 7 + doc/option_params/decimal_numeric.rb | 7 + doc/option_params/descriptions.rb | 15 + doc/option_params/explicit_array_values.rb | 9 + doc/option_params/explicit_hash_values.rb | 9 + doc/option_params/false_class.rb | 6 + doc/option_params/float.rb | 6 + doc/option_params/integer.rb | 6 + doc/option_params/long_binary.rb | 6 + doc/option_params/long_optional.rb | 6 + doc/option_params/long_required.rb | 6 + doc/option_params/long_simple.rb | 9 + doc/option_params/matched_values.rb | 6 + doc/option_params/method.rb | 11 + doc/option_params/mixed_names.rb | 12 + doc/option_params/numeric.rb | 6 + doc/option_params/object.rb | 6 + doc/option_params/octal_integer.rb | 7 + doc/option_params/option_params.rdoc | 845 +++++++++++++++++++++ doc/option_params/proc.rb | 13 + doc/option_params/regexp.rb | 6 + doc/option_params/shellwords.rb | 6 + doc/option_params/short_optional.rb | 6 + doc/option_params/short_range.rb | 6 + doc/option_params/short_required.rb | 6 + doc/option_params/short_simple.rb | 9 + doc/option_params/string.rb | 6 + doc/option_params/terminator.rb | 6 + doc/option_params/time.rb | 6 + doc/option_params/true_class.rb | 6 + doc/option_params/uri.rb | 6 + 37 files changed, 1106 insertions(+) create mode 100644 doc/option_params/argument_keywords.rb create mode 100644 doc/option_params/argument_strings.rb create mode 100644 doc/option_params/array.rb create mode 100644 doc/option_params/block.rb create mode 100644 doc/option_params/date.rb create mode 100644 doc/option_params/datetime.rb create mode 100644 doc/option_params/decimal_integer.rb create mode 100644 doc/option_params/decimal_numeric.rb create mode 100644 doc/option_params/descriptions.rb create mode 100644 doc/option_params/explicit_array_values.rb create mode 100644 doc/option_params/explicit_hash_values.rb create mode 100644 doc/option_params/false_class.rb create mode 100644 doc/option_params/float.rb create mode 100644 doc/option_params/integer.rb create mode 100644 doc/option_params/long_binary.rb create mode 100644 doc/option_params/long_optional.rb create mode 100644 doc/option_params/long_required.rb create mode 100644 doc/option_params/long_simple.rb create mode 100644 doc/option_params/matched_values.rb create mode 100644 doc/option_params/method.rb create mode 100644 doc/option_params/mixed_names.rb create mode 100644 doc/option_params/numeric.rb create mode 100644 doc/option_params/object.rb create mode 100644 doc/option_params/octal_integer.rb create mode 100644 doc/option_params/option_params.rdoc create mode 100644 doc/option_params/proc.rb create mode 100644 doc/option_params/regexp.rb create mode 100644 doc/option_params/shellwords.rb create mode 100644 doc/option_params/short_optional.rb create mode 100644 doc/option_params/short_range.rb create mode 100644 doc/option_params/short_required.rb create mode 100644 doc/option_params/short_simple.rb create mode 100644 doc/option_params/string.rb create mode 100644 doc/option_params/terminator.rb create mode 100644 doc/option_params/time.rb create mode 100644 doc/option_params/true_class.rb create mode 100644 doc/option_params/uri.rb diff --git a/doc/option_params/argument_keywords.rb b/doc/option_params/argument_keywords.rb new file mode 100644 index 0000000..8533257 --- /dev/null +++ b/doc/option_params/argument_keywords.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', :REQUIRED, 'Required argument') do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/argument_strings.rb b/doc/option_params/argument_strings.rb new file mode 100644 index 0000000..77861dd --- /dev/null +++ b/doc/option_params/argument_strings.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', '=XXX', 'Required argument') do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/array.rb b/doc/option_params/array.rb new file mode 100644 index 0000000..7c6c14f --- /dev/null +++ b/doc/option_params/array.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--array=ARRAY', Array) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/block.rb b/doc/option_params/block.rb new file mode 100644 index 0000000..c4dfdeb --- /dev/null +++ b/doc/option_params/block.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx', 'Option with no argument') do |value| + p ['Handler block for -xxx called with value:', value] +end +parser.on('--yyy YYY', 'Option with required argument') do |value| + p ['Handler block for -yyy called with value:', value] +end +parser.parse! diff --git a/doc/option_params/date.rb b/doc/option_params/date.rb new file mode 100644 index 0000000..5994ad6 --- /dev/null +++ b/doc/option_params/date.rb @@ -0,0 +1,6 @@ +require 'optparse/date' +parser = OptionParser.new +parser.on('--date=DATE', Date) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/datetime.rb b/doc/option_params/datetime.rb new file mode 100644 index 0000000..b9b591d --- /dev/null +++ b/doc/option_params/datetime.rb @@ -0,0 +1,6 @@ +require 'optparse/date' +parser = OptionParser.new +parser.on('--datetime=DATETIME', DateTime) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/decimal_integer.rb b/doc/option_params/decimal_integer.rb new file mode 100644 index 0000000..360bd28 --- /dev/null +++ b/doc/option_params/decimal_integer.rb @@ -0,0 +1,7 @@ +require 'optparse' +include OptionParser::Acceptables +parser = OptionParser.new +parser.on('--decimal_integer=DECIMAL_INTEGER', DecimalInteger) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/decimal_numeric.rb b/doc/option_params/decimal_numeric.rb new file mode 100644 index 0000000..954da13 --- /dev/null +++ b/doc/option_params/decimal_numeric.rb @@ -0,0 +1,7 @@ +require 'optparse' +include OptionParser::Acceptables +parser = OptionParser.new +parser.on('--decimal_numeric=DECIMAL_NUMERIC', DecimalNumeric) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/descriptions.rb b/doc/option_params/descriptions.rb new file mode 100644 index 0000000..9aec80a --- /dev/null +++ b/doc/option_params/descriptions.rb @@ -0,0 +1,15 @@ +require 'optparse' +parser = OptionParser.new +description = <<-EOT +Lorem ipsum dolor sit amet, consectetuer +adipiscing elit. Aenean commodo ligula eget. +Aenean massa. Cum sociis natoque penatibus +et magnis dis parturient montes, nascetur +ridiculus mus. Donec quam felis, ultricies +nec, pellentesque eu, pretium quis, sem. +EOT +descriptions = description.split($/) +parser.on('--xxx', *descriptions) do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/explicit_array_values.rb b/doc/option_params/explicit_array_values.rb new file mode 100644 index 0000000..64f930a --- /dev/null +++ b/doc/option_params/explicit_array_values.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-xXXX', ['foo', 'bar'], 'Values for required argument' ) do |value| + p ['-x', value] +end +parser.on('-y [YYY]', ['baz', 'bat'], 'Values for optional argument') do |value| + p ['-y', value] +end +parser.parse! diff --git a/doc/option_params/explicit_hash_values.rb b/doc/option_params/explicit_hash_values.rb new file mode 100644 index 0000000..9c9e6a4 --- /dev/null +++ b/doc/option_params/explicit_hash_values.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-xXXX', {foo: 0, bar: 1}, 'Values for required argument' ) do |value| + p ['-x', value] +end +parser.on('-y [YYY]', {baz: 2, bat: 3}, 'Values for optional argument') do |value| + p ['-y', value] +end +parser.parse! diff --git a/doc/option_params/false_class.rb b/doc/option_params/false_class.rb new file mode 100644 index 0000000..04fe335 --- /dev/null +++ b/doc/option_params/false_class.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--false_class=FALSE_CLASS', FalseClass) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/float.rb b/doc/option_params/float.rb new file mode 100644 index 0000000..390df7f --- /dev/null +++ b/doc/option_params/float.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--float=FLOAT', Float) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/integer.rb b/doc/option_params/integer.rb new file mode 100644 index 0000000..f10656f --- /dev/null +++ b/doc/option_params/integer.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--integer=INTEGER', Integer) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/long_binary.rb b/doc/option_params/long_binary.rb new file mode 100644 index 0000000..8ecceca --- /dev/null +++ b/doc/option_params/long_binary.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--[no-]binary') do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/long_optional.rb b/doc/option_params/long_optional.rb new file mode 100644 index 0000000..38dd821 --- /dev/null +++ b/doc/option_params/long_optional.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx [XXX]', 'Long name with optional argument') do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/long_required.rb b/doc/option_params/long_required.rb new file mode 100644 index 0000000..b76c997 --- /dev/null +++ b/doc/option_params/long_required.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx XXX', 'Long name with required argument') do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/long_simple.rb b/doc/option_params/long_simple.rb new file mode 100644 index 0000000..4e489c4 --- /dev/null +++ b/doc/option_params/long_simple.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx', 'One long name') do |value| + p ['--xxx', value] +end +parser.on('--y1%', '--z2#', 'Two long names (aliases)') do |value| + p ['--y1% or --z2#', value] +end +parser.parse! diff --git a/doc/option_params/matched_values.rb b/doc/option_params/matched_values.rb new file mode 100644 index 0000000..f184ca8 --- /dev/null +++ b/doc/option_params/matched_values.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx XXX', /foo/i, 'Matched values') do |value| + p ['--xxx', value] +end +parser.parse! diff --git a/doc/option_params/method.rb b/doc/option_params/method.rb new file mode 100644 index 0000000..3f02ff5 --- /dev/null +++ b/doc/option_params/method.rb @@ -0,0 +1,11 @@ +require 'optparse' +parser = OptionParser.new +def xxx_handler(value) + p ['Handler method for -xxx called with value:', value] +end +parser.on('--xxx', 'Option with no argument', method(:xxx_handler)) +def yyy_handler(value) + p ['Handler method for -yyy called with value:', value] +end +parser.on('--yyy YYY', 'Option with required argument', method(:yyy_handler)) +parser.parse! diff --git a/doc/option_params/mixed_names.rb b/doc/option_params/mixed_names.rb new file mode 100644 index 0000000..fe6c554 --- /dev/null +++ b/doc/option_params/mixed_names.rb @@ -0,0 +1,12 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', 'Short and long, simple') do |value| + p ['--xxx', value] +end +parser.on('-yYYY', '--yyy', 'Short and long, required argument') do |value| + p ['--yyy', value] +end +parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') do |value| + p ['--zzz', value] +end +parser.parse! diff --git a/doc/option_params/numeric.rb b/doc/option_params/numeric.rb new file mode 100644 index 0000000..d7021f1 --- /dev/null +++ b/doc/option_params/numeric.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--numeric=NUMERIC', Numeric) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/object.rb b/doc/option_params/object.rb new file mode 100644 index 0000000..0f5ae8b --- /dev/null +++ b/doc/option_params/object.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--object=OBJECT', Object) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/octal_integer.rb b/doc/option_params/octal_integer.rb new file mode 100644 index 0000000..b9644a0 --- /dev/null +++ b/doc/option_params/octal_integer.rb @@ -0,0 +1,7 @@ +require 'optparse' +include OptionParser::Acceptables +parser = OptionParser.new +parser.on('--octal_integer=OCTAL_INTEGER', OctalInteger) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/option_params.rdoc b/doc/option_params/option_params.rdoc new file mode 100644 index 0000000..7cf5ef8 --- /dev/null +++ b/doc/option_params/option_params.rdoc @@ -0,0 +1,845 @@ +== Parameters for New Options + +Option-creating methods in \OptionParser +accept arguments that determine the behavior of a new option: + +- OptionParser#on +- OptionParser#on_head +- OptionParser#on_tail +- OptionParser#define +- OptionParser#define_head +- OptionParser#define_tail +- OptionParser#make_switch + +The code examples on this page use: + +- OptionParser#on, to define options. +- OptionParser#parse!, to parse the command line. +- Built-in option --help, to display defined options. + +Contents: + +- {Option Names}[#label-Option+Names] + - {Short Names}[#label-Short+Names] + - {Simple Short Names}[#label-Simple+Short+Names] + - {Short Names with Required Arguments}[#label-Short+Names+with+Required+Arguments] + - {Short Names with Optional Arguments}[#label-Short+Names+with+Optional+Arguments] + - {Short Names from Range}[#label-Short+Names+from+Range] + - {Long Names}[#label-Long+Names] + - {Simple Long Names}[#label-Simple+Long+Names] + - {Long Names with Required Arguments}[#label-Long+Names+with+Required+Arguments] + - {Long Names with Optional Arguments}[#label-Long+Names+with+Optional+Arguments] + - {Mixed Names}[#label-Mixed+Names] +- {Argument Styles}[#label-Argument+Styles] +- {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] +- {Argument Converters}[#label-Argument+Converters] + - {Date}[#label-Date] + - {DateTime}[#label-DateTime] + - {Time}[#label-Time] + - {URI}[#label-URI] + - {Shellwords}[#label-Shellwords] + - {Integer}[#label-Integer] + - {Float}[#label-Float] + - {Numeric}[#label-Numeric] + - {DecimalInteger}[#label-DecimalInteger] + - {OctalInteger}[#label-OctalInteger] + - {DecimalNumeric}[#label-DecimalNumeric] + - {TrueClass}[#label-TrueClass] + - {FalseClass}[#label-FalseClass] + - {Object}[#label-Object] + - {String}[#label-String] + - {Array}[#label-Array] + - {Regexp}[#label-Regexp] +- {Descriptions}[#label-Descriptions] +- {Handlers}[#label-Handlers] + - {Handler Blocks}[#label-Handler+Blocks] + - {Handler Procs}[#label-Handler+Procs] + - {Handler Methods}[#label-Handler+Methods] +- {Terminators}[#label-Terminators] + +=== Option Names + +There are two kinds of option names: + +- Short option name, consisting of a single hyphen and a single character. +- Long option name, consisting of two hyphens and one or more characters. + +==== Short Names + +===== Simple Short Names + +File +short_simple.rb+ defines two options: + +- One with short name -x. +- The other with two short names, in effect, aliases, -1 and -%. + + :include: short_simple.rb + +Executions: + + $ ruby short_simple.rb --help + Usage: short_simple [options] + -x One short name + -1, -% Two short names (aliases) + $ ruby short_simple.rb -x + ["-x", true] + $ ruby short_simple.rb -1 -x -% + ["-1 or -%", true] + ["-x", true] + ["-1 or -%", true] + +===== Short Names with Required Arguments + +A short name followed (no whitespace) by a dummy word +defines an option that requires an argument. + +File +short_required.rb+ defines an option -x +that requires an argument. + + :include: short_required.rb + +Executions: + + $ ruby short_required.rb --help + Usage: short_required [options] + -xXXX Short name with required argument + $ ruby short_required.rb -x + short_required.rb:6:in `
': missing argument: -x (OptionParser::MissingArgument) + $ ruby short_required.rb -x FOO + ["-x", "FOO"] + +===== Short Names with Optional Arguments + +A short name followed (with whitespace) by a dummy word in square brackets +defines an option that allows an optional argument. + +File +short_optional.rb+ defines an option -x +that allows an optional argument. + + :include: short_optional.rb + +Executions: + + $ ruby short_optional.rb --help + Usage: short_optional [options] + -x [XXX] Short name with optional argument + $ ruby short_optional.rb -x + ["-x", nil] + $ ruby short_optional.rb -x FOO + ["-x", "FOO"] + +===== Short Names from Range + +You can define an option with multiple short names +taken from a range of characters. +The parser yields both the actual character cited and the value. + +File +short_range.rb+ defines an option with short names +for all printable characters from ! to ~: + + :include: short_range.rb + +Executions: + + $ ruby short_range.rb --help + Usage: short_range [options] + -[!-~] Short names in (very large) range + $ ruby short_range.rb -! + ["!-~", "!", nil] + $ ruby short_range.rb -! + ["!-~", "!", nil] + $ ruby short_range.rb -A + ["!-~", "A", nil] + $ ruby short_range.rb -z + ["!-~", "z", nil] + +==== Long Names + +===== Simple Long Names + +File +long_simple.rb+ defines two options: + +- One with long name -xxx. +- The other with two long names, in effect, aliases, + --y1% and --z2#. + + :include: long_simple.rb + +Executions: + + $ ruby long_simple.rb --help + Usage: long_simple [options] + --xxx One long name + --y1%, --z2# Two long names (aliases) + $ ruby long_simple.rb --xxx + ["--xxx", true] + $ ruby long_simple.rb --y1% --xxx --z2# + ["--y1% or --z2#", true] + ["--xxx", true] + ["--y1% or --z2#", true] + +===== Long Names with Required Arguments + +A long name followed (with whitespace) by a dummy word +defines an option that requires an argument. + +File +long_required.rb+ defines an option --xxx +that requires an argument. + + :include: long_required.rb + +Executions: + + $ ruby long_required.rb --help + Usage: long_required [options] + --xxx XXX Long name with required argument + $ ruby long_required.rb --xxx + long_required.rb:6:in `
': missing argument: --xxx (OptionParser::MissingArgument) + $ ruby long_required.rb --xxx FOO + ["--xxx", "FOO"] + +===== Long Names with Optional Arguments + +A long name followed (with whitespace) by a dummy word in square brackets +defines an option that allows an optional argument. + +File +long_optional.rb+ defines an option --xxx +that allows an optional argument. + + :include: long_optional.rb + +Executions: + + $ ruby long_optional.rb --help + Usage: long_optional [options] + --xxx [XXX] Long name with optional argument + $ ruby long_optional.rb --xxx + ["--xxx", nil] + $ ruby long_optional.rb --xxx FOO + ["--xxx", "FOO"] + +==== Mixed Names + +An option may have both short and long names. + +File +mixed_names.rb+ defines a mixture of short and long names. + + :include: mixed_names.rb + +Executions: + + $ ruby mixed_names.rb --help + Usage: mixed_names [options] + -x, --xxx Short and long, simple + --yyy yYYY + Short and long, required argument + --zzz zZZZ + Short and long, optional argument + $ ruby mixed_names.rb -x + ["--xxx", true] + $ ruby mixed_names.rb --xxx + ["--xxx", true] + $ ruby mixed_names.rb -y + mixed_names.rb:12:in `
': missing argument: -y (OptionParser::MissingArgument) + $ ruby mixed_names.rb -y FOO + ["--yyy", "FOO"] + $ ruby mixed_names.rb --yyy + mixed_names.rb:12:in `
': missing argument: --yyy (OptionParser::MissingArgument) + $ ruby mixed_names.rb --yyy BAR + ["--yyy", "BAR"] + $ ruby mixed_names.rb -z + ["--zzz", nil] + $ ruby mixed_names.rb -z BAZ + ["--zzz", "BAZ"] + $ ruby mixed_names.rb --zzz + ["--zzz", nil] + $ ruby mixed_names.rb --zzz BAT + ["--zzz", "BAT"] + +=== Argument Keywords + +As seen above, a given option name string may itself +indicate whether the option has no argument, a required argument, +or an optional argument. + +An alternative is to use a separate symbol keyword, +which is one of :NONE (the default), +:REQUIRED, :OPTIONAL. + +File +argument_keywords.rb+ defines an option with a required argument. + + :include: argument_keywords.rb + +Executions: + + $ ruby argument_keywords.rb --help + Usage: argument_keywords [options] + -x, --xxx Required argument + $ ruby argument_styles.rb --xxx + argument_styles.rb:6:in `
': missing argument: --xxx (OptionParser::MissingArgument) + $ ruby argument_styles.rb --xxx FOO + ["--xxx", "FOO"] + +=== Argument Strings + +Still another way to specify a required argument +is to define it in a string separate from the name string. + +File +argument_strings.rb+ defines an option with a required argument. + + :include: argument_strings.rb + +Executions: + + $ ruby argument_strings.rb --help + Usage: argument_strings [options] + -x, --xxx=XXX Required argument + $ ruby argument_strings.rb --xxx + argument_strings.rb:9:in `
': missing argument: --xxx (OptionParser::MissingArgument) + $ ruby argument_strings.rb --xxx FOO + ["--xxx", "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. + +File +explicit_array_values.rb+ defines options with explicit argument values. + + :include: 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 `
': missing argument: -x (OptionParser::MissingArgument) + $ ruby explicit_array_values.rb -x foo + ["-x", "foo"] + $ ruby explicit_array_values.rb -x bar + ["-x", "bar"] + $ ruby explicit_array_values.rb -x baz + explicit_array_values.rb:9:in `
': 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. + +File +explicit_hash_values.rb+ defines options with explicit argument values. + + :include: 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 `
': missing argument: -x (OptionParser::MissingArgument) + $ ruby explicit_hash_values.rb -x foo + ["-x", 0] + $ ruby explicit_hash_values.rb -x bar + ["-x", 1] + $ ruby explicit_hash_values.rb -x baz + explicit_hash_values.rb:9:in `
': 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 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: 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 `
': invalid argument: --xxx bar (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. + +\OptionParser has a number of built-in converters, +which are demonstrated below. + +==== \Date + +File +date.rb+ +defines an option whose argument is to be converted to a \Date object. +The argument is converted by method +{Date.parse}[https://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html#method-c-parse]. + + :include: date.rb + +Executions: + + $ ruby date.rb --date 2001-02-03 + [#, Date] + $ ruby date.rb --date 20010203 + [#, Date] + $ ruby date.rb --date "3rd Feb 2001" + [#, Date] + +==== \DateTime + +File +datetime.rb+ +defines an option whose argument is to be converted to a \DateTime object. +The argument is converted by method +{DateTime.parse}[https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/DateTime.html#method-c-parse]. + + :include: datetime.rb + +Executions: + + $ ruby datetime.rb --datetime 2001-02-03T04:05:06+07:00 + [#, DateTime] + $ ruby datetime.rb --datetime 20010203T040506+0700 + [#, DateTime] + $ ruby datetime.rb --datetime "3rd Feb 2001 04:05:06 PM" + [#, DateTime] + +==== \Time + +File +time.rb+ +defines an option whose argument is to be converted to a \Time object. +The argument is converted by method +{Time.httpdate}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-httpdate] or +{Time.parse}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-parse]. + + :include: time.rb + +Executions: + + $ ruby time.rb --time "Thu, 06 Oct 2011 02:26:12 GMT" + [2011-10-06 02:26:12 UTC, Time] + $ ruby time.rb --time 2010-10-31 + [2010-10-31 00:00:00 -0500, Time] + +==== \URI + +File +uri.rb+ +defines an option whose argument is to be converted to a \URI object. +The argument is converted by method +{URI.parse}[https://ruby-doc.org/stdlib-2.7.2/libdoc/uri/rdoc/URI.html#method-c-parse]. + + :include: uri.rb + +Executions: + + $ ruby uri.rb --uri https://github.com + [#, URI::HTTPS] + $ ruby uri.rb --uri http://github.com + [#, URI::HTTP] + $ ruby uri.rb --uri file://~/var + [#, URI::File] + +==== \Shellwords + +File +shellwords.rb+ +defines an option whose argument is to be converted to an \Array object by method +{Shellwords.shellwords}[https://ruby-doc.org/stdlib-2.7.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellwords]. + + :include: shellwords.rb + +Executions: + + $ ruby shellwords.rb --shellwords "ruby my_prog.rb | less" + [["ruby", "my_prog.rb", "|", "less"], Array] + $ ruby shellwords.rb --shellwords "here are 'two words'" + [["here", "are", "two words"], Array] + +==== \Integer + +File +integer.rb+ +defines an option whose argument is to be converted to an \Integer object. +The argument is converted by method +{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. + + :include: integer.rb + +Executions: + + $ ruby integer.rb --integer 100 + [100, Integer] + $ ruby integer.rb --integer -100 + [-100, Integer] + $ ruby integer.rb --integer 0100 + [64, Integer] + $ ruby integer.rb --integer 0x100 + [256, Integer] + $ ruby integer.rb --integer 0b100 + [4, Integer] + +==== \Float + +File +float.rb+ +defines an option whose argument is to be converted to a \Float object. +The argument is converted by method +{Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float]. + + :include: float.rb + +Executions: + + $ ruby float.rb --float 1 + [1.0, Float] + $ ruby float.rb --float 3.14159 + [3.14159, Float] + $ ruby float.rb --float 1.234E2 + [123.4, Float] + $ ruby float.rb --float 1.234E-2 + [0.01234, Float] + +==== \Numeric + +File +numeric.rb+ +defines an option whose argument is to be converted to an instance +of \Rational, \Float, or \Integer. +The argument is converted by method +{Kernel.Rational}[https://ruby-doc.org/core/Kernel.html#method-i-Rational], +{Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float], or +{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. + + :include: numeric.rb + +Executions: + + $ ruby numeric.rb --numeric 1/3 + [(1/3), Rational] + $ ruby numeric.rb --numeric 3.333E-1 + [0.3333, Float] + $ ruby numeric.rb --numeric 3 + [3, Integer] + +==== \DecimalInteger + +File +decimal_integer.rb+ +defines an option whose argument is to be converted to an \Integer object. +The argument is converted by method +{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. + + :include: decimal_integer.rb + +The argument may not be in a binary or hexadecimal format; +a leading zero is ignored (not parsed as octal). + +Executions: + + $ ruby decimal_integer.rb --decimal_integer 100 + [100, Integer] + $ ruby decimal_integer.rb --decimal_integer -100 + [-100, Integer] + $ ruby decimal_integer.rb --decimal_integer 0100 + [100, Integer] + $ ruby decimal_integer.rb --decimal_integer -0100 + [-100, Integer] + +==== \OctalInteger + +File +octal_integer.rb+ +defines an option whose argument is to be converted to an \Integer object. +The argument is converted by method +{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. + + :include: octal_integer.rb + +The argument may not be in a binary or hexadecimal format; +it is parsed as octal, regardless of whether it has a leading zero. + +Executions: + + $ ruby octal_integer.rb --octal_integer 100 + [64, Integer] + $ ruby octal_integer.rb --octal_integer -100 + [-64, Integer] + $ ruby octal_integer.rb --octal_integer 0100 + [64, Integer] + +==== \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}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. + + :include: decimal_numeric.rb + +The argument may not be in a binary or hexadecimal format; +a leading zero causes the argument to be parsed as octal. + +Executions: + + $ ruby decimal_numeric.rb --decimal_numeric 100 + [100, Integer] + $ ruby decimal_numeric.rb --decimal_numeric -100 + [-100, Integer] + $ ruby decimal_numeric.rb --decimal_numeric 0100 + [64, Integer] + +==== \TrueClass + +File +true_class.rb+ +defines an option whose argument is to be converted to +true+ or +false+. +The argument is evaluated by method +{Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. + + :include: true_class.rb + +The argument may be any of those shown in the examples below. + +Executions: + + $ ruby true_class.rb --true_class true + [true, TrueClass] + $ ruby true_class.rb --true_class yes + [true, TrueClass] + $ ruby true_class.rb --true_class + + [true, TrueClass] + $ ruby true_class.rb --true_class false + [false, FalseClass] + $ ruby true_class.rb --true_class no + [false, FalseClass] + $ ruby true_class.rb --true_class - + [false, FalseClass] + $ ruby true_class.rb --true_class nil + [false, FalseClass] + +==== \FalseClass + +File +false_class.rb+ +defines an option whose argument is to be converted to +true+ or +false+. +The argument is evaluated by method +{Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. + + :include: false_class.rb + +The argument may be any of those shown in the examples below. + +Executions: + + $ ruby false_class.rb --false_class false + [false, FalseClass] + $ ruby false_class.rb --false_class no + [false, FalseClass] + $ ruby false_class.rb --false_class - + [false, FalseClass] + $ ruby false_class.rb --false_class nil + [false, FalseClass] + $ ruby false_class.rb --false_class true + [true, TrueClass] + $ ruby false_class.rb --false_class yes + [true, TrueClass] + $ ruby false_class.rb --false_class + + [true, TrueClass] + +==== \Object + +File +object.rb+ +defines an option whose argument is not to be converted from \String. + + :include: object.rb + +Executions: + + $ ruby object.rb --object foo + ["foo", String] + $ ruby object.rb --object nil + ["nil", String] + +==== \String + +File +string.rb+ +defines an option whose argument is not to be converted from \String. + + :include: string.rb + +Executions: + + $ ruby string.rb --string foo + ["foo", String] + $ ruby string.rb --string nil + ["nil", String] + +==== \Array + +File +array.rb+ +defines an option whose argument is to be converted from \String +to an array of strings, based on comma-separated substrings. + + :include: array.rb + +Executions: + + $ ruby array.rb --array "" + [[], Array] + $ ruby array.rb --array foo,bar,baz + [["foo", "bar", "baz"], Array] + $ ruby array.rb --array "foo, bar, baz" + [["foo", " bar", " baz"], Array] + +==== \Regexp + +File +regexp.rb+ +defines an option whose argument is to be converted to a \Regexp object. + + :include: regexp.rb + +Executions: + + $ ruby regexp.rb --regexp foo + +=== Descriptions + +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. + +You may give any number of description parameters; +each becomes a line in the text generated by option --help. + +File +descriptions.rb+ has six strings in its array +descriptions+. +These are all passed as parameters to OptionParser#on, so that they +all, line for line, become the option's description. + + :include: descriptions.rb + +Executions: + + $ ruby descriptions.rb --help + Usage: descriptions [options] + --xxx Lorem ipsum dolor sit amet, consectetuer + adipiscing elit. Aenean commodo ligula eget. + Aenean massa. Cum sociis natoque penatibus + et magnis dis parturient montes, nascetur + ridiculus mus. Donec quam felis, ultricies + nec, pellentesque eu, pretium quis, sem. + $ ruby descriptions.rb --xxx + ["--xxx", true] + +=== Handlers + +The handler for an option is an executable that will be called +when the option is encountered. The handler may be: + +- A block (this is most often seen). +- A proc. +- A method. + +==== Handler Blocks + +An option hadler may be a block. + +File +block.rb+ defines an option that has a handler block. + + :include: block.rb + +Executions: + + $ ruby block.rb --help + Usage: block [options] + --xxx Option with no argument + --yyy YYY Option with required argument + $ ruby block.rb --xxx + ["Handler block for -xxx called with value:", true] + $ ruby block.rb --yyy FOO + ["Handler block for -yyy called with value:", "FOO"] + +==== Handler Procs + +An option handler may be a Proc. + +File +proc.rb+ defines an option that has a handler proc. + + :include: proc.rb + +Executions: + + $ ruby proc.rb --help + Usage: proc [options] + --xxx Option with no argument + --yyy YYY Option with required argument + $ ruby proc.rb --xxx + ["Handler proc for -xxx called with value:", true] + $ ruby proc.rb --yyy FOO + ["Handler proc for -yyy called with value:", "FOO"] + +==== Handler Methods + +An option handler may be a Method. + +File +proc.rb+ defines an option that has a handler method. + + :include: method.rb + +Executions: + + $ ruby method.rb --help + Usage: method [options] + --xxx Option with no argument + --yyy YYY Option with required argument + $ ruby method.rb --xxx + ["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 -- 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 --my_option. + + :include: terminator.rb + +The first execution fails because --nosuch is not a defined option; +the second succeeds because -- causes that option to be ignored: + + $ ruby terminator.rb --my_option FOO --other_option BAR + ["FOO", String] + terminator.rb:6:in `
': invalid option: --other_option (OptionParser::InvalidOption) + $ ruby terminator.rb --my_option FOO -- --other_option BAR + ["FOO", String] diff --git a/doc/option_params/proc.rb b/doc/option_params/proc.rb new file mode 100644 index 0000000..9c669fd --- /dev/null +++ b/doc/option_params/proc.rb @@ -0,0 +1,13 @@ +require 'optparse' +parser = OptionParser.new +parser.on( + '--xxx', + 'Option with no argument', + ->(value) {p ['Handler proc for -xxx called with value:', value]} +) +parser.on( + '--yyy YYY', + 'Option with required argument', + ->(value) {p ['Handler proc for -yyy called with value:', value]} +) +parser.parse! diff --git a/doc/option_params/regexp.rb b/doc/option_params/regexp.rb new file mode 100644 index 0000000..6aba45c --- /dev/null +++ b/doc/option_params/regexp.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--regexp=REGEXP', Regexp) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/shellwords.rb b/doc/option_params/shellwords.rb new file mode 100644 index 0000000..d181d4a --- /dev/null +++ b/doc/option_params/shellwords.rb @@ -0,0 +1,6 @@ +require 'optparse/shellwords' +parser = OptionParser.new +parser.on('--shellwords=SHELLWORDS', Shellwords) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/short_optional.rb b/doc/option_params/short_optional.rb new file mode 100644 index 0000000..6eebf01 --- /dev/null +++ b/doc/option_params/short_optional.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x [XXX]', 'Short name with optional argument') do |value| + p ['-x', value] +end +parser.parse! diff --git a/doc/option_params/short_range.rb b/doc/option_params/short_range.rb new file mode 100644 index 0000000..f5b870a --- /dev/null +++ b/doc/option_params/short_range.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-[!-~]', 'Short names in (very large) range') do |name, value| + p ['!-~', name, value] +end +parser.parse! diff --git a/doc/option_params/short_required.rb b/doc/option_params/short_required.rb new file mode 100644 index 0000000..867c02c --- /dev/null +++ b/doc/option_params/short_required.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-xXXX', 'Short name with required argument') do |value| + p ['-x', value] +end +parser.parse! diff --git a/doc/option_params/short_simple.rb b/doc/option_params/short_simple.rb new file mode 100644 index 0000000..d3d489e --- /dev/null +++ b/doc/option_params/short_simple.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', 'One short name') do |value| + p ['-x', value] +end +parser.on('-1', '-%', 'Two short names (aliases)') do |value| + p ['-1 or -%', value] +end +parser.parse! diff --git a/doc/option_params/string.rb b/doc/option_params/string.rb new file mode 100644 index 0000000..fee84a1 --- /dev/null +++ b/doc/option_params/string.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--string=STRING', String) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/terminator.rb b/doc/option_params/terminator.rb new file mode 100644 index 0000000..c718ac1 --- /dev/null +++ b/doc/option_params/terminator.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--my_option XXX') do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/time.rb b/doc/option_params/time.rb new file mode 100644 index 0000000..aa8b0cf --- /dev/null +++ b/doc/option_params/time.rb @@ -0,0 +1,6 @@ +require 'optparse/time' +parser = OptionParser.new +parser.on('--time=TIME', Time) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/true_class.rb b/doc/option_params/true_class.rb new file mode 100644 index 0000000..40db9d0 --- /dev/null +++ b/doc/option_params/true_class.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--true_class=TRUE_CLASS', TrueClass) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/option_params/uri.rb b/doc/option_params/uri.rb new file mode 100644 index 0000000..b492835 --- /dev/null +++ b/doc/option_params/uri.rb @@ -0,0 +1,6 @@ +require 'optparse/uri' +parser = OptionParser.new +parser.on('--uri=URI', URI) do |value| + p [value, value.class] +end +parser.parse! From d55d9284c3a02a794d63a842764591d4ff079241 Mon Sep 17 00:00:00 2001 From: BurdetteLamar Date: Wed, 7 Apr 2021 11:58:46 -0500 Subject: [PATCH 05/27] Make use of option_params.rdoc --- doc/creates_option.rdoc | 7 +++ doc/option_params/option_params.rdoc | 4 +- lib/optparse.rb | 82 ++++++---------------------- lib/optparse/kwargs.rb | 2 + 4 files changed, 28 insertions(+), 67 deletions(-) create mode 100644 doc/creates_option.rdoc diff --git a/doc/creates_option.rdoc b/doc/creates_option.rdoc new file mode 100644 index 0000000..d006706 --- /dev/null +++ b/doc/creates_option.rdoc @@ -0,0 +1,7 @@ +Creates an option from the given parameters +params+. +See {Parameters for New Options}[doc/option_params/option_params_rdoc.html]. + +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}[doc/option_params/option_params_rdoc.html#label-Option+Handlers]. diff --git a/doc/option_params/option_params.rdoc b/doc/option_params/option_params.rdoc index 7cf5ef8..ebd08f1 100644 --- a/doc/option_params/option_params.rdoc +++ b/doc/option_params/option_params.rdoc @@ -55,7 +55,7 @@ Contents: - {Array}[#label-Array] - {Regexp}[#label-Regexp] - {Descriptions}[#label-Descriptions] -- {Handlers}[#label-Handlers] +- {Option Handlers}[#label-Option+Handlers] - {Handler Blocks}[#label-Handler+Blocks] - {Handler Procs}[#label-Handler+Procs] - {Handler Methods}[#label-Handler+Methods] @@ -759,7 +759,7 @@ Executions: $ ruby descriptions.rb --xxx ["--xxx", true] -=== Handlers +=== Option Handlers The handler for an option is an executable that will be called when the option is encountered. The handler may be: diff --git a/lib/optparse.rb b/lib/optparse.rb index 598ebd1..0f92eba 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -240,14 +240,14 @@ # # require 'optparse' # -# params = {} +# options = {} # OptionParser.new do |parser| # parser.on('-a') # parser.on('-b NUM', Integer) # parser.on('-v', '--verbose') -# end.parse!(into: params) +# end.parse!(into: options) # -# p params +# p options # # Used: # @@ -1314,64 +1314,7 @@ def notwice(obj, prv, msg) # :call-seq: # make_switch(params, block = nil) # - # Creates an OptionParser::Switch from the parameters. The parsed argument - # value is passed to the given block, where it can be processed. - # - # See at the beginning of OptionParser for some full examples. - # - # +params+ can include the following elements: - # - # [Argument style:] - # One of the following: - # :NONE, :REQUIRED, :OPTIONAL - # - # [Argument pattern:] - # Acceptable option argument format, must be pre-defined with - # OptionParser.accept or OptionParser#accept, or Regexp. This can appear - # once or assigned as String if not present, otherwise causes an - # ArgumentError. Examples: - # Float, Time, Array - # - # [Possible argument values:] - # Hash or Array. - # [:text, :binary, :auto] - # %w[iso-2022-jp shift_jis euc-jp utf8 binary] - # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } - # - # [Long style switch:] - # Specifies a long style switch which takes a mandatory, optional or no - # argument. It's a string of the following form: - # "--switch=MANDATORY" or "--switch MANDATORY" - # "--switch[=OPTIONAL]" - # "--switch" - # - # [Short style switch:] - # Specifies short style switch which takes a mandatory, optional or no - # argument. It's a string of the following form: - # "-xMANDATORY" - # "-x[OPTIONAL]" - # "-x" - # There is also a special form which matches character range (not full - # set of regular expression): - # "-[a-z]MANDATORY" - # "-[a-z][OPTIONAL]" - # "-[a-z]" - # - # [Argument style and description:] - # Instead of specifying mandatory or optional arguments directly in the - # switch parameter, this separate parameter can be used. - # "=MANDATORY" - # "=[OPTIONAL]" - # - # [Description:] - # Description string for the option. - # "Run verbosely" - # If you give multiple description strings, each string will be printed - # line by line. - # - # [Handler:] - # Handler for the parsed argument value. Either give a block or pass a - # Proc or Method as an argument. + # :include: ../doc/creates_option.rdoc # def make_switch(opts, block = nil) short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] @@ -1509,6 +1452,8 @@ def make_switch(opts, block = nil) # :call-seq: # define(*params, &block) # + # :include: ../doc/creates_option.rdoc + # def define(*opts, &block) top.append(*(sw = make_switch(opts, block))) sw[0] @@ -1517,8 +1462,7 @@ def define(*opts, &block) # :call-seq: # on(*params, &block) # - # Add option switch and handler. See #make_switch for an explanation of - # parameters. + # :include: ../doc/creates_option.rdoc # def on(*opts, &block) define(*opts, &block) @@ -1529,6 +1473,8 @@ def on(*opts, &block) # :call-seq: # define_head(*params, &block) # + # :include: ../doc/creates_option.rdoc + # def define_head(*opts, &block) top.prepend(*(sw = make_switch(opts, block))) sw[0] @@ -1537,7 +1483,9 @@ def define_head(*opts, &block) # :call-seq: # on_head(*params, &block) # - # Add option switch like with #on, but at head of summary. + # :include: ../doc/creates_option.rdoc + # + # The new option is added at the head of the summary. # def on_head(*opts, &block) define_head(*opts, &block) @@ -1548,6 +1496,8 @@ def on_head(*opts, &block) # :call-seq: # define_tail(*params, &block) # + # :include: ../doc/creates_option.rdoc + # def define_tail(*opts, &block) base.append(*(sw = make_switch(opts, block))) sw[0] @@ -1557,7 +1507,9 @@ def define_tail(*opts, &block) # :call-seq: # on_tail(*params, &block) # - # Add option switch like with #on, but at tail of summary. + # :include: ../doc/creates_option.rdoc + # + # The new option is added at the tail of the summary. # def on_tail(*opts, &block) define_tail(*opts, &block) diff --git a/lib/optparse/kwargs.rb b/lib/optparse/kwargs.rb index 5a2def4..d858faf 100644 --- a/lib/optparse/kwargs.rb +++ b/lib/optparse/kwargs.rb @@ -5,6 +5,8 @@ class OptionParser # :call-seq: # define_by_keywords(options, method, **params) # + # :include: ../../doc/creates_option.rdoc + # def define_by_keywords(options, meth, **opts) meth.parameters.each do |type, name| case type From f3ca83caff20f6daf07a70a3f3f41a6666790b6c Mon Sep 17 00:00:00 2001 From: Olle Jonsson Date: Thu, 8 Apr 2021 05:33:56 +0200 Subject: [PATCH 06/27] gemspec: Explicit files list (#10) This avoid shelling out, and includes a narrower list of files. Co-authored-by: Nobuyoshi Nakada --- optparse.gemspec | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/optparse.gemspec b/optparse.gemspec index b8ec8cf..ae65966 100644 --- a/optparse.gemspec +++ b/optparse.gemspec @@ -22,11 +22,7 @@ Gem::Specification.new do |spec| spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage - spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do - `git ls-files -z`.split("\x0").reject { |f| - f.match(%r{\A(?:(?:test|spec|features)/|Gemfile|\.(?:editor|git))}) - } - end + spec.files = Dir["{doc,lib,misc}/**/*"] + %w[README.md ChangeLog COPYING] spec.bindir = "exe" spec.executables = [] spec.require_paths = ["lib"] From 9a2352c1c9c3445d1618da577f19137243a2a748 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Fri, 9 Apr 2021 08:21:34 -0500 Subject: [PATCH 07/27] Reorganize Ruby example files for sharing (#14) --- doc/creates_option.rdoc | 4 +- doc/{option_params => }/option_params.rdoc | 70 +++++++++---------- doc/option_params/mixed_names.rb | 12 ---- .../argument_keywords.rb | 0 .../argument_strings.rb | 0 doc/{tutorial => ruby}/argv.rb | 0 doc/{option_params => ruby}/array.rb | 0 doc/{option_params => ruby}/block.rb | 0 doc/{option_params => ruby}/date.rb | 0 doc/{option_params => ruby}/datetime.rb | 0 .../decimal_integer.rb | 0 .../decimal_numeric.rb | 0 doc/{option_params => ruby}/descriptions.rb | 0 .../explicit_array_values.rb | 0 .../explicit_hash_values.rb | 0 doc/{option_params => ruby}/false_class.rb | 0 doc/{option_params => ruby}/float.rb | 0 doc/{option_params => ruby}/integer.rb | 0 doc/{option_params => ruby}/long_binary.rb | 0 doc/{tutorial => ruby}/long_names.rb | 0 doc/{option_params => ruby}/long_optional.rb | 0 doc/{option_params => ruby}/long_required.rb | 0 doc/{option_params => ruby}/long_simple.rb | 0 doc/{option_params => ruby}/matched_values.rb | 0 doc/{option_params => ruby}/method.rb | 0 doc/{tutorial => ruby}/mixed_names.rb | 0 doc/{option_params => ruby}/numeric.rb | 0 doc/{option_params => ruby}/object.rb | 0 doc/{option_params => ruby}/octal_integer.rb | 0 doc/{tutorial => ruby}/optional_argument.rb | 0 doc/{option_params => ruby}/proc.rb | 0 doc/{option_params => ruby}/regexp.rb | 0 doc/{tutorial => ruby}/required_argument.rb | 0 doc/{option_params => ruby}/shellwords.rb | 0 doc/{tutorial => ruby}/short_names.rb | 0 doc/{option_params => ruby}/short_optional.rb | 0 doc/{option_params => ruby}/short_range.rb | 0 doc/{option_params => ruby}/short_required.rb | 0 doc/{option_params => ruby}/short_simple.rb | 0 doc/{option_params => ruby}/string.rb | 0 doc/{option_params => ruby}/terminator.rb | 0 doc/{option_params => ruby}/time.rb | 0 doc/{option_params => ruby}/true_class.rb | 0 doc/{option_params => ruby}/uri.rb | 0 doc/{tutorial => }/tutorial.rdoc | 12 ++-- 45 files changed, 43 insertions(+), 55 deletions(-) rename doc/{option_params => }/option_params.rdoc (95%) delete mode 100644 doc/option_params/mixed_names.rb rename doc/{option_params => ruby}/argument_keywords.rb (100%) rename doc/{option_params => ruby}/argument_strings.rb (100%) rename doc/{tutorial => ruby}/argv.rb (100%) rename doc/{option_params => ruby}/array.rb (100%) rename doc/{option_params => ruby}/block.rb (100%) rename doc/{option_params => ruby}/date.rb (100%) rename doc/{option_params => ruby}/datetime.rb (100%) rename doc/{option_params => ruby}/decimal_integer.rb (100%) rename doc/{option_params => ruby}/decimal_numeric.rb (100%) rename doc/{option_params => ruby}/descriptions.rb (100%) rename doc/{option_params => ruby}/explicit_array_values.rb (100%) rename doc/{option_params => ruby}/explicit_hash_values.rb (100%) rename doc/{option_params => ruby}/false_class.rb (100%) rename doc/{option_params => ruby}/float.rb (100%) rename doc/{option_params => ruby}/integer.rb (100%) rename doc/{option_params => ruby}/long_binary.rb (100%) rename doc/{tutorial => ruby}/long_names.rb (100%) rename doc/{option_params => ruby}/long_optional.rb (100%) rename doc/{option_params => ruby}/long_required.rb (100%) rename doc/{option_params => ruby}/long_simple.rb (100%) rename doc/{option_params => ruby}/matched_values.rb (100%) rename doc/{option_params => ruby}/method.rb (100%) rename doc/{tutorial => ruby}/mixed_names.rb (100%) rename doc/{option_params => ruby}/numeric.rb (100%) rename doc/{option_params => ruby}/object.rb (100%) rename doc/{option_params => ruby}/octal_integer.rb (100%) rename doc/{tutorial => ruby}/optional_argument.rb (100%) rename doc/{option_params => ruby}/proc.rb (100%) rename doc/{option_params => ruby}/regexp.rb (100%) rename doc/{tutorial => ruby}/required_argument.rb (100%) rename doc/{option_params => ruby}/shellwords.rb (100%) rename doc/{tutorial => ruby}/short_names.rb (100%) rename doc/{option_params => ruby}/short_optional.rb (100%) rename doc/{option_params => ruby}/short_range.rb (100%) rename doc/{option_params => ruby}/short_required.rb (100%) rename doc/{option_params => ruby}/short_simple.rb (100%) rename doc/{option_params => ruby}/string.rb (100%) rename doc/{option_params => ruby}/terminator.rb (100%) rename doc/{option_params => ruby}/time.rb (100%) rename doc/{option_params => ruby}/true_class.rb (100%) rename doc/{option_params => ruby}/uri.rb (100%) rename doc/{tutorial => }/tutorial.rdoc (96%) diff --git a/doc/creates_option.rdoc b/doc/creates_option.rdoc index d006706..af1ac16 100644 --- a/doc/creates_option.rdoc +++ b/doc/creates_option.rdoc @@ -1,7 +1,7 @@ Creates an option from the given parameters +params+. -See {Parameters for New Options}[doc/option_params/option_params_rdoc.html]. +See {Parameters for New Options}[doc/option_params_rdoc.html]. 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}[doc/option_params/option_params_rdoc.html#label-Option+Handlers]. +See {Option Handlers}[doc/option_params_rdoc.html#label-Option+Handlers]. diff --git a/doc/option_params/option_params.rdoc b/doc/option_params.rdoc similarity index 95% rename from doc/option_params/option_params.rdoc rename to doc/option_params.rdoc index ebd08f1..98d9630 100644 --- a/doc/option_params/option_params.rdoc +++ b/doc/option_params.rdoc @@ -77,7 +77,7 @@ File +short_simple.rb+ defines two options: - One with short name -x. - The other with two short names, in effect, aliases, -1 and -%. - :include: short_simple.rb + :include: ruby/short_simple.rb Executions: @@ -100,7 +100,7 @@ defines an option that requires an argument. File +short_required.rb+ defines an option -x that requires an argument. - :include: short_required.rb + :include: ruby/short_required.rb Executions: @@ -120,7 +120,7 @@ defines an option that allows an optional argument. File +short_optional.rb+ defines an option -x that allows an optional argument. - :include: short_optional.rb + :include: ruby/short_optional.rb Executions: @@ -141,7 +141,7 @@ The parser yields both the actual character cited and the value. File +short_range.rb+ defines an option with short names for all printable characters from ! to ~: - :include: short_range.rb + :include: ruby/short_range.rb Executions: @@ -167,7 +167,7 @@ File +long_simple.rb+ defines two options: - The other with two long names, in effect, aliases, --y1% and --z2#. - :include: long_simple.rb + :include: ruby/long_simple.rb Executions: @@ -190,7 +190,7 @@ defines an option that requires an argument. File +long_required.rb+ defines an option --xxx that requires an argument. - :include: long_required.rb + :include: ruby/long_required.rb Executions: @@ -210,7 +210,7 @@ defines an option that allows an optional argument. File +long_optional.rb+ defines an option --xxx that allows an optional argument. - :include: long_optional.rb + :include: ruby/long_optional.rb Executions: @@ -228,7 +228,7 @@ An option may have both short and long names. File +mixed_names.rb+ defines a mixture of short and long names. - :include: mixed_names.rb + :include: ruby/mixed_names.rb Executions: @@ -272,7 +272,7 @@ which is one of :NONE (the default), File +argument_keywords.rb+ defines an option with a required argument. - :include: argument_keywords.rb + :include: ruby/argument_keywords.rb Executions: @@ -291,7 +291,7 @@ is to define it in a string separate from the name string. File +argument_strings.rb+ defines an option with a required argument. - :include: argument_strings.rb + :include: ruby/argument_strings.rb Executions: @@ -323,7 +323,7 @@ The argument value must be one of those strings. File +explicit_array_values.rb+ defines options with explicit argument values. - :include: explicit_array_values.rb + :include: ruby/explicit_array_values.rb Executions: @@ -349,7 +349,7 @@ and the value yielded will be the value for that key. File +explicit_hash_values.rb+ defines options with explicit argument values. - :include: explicit_hash_values.rb + :include: ruby/explicit_hash_values.rb Executions: @@ -381,7 +381,7 @@ by specifying a Regexp that the given argument must match. File +matched_values.rb+ defines options with matched argument values. - :include: matched_values.rb + :include: ruby/matched_values.rb Executions: @@ -410,7 +410,7 @@ defines an option whose argument is to be converted to a \Date object. The argument is converted by method {Date.parse}[https://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html#method-c-parse]. - :include: date.rb + :include: ruby/date.rb Executions: @@ -428,7 +428,7 @@ defines an option whose argument is to be converted to a \DateTime object. The argument is converted by method {DateTime.parse}[https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/DateTime.html#method-c-parse]. - :include: datetime.rb + :include: ruby/datetime.rb Executions: @@ -447,7 +447,7 @@ The argument is converted by method {Time.httpdate}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-httpdate] or {Time.parse}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-parse]. - :include: time.rb + :include: ruby/time.rb Executions: @@ -463,7 +463,7 @@ defines an option whose argument is to be converted to a \URI object. The argument is converted by method {URI.parse}[https://ruby-doc.org/stdlib-2.7.2/libdoc/uri/rdoc/URI.html#method-c-parse]. - :include: uri.rb + :include: ruby/uri.rb Executions: @@ -480,7 +480,7 @@ File +shellwords.rb+ defines an option whose argument is to be converted to an \Array object by method {Shellwords.shellwords}[https://ruby-doc.org/stdlib-2.7.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellwords]. - :include: shellwords.rb + :include: ruby/shellwords.rb Executions: @@ -496,7 +496,7 @@ defines an option whose argument is to be converted to an \Integer object. The argument is converted by method {Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - :include: integer.rb + :include: ruby/integer.rb Executions: @@ -518,7 +518,7 @@ defines an option whose argument is to be converted to a \Float object. The argument is converted by method {Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float]. - :include: float.rb + :include: ruby/float.rb Executions: @@ -541,7 +541,7 @@ The argument is converted by method {Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float], or {Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - :include: numeric.rb + :include: ruby/numeric.rb Executions: @@ -559,7 +559,7 @@ defines an option whose argument is to be converted to an \Integer object. The argument is converted by method {Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - :include: decimal_integer.rb + :include: ruby/decimal_integer.rb The argument may not be in a binary or hexadecimal format; a leading zero is ignored (not parsed as octal). @@ -582,7 +582,7 @@ defines an option whose argument is to be converted to an \Integer object. The argument is converted by method {Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - :include: octal_integer.rb + :include: ruby/octal_integer.rb The argument may not be in a binary or hexadecimal format; it is parsed as octal, regardless of whether it has a leading zero. @@ -603,7 +603,7 @@ defines an option whose argument is to be converted to an \Integer object. The argument is converted by method {Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - :include: decimal_numeric.rb + :include: ruby/decimal_numeric.rb The argument may not be in a binary or hexadecimal format; a leading zero causes the argument to be parsed as octal. @@ -624,7 +624,7 @@ defines an option whose argument is to be converted to +true+ or +false+. The argument is evaluated by method {Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. - :include: true_class.rb + :include: ruby/true_class.rb The argument may be any of those shown in the examples below. @@ -652,7 +652,7 @@ defines an option whose argument is to be converted to +true+ or +false+. The argument is evaluated by method {Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. - :include: false_class.rb + :include: ruby/false_class.rb The argument may be any of those shown in the examples below. @@ -678,7 +678,7 @@ Executions: File +object.rb+ defines an option whose argument is not to be converted from \String. - :include: object.rb + :include: ruby/object.rb Executions: @@ -692,7 +692,7 @@ Executions: File +string.rb+ defines an option whose argument is not to be converted from \String. - :include: string.rb + :include: ruby/string.rb Executions: @@ -707,7 +707,7 @@ File +array.rb+ defines an option whose argument is to be converted from \String to an array of strings, based on comma-separated substrings. - :include: array.rb + :include: ruby/array.rb Executions: @@ -723,7 +723,7 @@ Executions: File +regexp.rb+ defines an option whose argument is to be converted to a \Regexp object. - :include: regexp.rb + :include: ruby/regexp.rb Executions: @@ -744,7 +744,7 @@ File +descriptions.rb+ has six strings in its array +descriptions+. These are all passed as parameters to OptionParser#on, so that they all, line for line, become the option's description. - :include: descriptions.rb + :include: ruby/descriptions.rb Executions: @@ -774,7 +774,7 @@ An option hadler may be a block. File +block.rb+ defines an option that has a handler block. - :include: block.rb + :include: ruby/block.rb Executions: @@ -793,7 +793,7 @@ An option handler may be a Proc. File +proc.rb+ defines an option that has a handler proc. - :include: proc.rb + :include: ruby/proc.rb Executions: @@ -812,7 +812,7 @@ An option handler may be a Method. File +proc.rb+ defines an option that has a handler method. - :include: method.rb + :include: ruby/method.rb Executions: @@ -833,7 +833,7 @@ This can be useful if there are options not meant for the current program. File +terminator.rb+ defines one option --my_option. - :include: terminator.rb + :include: ruby/terminator.rb The first execution fails because --nosuch is not a defined option; the second succeeds because -- causes that option to be ignored: diff --git a/doc/option_params/mixed_names.rb b/doc/option_params/mixed_names.rb deleted file mode 100644 index fe6c554..0000000 --- a/doc/option_params/mixed_names.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'optparse' -parser = OptionParser.new -parser.on('-x', '--xxx', 'Short and long, simple') do |value| - p ['--xxx', value] -end -parser.on('-yYYY', '--yyy', 'Short and long, required argument') do |value| - p ['--yyy', value] -end -parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') do |value| - p ['--zzz', value] -end -parser.parse! diff --git a/doc/option_params/argument_keywords.rb b/doc/ruby/argument_keywords.rb similarity index 100% rename from doc/option_params/argument_keywords.rb rename to doc/ruby/argument_keywords.rb diff --git a/doc/option_params/argument_strings.rb b/doc/ruby/argument_strings.rb similarity index 100% rename from doc/option_params/argument_strings.rb rename to doc/ruby/argument_strings.rb diff --git a/doc/tutorial/argv.rb b/doc/ruby/argv.rb similarity index 100% rename from doc/tutorial/argv.rb rename to doc/ruby/argv.rb diff --git a/doc/option_params/array.rb b/doc/ruby/array.rb similarity index 100% rename from doc/option_params/array.rb rename to doc/ruby/array.rb diff --git a/doc/option_params/block.rb b/doc/ruby/block.rb similarity index 100% rename from doc/option_params/block.rb rename to doc/ruby/block.rb diff --git a/doc/option_params/date.rb b/doc/ruby/date.rb similarity index 100% rename from doc/option_params/date.rb rename to doc/ruby/date.rb diff --git a/doc/option_params/datetime.rb b/doc/ruby/datetime.rb similarity index 100% rename from doc/option_params/datetime.rb rename to doc/ruby/datetime.rb diff --git a/doc/option_params/decimal_integer.rb b/doc/ruby/decimal_integer.rb similarity index 100% rename from doc/option_params/decimal_integer.rb rename to doc/ruby/decimal_integer.rb diff --git a/doc/option_params/decimal_numeric.rb b/doc/ruby/decimal_numeric.rb similarity index 100% rename from doc/option_params/decimal_numeric.rb rename to doc/ruby/decimal_numeric.rb diff --git a/doc/option_params/descriptions.rb b/doc/ruby/descriptions.rb similarity index 100% rename from doc/option_params/descriptions.rb rename to doc/ruby/descriptions.rb diff --git a/doc/option_params/explicit_array_values.rb b/doc/ruby/explicit_array_values.rb similarity index 100% rename from doc/option_params/explicit_array_values.rb rename to doc/ruby/explicit_array_values.rb diff --git a/doc/option_params/explicit_hash_values.rb b/doc/ruby/explicit_hash_values.rb similarity index 100% rename from doc/option_params/explicit_hash_values.rb rename to doc/ruby/explicit_hash_values.rb diff --git a/doc/option_params/false_class.rb b/doc/ruby/false_class.rb similarity index 100% rename from doc/option_params/false_class.rb rename to doc/ruby/false_class.rb diff --git a/doc/option_params/float.rb b/doc/ruby/float.rb similarity index 100% rename from doc/option_params/float.rb rename to doc/ruby/float.rb diff --git a/doc/option_params/integer.rb b/doc/ruby/integer.rb similarity index 100% rename from doc/option_params/integer.rb rename to doc/ruby/integer.rb diff --git a/doc/option_params/long_binary.rb b/doc/ruby/long_binary.rb similarity index 100% rename from doc/option_params/long_binary.rb rename to doc/ruby/long_binary.rb diff --git a/doc/tutorial/long_names.rb b/doc/ruby/long_names.rb similarity index 100% rename from doc/tutorial/long_names.rb rename to doc/ruby/long_names.rb diff --git a/doc/option_params/long_optional.rb b/doc/ruby/long_optional.rb similarity index 100% rename from doc/option_params/long_optional.rb rename to doc/ruby/long_optional.rb diff --git a/doc/option_params/long_required.rb b/doc/ruby/long_required.rb similarity index 100% rename from doc/option_params/long_required.rb rename to doc/ruby/long_required.rb diff --git a/doc/option_params/long_simple.rb b/doc/ruby/long_simple.rb similarity index 100% rename from doc/option_params/long_simple.rb rename to doc/ruby/long_simple.rb diff --git a/doc/option_params/matched_values.rb b/doc/ruby/matched_values.rb similarity index 100% rename from doc/option_params/matched_values.rb rename to doc/ruby/matched_values.rb diff --git a/doc/option_params/method.rb b/doc/ruby/method.rb similarity index 100% rename from doc/option_params/method.rb rename to doc/ruby/method.rb diff --git a/doc/tutorial/mixed_names.rb b/doc/ruby/mixed_names.rb similarity index 100% rename from doc/tutorial/mixed_names.rb rename to doc/ruby/mixed_names.rb diff --git a/doc/option_params/numeric.rb b/doc/ruby/numeric.rb similarity index 100% rename from doc/option_params/numeric.rb rename to doc/ruby/numeric.rb diff --git a/doc/option_params/object.rb b/doc/ruby/object.rb similarity index 100% rename from doc/option_params/object.rb rename to doc/ruby/object.rb diff --git a/doc/option_params/octal_integer.rb b/doc/ruby/octal_integer.rb similarity index 100% rename from doc/option_params/octal_integer.rb rename to doc/ruby/octal_integer.rb diff --git a/doc/tutorial/optional_argument.rb b/doc/ruby/optional_argument.rb similarity index 100% rename from doc/tutorial/optional_argument.rb rename to doc/ruby/optional_argument.rb diff --git a/doc/option_params/proc.rb b/doc/ruby/proc.rb similarity index 100% rename from doc/option_params/proc.rb rename to doc/ruby/proc.rb diff --git a/doc/option_params/regexp.rb b/doc/ruby/regexp.rb similarity index 100% rename from doc/option_params/regexp.rb rename to doc/ruby/regexp.rb diff --git a/doc/tutorial/required_argument.rb b/doc/ruby/required_argument.rb similarity index 100% rename from doc/tutorial/required_argument.rb rename to doc/ruby/required_argument.rb diff --git a/doc/option_params/shellwords.rb b/doc/ruby/shellwords.rb similarity index 100% rename from doc/option_params/shellwords.rb rename to doc/ruby/shellwords.rb diff --git a/doc/tutorial/short_names.rb b/doc/ruby/short_names.rb similarity index 100% rename from doc/tutorial/short_names.rb rename to doc/ruby/short_names.rb diff --git a/doc/option_params/short_optional.rb b/doc/ruby/short_optional.rb similarity index 100% rename from doc/option_params/short_optional.rb rename to doc/ruby/short_optional.rb diff --git a/doc/option_params/short_range.rb b/doc/ruby/short_range.rb similarity index 100% rename from doc/option_params/short_range.rb rename to doc/ruby/short_range.rb diff --git a/doc/option_params/short_required.rb b/doc/ruby/short_required.rb similarity index 100% rename from doc/option_params/short_required.rb rename to doc/ruby/short_required.rb diff --git a/doc/option_params/short_simple.rb b/doc/ruby/short_simple.rb similarity index 100% rename from doc/option_params/short_simple.rb rename to doc/ruby/short_simple.rb diff --git a/doc/option_params/string.rb b/doc/ruby/string.rb similarity index 100% rename from doc/option_params/string.rb rename to doc/ruby/string.rb diff --git a/doc/option_params/terminator.rb b/doc/ruby/terminator.rb similarity index 100% rename from doc/option_params/terminator.rb rename to doc/ruby/terminator.rb diff --git a/doc/option_params/time.rb b/doc/ruby/time.rb similarity index 100% rename from doc/option_params/time.rb rename to doc/ruby/time.rb diff --git a/doc/option_params/true_class.rb b/doc/ruby/true_class.rb similarity index 100% rename from doc/option_params/true_class.rb rename to doc/ruby/true_class.rb diff --git a/doc/option_params/uri.rb b/doc/ruby/uri.rb similarity index 100% rename from doc/option_params/uri.rb rename to doc/ruby/uri.rb diff --git a/doc/tutorial/tutorial.rdoc b/doc/tutorial.rdoc similarity index 96% rename from doc/tutorial/tutorial.rdoc rename to doc/tutorial.rdoc index 60ead0a..5e95f20 100644 --- a/doc/tutorial/tutorial.rdoc +++ b/doc/tutorial.rdoc @@ -6,7 +6,7 @@ When a Ruby program executes, it captures its command-line arguments and options into variable ARGV. This simple program just prints its \ARGV: - :include: argv.rb + :include: ruby/argv.rb Execution, with arguments and options: @@ -67,7 +67,7 @@ File +short_names.rb+ defines an option with a short name, -x, and an option with two short names (aliases, in effect) -y and -z. - :include: short_names.rb + :include: ruby/short_names.rb Executions: @@ -99,7 +99,7 @@ File +long_names.rb+ defines an option with a long name, --xxx, and an option with two long names (aliases, in effect) --y1% and --z2#. - :include: long_names.rb + :include: ruby/long_names.rb Executions: @@ -118,7 +118,7 @@ so that a short name is in effect an abbreviation of a long name. File +mixed_names.rb+ defines options that each have both a short and a long name. - :include: mixed_names.rb + :include: ruby/mixed_names.rb Executions: @@ -147,7 +147,7 @@ to its name definition. File +required_argument.rb+ defines two options; each has a required argument because the name definition has a following dummy word. - :include: required_argument.rb + :include: ruby/required_argument.rb When an option is found, the given argument is yielded. @@ -172,7 +172,7 @@ File +optional_argument.rb+ defines two options; each has an optional argument because the name definition has a following dummy word in square brackets. - :include: optional_argument.rb + :include: ruby/optional_argument.rb When an option with an argument is found, the given argument yielded. From c91ed8d33db7355cf0a5a8323f3f6aad57e18b38 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Sat, 10 Apr 2021 10:05:44 -0500 Subject: [PATCH 08/27] Rdoc (#15) * Resolve shared mixed_names.rb * Add long option with negation * Show --help for all examples * Table of contents for tutorial * Move argument converters to separate rdoc * Add references to argument_converters.rdoc * Tune up argument converters * Change explicit links to auto-links --- doc/argument_converters.rdoc | 362 +++++++++++++++++ doc/option_params.rdoc | 376 ++---------------- doc/ruby/custom_converter.rb | 9 + doc/ruby/long_names.rb | 4 +- .../{long_binary.rb => long_with_negation.rb} | 2 +- doc/ruby/mixed_names.rb | 9 +- doc/ruby/optional_argument.rb | 4 +- doc/ruby/required_argument.rb | 4 +- doc/ruby/short_names.rb | 4 +- doc/tutorial.rdoc | 78 +++- 10 files changed, 487 insertions(+), 365 deletions(-) create mode 100644 doc/argument_converters.rdoc create mode 100644 doc/ruby/custom_converter.rb rename doc/ruby/{long_binary.rb => long_with_negation.rb} (57%) diff --git a/doc/argument_converters.rdoc b/doc/argument_converters.rdoc new file mode 100644 index 0000000..fc5a015 --- /dev/null +++ b/doc/argument_converters.rdoc @@ -0,0 +1,362 @@ +== Argument Converters + +An option can specify that its argument is to be converted +from the default \String to an instance of another class. + +=== Contents + +- {Built-In Argument Converters}[#label-Built-In+Argument+Converters] + - {Date}[#label-Date] + - {DateTime}[#label-DateTime] + - {Time}[#label-Time] + - {URI}[#label-URI] + - {Shellwords}[#label-Shellwords] + - {Integer}[#label-Integer] + - {Float}[#label-Float] + - {Numeric}[#label-Numeric] + - {DecimalInteger}[#label-DecimalInteger] + - {OctalInteger}[#label-OctalInteger] + - {DecimalNumeric}[#label-DecimalNumeric] + - {TrueClass}[#label-TrueClass] + - {FalseClass}[#label-FalseClass] + - {Object}[#label-Object] + - {String}[#label-String] + - {Array}[#label-Array] + - {Regexp}[#label-Regexp] +- {Custom Argument Converters}[#label-Custom+Argument+Converters] + +=== Built-In Argument Converters + +\OptionParser has a number of built-in argument converters, +which are demonstrated below. + +==== \Date + +File +date.rb+ +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 + +Executions: + + $ ruby date.rb --date 2001-02-03 + [#, Date] + $ ruby date.rb --date 20010203 + [#, Date] + $ ruby date.rb --date "3rd Feb 2001" + [#, Date] + +==== \DateTime + +File +datetime.rb+ +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 + +Executions: + + $ ruby datetime.rb --datetime 2001-02-03T04:05:06+07:00 + [#, DateTime] + $ ruby datetime.rb --datetime 20010203T040506+0700 + [#, DateTime] + $ ruby datetime.rb --datetime "3rd Feb 2001 04:05:06 PM" + [#, DateTime] + +==== \Time + +File +time.rb+ +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 + +Executions: + + $ ruby time.rb --time "Thu, 06 Oct 2011 02:26:12 GMT" + [2011-10-06 02:26:12 UTC, Time] + $ ruby time.rb --time 2010-10-31 + [2010-10-31 00:00:00 -0500, Time] + +==== \URI + +File +uri.rb+ +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 + +Executions: + + $ ruby uri.rb --uri https://github.com + [#, URI::HTTPS] + $ ruby uri.rb --uri http://github.com + [#, URI::HTTP] + $ ruby uri.rb --uri file://~/var + [#, URI::File] + +==== \Shellwords + +File +shellwords.rb+ +defines an option whose argument is to be converted to an \Array object by method +Shellwords#shellwords. + + :include: ruby/shellwords.rb + +Executions: + + $ ruby shellwords.rb --shellwords "ruby my_prog.rb | less" + [["ruby", "my_prog.rb", "|", "less"], Array] + $ ruby shellwords.rb --shellwords "here are 'two words'" + [["here", "are", "two words"], Array] + +==== \Integer + +File +integer.rb+ +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 + +Executions: + + $ ruby integer.rb --integer 100 + [100, Integer] + $ ruby integer.rb --integer -100 + [-100, Integer] + $ ruby integer.rb --integer 0100 + [64, Integer] + $ ruby integer.rb --integer 0x100 + [256, Integer] + $ ruby integer.rb --integer 0b100 + [4, Integer] + +==== \Float + +File +float.rb+ +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 + +Executions: + + $ ruby float.rb --float 1 + [1.0, Float] + $ ruby float.rb --float 3.14159 + [3.14159, Float] + $ ruby float.rb --float 1.234E2 + [123.4, Float] + $ ruby float.rb --float 1.234E-2 + [0.01234, Float] + +==== \Numeric + +File +numeric.rb+ +defines an option whose argument is to be converted to an instance +of \Rational, \Float, or \Integer. +The argument is converted by method Kernel#Rational, +Kernel#Float, or Kernel#Integer. + + :include: ruby/numeric.rb + +Executions: + + $ ruby numeric.rb --numeric 1/3 + [(1/3), Rational] + $ ruby numeric.rb --numeric 3.333E-1 + [0.3333, Float] + $ ruby numeric.rb --numeric 3 + [3, Integer] + +==== \DecimalInteger + +File +decimal_integer.rb+ +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 + +The argument may not be in a binary or hexadecimal format; +a leading zero is ignored (not parsed as octal). + +Executions: + + $ ruby decimal_integer.rb --decimal_integer 100 + [100, Integer] + $ ruby decimal_integer.rb --decimal_integer -100 + [-100, Integer] + $ ruby decimal_integer.rb --decimal_integer 0100 + [100, Integer] + $ ruby decimal_integer.rb --decimal_integer -0100 + [-100, Integer] + +==== \OctalInteger + +File +octal_integer.rb+ +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 + +The argument may not be in a binary or hexadecimal format; +it is parsed as octal, regardless of whether it has a leading zero. + +Executions: + + $ ruby octal_integer.rb --octal_integer 100 + [64, Integer] + $ ruby octal_integer.rb --octal_integer -100 + [-64, Integer] + $ ruby octal_integer.rb --octal_integer 0100 + [64, Integer] + +==== \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 + + :include: ruby/decimal_numeric.rb + +The argument may not be in a binary or hexadecimal format; +a leading zero causes the argument to be parsed as octal. + +Executions: + + $ ruby decimal_numeric.rb --decimal_numeric 100 + [100, Integer] + $ ruby decimal_numeric.rb --decimal_numeric -100 + [-100, Integer] + $ ruby decimal_numeric.rb --decimal_numeric 0100 + [64, Integer] + +==== \TrueClass + +File +true_class.rb+ +defines an option whose argument is to be converted to +true+ or +false+. +The argument is evaluated by method Object#nil?. + + :include: ruby/true_class.rb + +The argument may be any of those shown in the examples below. + +Executions: + + $ ruby true_class.rb --true_class true + [true, TrueClass] + $ ruby true_class.rb --true_class yes + [true, TrueClass] + $ ruby true_class.rb --true_class + + [true, TrueClass] + $ ruby true_class.rb --true_class false + [false, FalseClass] + $ ruby true_class.rb --true_class no + [false, FalseClass] + $ ruby true_class.rb --true_class - + [false, FalseClass] + $ ruby true_class.rb --true_class nil + [false, FalseClass] + +==== \FalseClass + +File +false_class.rb+ +defines an option whose argument is to be converted to +true+ or +false+. +The argument is evaluated by method Object#nil?. + + :include: ruby/false_class.rb + +The argument may be any of those shown in the examples below. + +Executions: + + $ ruby false_class.rb --false_class false + [false, FalseClass] + $ ruby false_class.rb --false_class no + [false, FalseClass] + $ ruby false_class.rb --false_class - + [false, FalseClass] + $ ruby false_class.rb --false_class nil + [false, FalseClass] + $ ruby false_class.rb --false_class true + [true, TrueClass] + $ ruby false_class.rb --false_class yes + [true, TrueClass] + $ ruby false_class.rb --false_class + + [true, TrueClass] + +==== \Object + +File +object.rb+ +defines an option whose argument is not to be converted from \String. + + :include: ruby/object.rb + +Executions: + + $ ruby object.rb --object foo + ["foo", String] + $ ruby object.rb --object nil + ["nil", String] + +==== \String + +File +string.rb+ +defines an option whose argument is not to be converted from \String. + + :include: ruby/string.rb + +Executions: + + $ ruby string.rb --string foo + ["foo", String] + $ ruby string.rb --string nil + ["nil", String] + +==== \Array + +File +array.rb+ +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 + +Executions: + + $ ruby array.rb --array "" + [[], Array] + $ ruby array.rb --array foo,bar,baz + [["foo", "bar", "baz"], Array] + $ ruby array.rb --array "foo, bar, baz" + [["foo", " bar", " baz"], Array] + +==== \Regexp + +File +regexp.rb+ +defines an option whose argument is to be converted to a \Regexp object. + + :include: ruby/regexp.rb + +Executions: + + $ ruby regexp.rb --regexp foo + +=== 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. + + :include: ruby/custom_converter.rb + +Executions: + + $ ruby custom_converter.rb --complex 0 + [(0+0i), Complex] + $ ruby custom_converter.rb --complex 1 + [(1+0i), Complex] + $ ruby custom_converter.rb --complex 1+2i + [(1+2i), Complex] + $ ruby custom_converter.rb --complex 0.3-0.5i + [(0.3-0.5i), Complex] diff --git a/doc/option_params.rdoc b/doc/option_params.rdoc index 98d9630..0d06b41 100644 --- a/doc/option_params.rdoc +++ b/doc/option_params.rdoc @@ -29,6 +29,7 @@ Contents: - {Simple Long Names}[#label-Simple+Long+Names] - {Long Names with Required Arguments}[#label-Long+Names+with+Required+Arguments] - {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 Values}[#label-Argument+Values] @@ -37,23 +38,6 @@ Contents: - {Explicit Values in Hash}[#label-Explicit+Values+in+Hash] - {Argument Value Patterns}[#label-Argument+Value+Patterns] - {Argument Converters}[#label-Argument+Converters] - - {Date}[#label-Date] - - {DateTime}[#label-DateTime] - - {Time}[#label-Time] - - {URI}[#label-URI] - - {Shellwords}[#label-Shellwords] - - {Integer}[#label-Integer] - - {Float}[#label-Float] - - {Numeric}[#label-Numeric] - - {DecimalInteger}[#label-DecimalInteger] - - {OctalInteger}[#label-OctalInteger] - - {DecimalNumeric}[#label-DecimalNumeric] - - {TrueClass}[#label-TrueClass] - - {FalseClass}[#label-FalseClass] - - {Object}[#label-Object] - - {String}[#label-String] - - {Array}[#label-Array] - - {Regexp}[#label-Regexp] - {Descriptions}[#label-Descriptions] - {Option Handlers}[#label-Option+Handlers] - {Handler Blocks}[#label-Handler+Blocks] @@ -222,6 +206,24 @@ Executions: $ ruby long_optional.rb --xxx FOO ["--xxx", "FOO"] +===== Long Names with Negation + +A long name may be defined with both positive and negative senses. + +File +long_with_negation.rb+ defines an option that has both senses. + + :include: ruby/long_with_negation.rb + +Executions: + + $ ruby long_with_negation.rb --help + Usage: long_with_negation [options] + --[no-]binary Long name with negation + $ ruby long_with_negation.rb --binary + [true, TrueClass] + $ ruby long_with_negation.rb --no-binary + [false, FalseClass] + ==== Mixed Names An option may have both short and long names. @@ -233,12 +235,10 @@ File +mixed_names.rb+ defines a mixture of short and long names. Executions: $ ruby mixed_names.rb --help - Usage: mixed_names [options] - -x, --xxx Short and long, simple - --yyy yYYY - Short and long, required argument - --zzz zZZZ - Short and long, optional argument +Usage: mixed_names [options] + -x, --xxx Short and long, no argument + -y, --yyyYYY Short and long, required argument + -z, --zzz [ZZZ] Short and long, optional argument $ ruby mixed_names.rb -x ["--xxx", true] $ ruby mixed_names.rb --xxx @@ -400,334 +400,10 @@ Executions: An option can specify that its argument is to be converted from the default \String to an instance of another class. -\OptionParser has a number of built-in converters, -which are demonstrated below. - -==== \Date - -File +date.rb+ -defines an option whose argument is to be converted to a \Date object. -The argument is converted by method -{Date.parse}[https://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html#method-c-parse]. - - :include: ruby/date.rb - -Executions: - - $ ruby date.rb --date 2001-02-03 - [#, Date] - $ ruby date.rb --date 20010203 - [#, Date] - $ ruby date.rb --date "3rd Feb 2001" - [#, Date] - -==== \DateTime - -File +datetime.rb+ -defines an option whose argument is to be converted to a \DateTime object. -The argument is converted by method -{DateTime.parse}[https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/DateTime.html#method-c-parse]. - - :include: ruby/datetime.rb - -Executions: - - $ ruby datetime.rb --datetime 2001-02-03T04:05:06+07:00 - [#, DateTime] - $ ruby datetime.rb --datetime 20010203T040506+0700 - [#, DateTime] - $ ruby datetime.rb --datetime "3rd Feb 2001 04:05:06 PM" - [#, DateTime] - -==== \Time - -File +time.rb+ -defines an option whose argument is to be converted to a \Time object. -The argument is converted by method -{Time.httpdate}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-httpdate] or -{Time.parse}[https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html#method-c-parse]. - - :include: ruby/time.rb - -Executions: - - $ ruby time.rb --time "Thu, 06 Oct 2011 02:26:12 GMT" - [2011-10-06 02:26:12 UTC, Time] - $ ruby time.rb --time 2010-10-31 - [2010-10-31 00:00:00 -0500, Time] - -==== \URI - -File +uri.rb+ -defines an option whose argument is to be converted to a \URI object. -The argument is converted by method -{URI.parse}[https://ruby-doc.org/stdlib-2.7.2/libdoc/uri/rdoc/URI.html#method-c-parse]. - - :include: ruby/uri.rb - -Executions: - - $ ruby uri.rb --uri https://github.com - [#, URI::HTTPS] - $ ruby uri.rb --uri http://github.com - [#, URI::HTTP] - $ ruby uri.rb --uri file://~/var - [#, URI::File] - -==== \Shellwords - -File +shellwords.rb+ -defines an option whose argument is to be converted to an \Array object by method -{Shellwords.shellwords}[https://ruby-doc.org/stdlib-2.7.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellwords]. - - :include: ruby/shellwords.rb - -Executions: - - $ ruby shellwords.rb --shellwords "ruby my_prog.rb | less" - [["ruby", "my_prog.rb", "|", "less"], Array] - $ ruby shellwords.rb --shellwords "here are 'two words'" - [["here", "are", "two words"], Array] - -==== \Integer - -File +integer.rb+ -defines an option whose argument is to be converted to an \Integer object. -The argument is converted by method -{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - - :include: ruby/integer.rb - -Executions: - - $ ruby integer.rb --integer 100 - [100, Integer] - $ ruby integer.rb --integer -100 - [-100, Integer] - $ ruby integer.rb --integer 0100 - [64, Integer] - $ ruby integer.rb --integer 0x100 - [256, Integer] - $ ruby integer.rb --integer 0b100 - [4, Integer] - -==== \Float - -File +float.rb+ -defines an option whose argument is to be converted to a \Float object. -The argument is converted by method -{Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float]. - - :include: ruby/float.rb - -Executions: - - $ ruby float.rb --float 1 - [1.0, Float] - $ ruby float.rb --float 3.14159 - [3.14159, Float] - $ ruby float.rb --float 1.234E2 - [123.4, Float] - $ ruby float.rb --float 1.234E-2 - [0.01234, Float] - -==== \Numeric - -File +numeric.rb+ -defines an option whose argument is to be converted to an instance -of \Rational, \Float, or \Integer. -The argument is converted by method -{Kernel.Rational}[https://ruby-doc.org/core/Kernel.html#method-i-Rational], -{Kernel.Float}[https://ruby-doc.org/core/Kernel.html#method-i-Float], or -{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - - :include: ruby/numeric.rb - -Executions: - - $ ruby numeric.rb --numeric 1/3 - [(1/3), Rational] - $ ruby numeric.rb --numeric 3.333E-1 - [0.3333, Float] - $ ruby numeric.rb --numeric 3 - [3, Integer] - -==== \DecimalInteger - -File +decimal_integer.rb+ -defines an option whose argument is to be converted to an \Integer object. -The argument is converted by method -{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - - :include: ruby/decimal_integer.rb - -The argument may not be in a binary or hexadecimal format; -a leading zero is ignored (not parsed as octal). - -Executions: - - $ ruby decimal_integer.rb --decimal_integer 100 - [100, Integer] - $ ruby decimal_integer.rb --decimal_integer -100 - [-100, Integer] - $ ruby decimal_integer.rb --decimal_integer 0100 - [100, Integer] - $ ruby decimal_integer.rb --decimal_integer -0100 - [-100, Integer] - -==== \OctalInteger - -File +octal_integer.rb+ -defines an option whose argument is to be converted to an \Integer object. -The argument is converted by method -{Kernel.Integer}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - - :include: ruby/octal_integer.rb - -The argument may not be in a binary or hexadecimal format; -it is parsed as octal, regardless of whether it has a leading zero. - -Executions: - - $ ruby octal_integer.rb --octal_integer 100 - [64, Integer] - $ ruby octal_integer.rb --octal_integer -100 - [-64, Integer] - $ ruby octal_integer.rb --octal_integer 0100 - [64, Integer] - -==== \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}[https://ruby-doc.org/core/Kernel.html#method-i-Integer]. - - :include: ruby/decimal_numeric.rb - -The argument may not be in a binary or hexadecimal format; -a leading zero causes the argument to be parsed as octal. - -Executions: - - $ ruby decimal_numeric.rb --decimal_numeric 100 - [100, Integer] - $ ruby decimal_numeric.rb --decimal_numeric -100 - [-100, Integer] - $ ruby decimal_numeric.rb --decimal_numeric 0100 - [64, Integer] - -==== \TrueClass - -File +true_class.rb+ -defines an option whose argument is to be converted to +true+ or +false+. -The argument is evaluated by method -{Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. - - :include: ruby/true_class.rb - -The argument may be any of those shown in the examples below. - -Executions: - - $ ruby true_class.rb --true_class true - [true, TrueClass] - $ ruby true_class.rb --true_class yes - [true, TrueClass] - $ ruby true_class.rb --true_class + - [true, TrueClass] - $ ruby true_class.rb --true_class false - [false, FalseClass] - $ ruby true_class.rb --true_class no - [false, FalseClass] - $ ruby true_class.rb --true_class - - [false, FalseClass] - $ ruby true_class.rb --true_class nil - [false, FalseClass] - -==== \FalseClass - -File +false_class.rb+ -defines an option whose argument is to be converted to +true+ or +false+. -The argument is evaluated by method -{Object#nil?}[https://ruby-doc.org/core-3.0.0/Object.html#method-i-nil-3F]. - - :include: ruby/false_class.rb - -The argument may be any of those shown in the examples below. - -Executions: - - $ ruby false_class.rb --false_class false - [false, FalseClass] - $ ruby false_class.rb --false_class no - [false, FalseClass] - $ ruby false_class.rb --false_class - - [false, FalseClass] - $ ruby false_class.rb --false_class nil - [false, FalseClass] - $ ruby false_class.rb --false_class true - [true, TrueClass] - $ ruby false_class.rb --false_class yes - [true, TrueClass] - $ ruby false_class.rb --false_class + - [true, TrueClass] - -==== \Object - -File +object.rb+ -defines an option whose argument is not to be converted from \String. - - :include: ruby/object.rb - -Executions: - - $ ruby object.rb --object foo - ["foo", String] - $ ruby object.rb --object nil - ["nil", String] - -==== \String - -File +string.rb+ -defines an option whose argument is not to be converted from \String. - - :include: ruby/string.rb - -Executions: - - $ ruby string.rb --string foo - ["foo", String] - $ ruby string.rb --string nil - ["nil", String] - -==== \Array - -File +array.rb+ -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 - -Executions: - - $ ruby array.rb --array "" - [[], Array] - $ ruby array.rb --array foo,bar,baz - [["foo", "bar", "baz"], Array] - $ ruby array.rb --array "foo, bar, baz" - [["foo", " bar", " baz"], Array] - -==== \Regexp - -File +regexp.rb+ -defines an option whose argument is to be converted to a \Regexp object. - - :include: ruby/regexp.rb - -Executions: +There are a number of built-in converters. +You can also define custom converters. - $ ruby regexp.rb --regexp foo +See {Argument Converters}[./argument_converters_rdoc.html]. === Descriptions diff --git a/doc/ruby/custom_converter.rb b/doc/ruby/custom_converter.rb new file mode 100644 index 0000000..029da08 --- /dev/null +++ b/doc/ruby/custom_converter.rb @@ -0,0 +1,9 @@ +require 'optparse/date' +parser = OptionParser.new +parser.accept(Complex) do |value| + value.to_c +end +parser.on('--complex COMPLEX', Complex) do |value| + p [value, value.class] +end +parser.parse! diff --git a/doc/ruby/long_names.rb b/doc/ruby/long_names.rb index a34b338..a49dbda 100644 --- a/doc/ruby/long_names.rb +++ b/doc/ruby/long_names.rb @@ -1,9 +1,9 @@ require 'optparse' parser = OptionParser.new -parser.on('--xxx') do |value| +parser.on('--xxx', 'Long name') do |value| p ['-xxx', value] end -parser.on('--y1%', '--z2#') do |value| +parser.on('--y1%', '--z2#', "Two long names") do |value| p ['--y1% or --z2#', value] end parser.parse! diff --git a/doc/ruby/long_binary.rb b/doc/ruby/long_with_negation.rb similarity index 57% rename from doc/ruby/long_binary.rb rename to doc/ruby/long_with_negation.rb index 8ecceca..3f2913c 100644 --- a/doc/ruby/long_binary.rb +++ b/doc/ruby/long_with_negation.rb @@ -1,6 +1,6 @@ require 'optparse' parser = OptionParser.new -parser.on('--[no-]binary') do |value| +parser.on('--[no-]binary', 'Long name with negation') do |value| p [value, value.class] end parser.parse! diff --git a/doc/ruby/mixed_names.rb b/doc/ruby/mixed_names.rb index e886049..67f81e7 100644 --- a/doc/ruby/mixed_names.rb +++ b/doc/ruby/mixed_names.rb @@ -1,9 +1,12 @@ require 'optparse' parser = OptionParser.new -parser.on('-x', '--xxx') do |value| +parser.on('-x', '--xxx', 'Short and long, no argument') do |value| p ['--xxx', value] end -parser.on('-y', '--y1%') do |value| - p ['--y1%', value] +parser.on('-yYYY', '--yyy', 'Short and long, required argument') do |value| + p ['--yyy', value] +end +parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') do |value| + p ['--zzz', value] end parser.parse! diff --git a/doc/ruby/optional_argument.rb b/doc/ruby/optional_argument.rb index ebff2f4..456368a 100644 --- a/doc/ruby/optional_argument.rb +++ b/doc/ruby/optional_argument.rb @@ -1,9 +1,9 @@ require 'optparse' parser = OptionParser.new -parser.on('-x [XXX]', '--xxx') do |value| +parser.on('-x [XXX]', '--xxx', 'Optional argument via short name') do |value| p ['--xxx', value] end -parser.on('-y', '--yyy [YYY]') do |value| +parser.on('-y', '--yyy [YYY]', 'Optional argument via long name') do |value| p ['--yyy', value] end parser.parse! diff --git a/doc/ruby/required_argument.rb b/doc/ruby/required_argument.rb index 7a5a868..228a492 100644 --- a/doc/ruby/required_argument.rb +++ b/doc/ruby/required_argument.rb @@ -1,9 +1,9 @@ require 'optparse' parser = OptionParser.new -parser.on('-x XXX', '--xxx') do |value| +parser.on('-x XXX', '--xxx', 'Required argument via short name') do |value| p ['--xxx', value] end -parser.on('-y', '--y YYY') do |value| +parser.on('-y', '--y YYY', 'Required argument via long name') do |value| p ['--yyy', value] end parser.parse! diff --git a/doc/ruby/short_names.rb b/doc/ruby/short_names.rb index 6581dfe..4a75651 100644 --- a/doc/ruby/short_names.rb +++ b/doc/ruby/short_names.rb @@ -1,9 +1,9 @@ require 'optparse' parser = OptionParser.new -parser.on('-x') do |value| +parser.on('-x', 'Short name') do |value| p ['x', value] end -parser.on('-1', '-%') do |value| +parser.on('-1', '-%', 'Two short names') do |value| p ['-1 or -%', value] end parser.parse! diff --git a/doc/tutorial.rdoc b/doc/tutorial.rdoc index 5e95f20..42e0d1e 100644 --- a/doc/tutorial.rdoc +++ b/doc/tutorial.rdoc @@ -32,6 +32,19 @@ The class also has: - Method #summarize: returns a text summary of the options. - Method #help: displays automatically-generated help text. +=== Contents + +- {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] +- {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] +- {Argument Converters}[#label-Argument+Converters] + === Defining Options A common way to define an option in \OptionParser @@ -71,6 +84,10 @@ and an option with two short names (aliases, in effect) -y and -z--y1% and -- Executions: + $ ruby long_names.rb --help + Usage: long_names [options] + --xxx Long name + --y1%, --z2# Two long names $ ruby long_names.rb --xxx ["-xxx", true] $ ruby long_names.rb --y1% @@ -110,6 +131,22 @@ Executions: $ ruby long_names.rb --z2# ["--y1% or --z2#", true] +A long name may be defined with both positive and negative senses. + +File +long_with_negation.rb+ defines an option that has both senses. + + :include: ruby/long_with_negation.rb + +Executions: + + $ ruby long_with_negation.rb --help + Usage: long_with_negation [options] + --[no-]binary Long name with negation + $ ruby long_with_negation.rb --binary + [true, TrueClass] + $ ruby long_with_negation.rb --no-binary + [false, FalseClass] + ==== Mixing Option Names Many developers like to mix short and long option names, @@ -122,14 +159,31 @@ defines options that each have both a short and a long name. Executions: + $ ruby mixed_names.rb --help + Usage: mixed_names [options] + -x, --xxx Short and long, no argument + -y, --yyyYYY Short and long, required argument + -z, --zzz [ZZZ] Short and long, optional argument $ ruby mixed_names.rb -x ["--xxx", true] $ ruby mixed_names.rb --xxx ["--xxx", true] $ ruby mixed_names.rb -y - ["--y1%", true] - $ ruby mixed_names.rb --y1% - ["--y1%", true] + mixed_names.rb:12:in `
': missing argument: -y (OptionParser::MissingArgument) + $ ruby mixed_names.rb -y FOO + ["--yyy", "FOO"] + $ ruby mixed_names.rb --yyy + mixed_names.rb:12:in `
': missing argument: --yyy (OptionParser::MissingArgument) + $ ruby mixed_names.rb --yyy BAR + ["--yyy", "BAR"] + $ ruby mixed_names.rb -z + ["--zzz", nil] + $ ruby mixed_names.rb -z BAZ + ["--zzz", "BAZ"] + $ ruby mixed_names.rb --zzz + ["--zzz", nil] + $ ruby mixed_names.rb --zzz BAT + ["--zzz", "BAT"] === Option Arguments @@ -153,6 +207,10 @@ When an option is found, the given argument is yielded. Executions: + $ ruby required_argument.rb --help + Usage: required_argument [options] + -x, --xxx XXX Required argument via short name + -y, --y YYY Required argument via long name $ ruby required_argument.rb -x AAA ["--xxx", "AAA"] $ ruby required_argument.rb -y BBB @@ -178,9 +236,23 @@ When an option with an argument is found, the given argument yielded. Executions: + $ ruby optional_argument.rb --help + Usage: optional_argument [options] + -x, --xxx [XXX] Optional argument via short name + -y, --yyy [YYY] Optional argument via long name $ ruby optional_argument.rb -x AAA ["--xxx", "AAA"] $ ruby optional_argument.rb -y BBB ["--yyy", "BBB"] Omitting an optional argument does not raise an error. + +=== Argument Converters + +An option can specify that its argument is to be converted +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]. From 39d39676c45083953a082c4f6e2e8a7315b7066d Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Sat, 10 Apr 2021 16:30:19 -0500 Subject: [PATCH 09/27] More on tutorial (#16) - Added example in "Argument Converters"; it doesn't seem right for a tutorial to have no example in one of its topics (and instead just linking elsewhere). - Added section "Command-Line Abbreviations." - Added section "Keyword Argument into," showing how to: - Collect options. - Check for missing options. - Provide option defaults. --- doc/ruby/abbreviation.rb | 9 +++ doc/ruby/collected_options.rb | 8 ++ doc/ruby/default_values.rb | 8 ++ doc/ruby/missing_options.rb | 12 +++ doc/ruby/no_abbreviation.rb | 10 +++ doc/tutorial.rdoc | 136 +++++++++++++++++++++++++++++++++- 6 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 doc/ruby/abbreviation.rb create mode 100644 doc/ruby/collected_options.rb create mode 100644 doc/ruby/default_values.rb create mode 100644 doc/ruby/missing_options.rb create mode 100644 doc/ruby/no_abbreviation.rb diff --git a/doc/ruby/abbreviation.rb b/doc/ruby/abbreviation.rb new file mode 100644 index 0000000..b438c1b --- /dev/null +++ b/doc/ruby/abbreviation.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-n', '--dry-run',) do |value| + p ['--dry-run', value] +end +parser.on('-d', '--draft',) do |value| + p ['--draft', value] +end +parser.parse! diff --git a/doc/ruby/collected_options.rb b/doc/ruby/collected_options.rb new file mode 100644 index 0000000..2115e03 --- /dev/null +++ b/doc/ruby/collected_options.rb @@ -0,0 +1,8 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', 'Short and long, no argument') +parser.on('-yYYY', '--yyy', 'Short and long, required argument') +parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') +options = {} +parser.parse!(into: options) +p options diff --git a/doc/ruby/default_values.rb b/doc/ruby/default_values.rb new file mode 100644 index 0000000..24c26fa --- /dev/null +++ b/doc/ruby/default_values.rb @@ -0,0 +1,8 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', 'Short and long, no argument') +parser.on('-yYYY', '--yyy', 'Short and long, required argument') +parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') +options = {yyy: 'AAA', zzz: 'BBB'} +parser.parse!(into: options) +p options diff --git a/doc/ruby/missing_options.rb b/doc/ruby/missing_options.rb new file mode 100644 index 0000000..9428463 --- /dev/null +++ b/doc/ruby/missing_options.rb @@ -0,0 +1,12 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', 'Short and long, no argument') +parser.on('-yYYY', '--yyy', 'Short and long, required argument') +parser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') +options = {} +parser.parse!(into: options) +required_options = [:xxx, :zzz] +missing_options = required_options - options.keys +unless missing_options.empty? + fail "Missing required options: #{missing_options}" +end diff --git a/doc/ruby/no_abbreviation.rb b/doc/ruby/no_abbreviation.rb new file mode 100644 index 0000000..5464492 --- /dev/null +++ b/doc/ruby/no_abbreviation.rb @@ -0,0 +1,10 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-n', '--dry-run',) do |value| + p ['--dry-run', value] +end +parser.on('-d', '--draft',) do |value| + p ['--draft', value] +end +parser.require_exact = true +parser.parse! diff --git a/doc/tutorial.rdoc b/doc/tutorial.rdoc index 42e0d1e..7721dc6 100644 --- a/doc/tutorial.rdoc +++ b/doc/tutorial.rdoc @@ -39,10 +39,15 @@ The class also has: - {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 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 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] === Defining Options @@ -185,6 +190,47 @@ Executions: $ ruby mixed_names.rb --zzz BAT ["--zzz", "BAT"] +==== Command-Line Abbreviations + +By default, abbreviations for command-line option names are allowed. +An abbreviated option is valid if it is unique among abbreviated option names. + + :include: ruby/abbreviation.rb + +Executions: + + $ ruby abbreviation.rb --help + Usage: abbreviation [options] + -n, --dry-run + -d, --draft + $ ruby abbreviation.rb -n + ["--dry-run", true] + $ ruby abbreviation.rb --dry-run + ["--dry-run", true] + $ ruby abbreviation.rb -d + ["--draft", true] + $ ruby abbreviation.rb --draft + ["--draft", true] + $ ruby abbreviation.rb --d + abbreviation.rb:9:in `
': ambiguous option: --d (OptionParser::AmbiguousOption) + $ ruby abbreviation.rb --dr + abbreviation.rb:9:in `
': ambiguous option: --dr (OptionParser::AmbiguousOption) + $ ruby abbreviation.rb --dry + ["--dry-run", true] + $ ruby abbreviation.rb --dra + ["--draft", true] + +You can disable abbreviation using method +require_exact+. + + :include: ruby/no_abbreviation.rb + +Executions: + + $ ruby no_abbreviation.rb --dry-ru + no_abbreviation.rb:10:in `
': invalid option: --dry-ru (OptionParser::InvalidOption) + $ ruby no_abbreviation.rb --dry-run + ["--dry-run", true] + === Option Arguments An option may take no argument, a required argument, or an optional argument. @@ -247,12 +293,96 @@ Executions: Omitting an optional argument does not raise an error. +=== Keyword Argument +into+ + +In parsing options, you can add keyword option +into+ with a hash-like argument; +each parsed option will be added as a name/value pair. + +This is useful for: + +- Collecting options. +- Checking for missing options. +- Providing default values for options. + +==== Collecting Options + +Use keyword argument +into+ to collect options. + + :include: ruby/collected_options.rb + +Executions: + + $ ruby collected_options.rb --help + Usage: into [options] + -x, --xxx Short and long, no argument + -y, --yyyYYY Short and long, required argument + -z, --zzz [ZZZ] Short and long, optional argument + $ ruby collected_options.rb --xxx + {:xxx=>true} + $ ruby collected_options.rb --xxx --yyy FOO + {:xxx=>true, :yyy=>"FOO"} + $ ruby collected_options.rb --xxx --yyy FOO --zzz Bar + {:xxx=>true, :yyy=>"FOO", :zzz=>"Bar"} + $ ruby collected_options.rb --xxx --yyy FOO --yyy BAR + {:xxx=>true, :yyy=>"BAR"} + +Note in the last execution that the argument value for option --yyy +was overwritten. + +==== Checking for Missing Options + +Use the collected options to check for missing options. + + :include: ruby/missing_options.rb + +Executions: + + $ ruby missing_options.rb --help + Usage: missing_options [options] + -x, --xxx Short and long, no argument + -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 `
': Missing required options: [:xxx, :zzz] (RuntimeError) + +==== Default Values for Options + +Initialize the +into+ argument to define default values for options. + + :include: ruby/default_values.rb + +Executions: + + $ ruby default_values.rb --help + Usage: default_values [options] + -x, --xxx Short and long, no argument + -y, --yyyYYY Short and long, required argument + -z, --zzz [ZZZ] Short and long, optional argument + $ 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. - There are a number of built-in converters. -You can also define custom converters. -See {Argument Converters}[./argument_converters_rdoc.html]. +Example: File +date.rb+ +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 + +Executions: + + $ ruby date.rb --date 2001-02-03 + [#, Date] + $ ruby date.rb --date 20010203 + [#, Date] + $ ruby date.rb --date "3rd Feb 2001" + [#, Date] + +You can also define custom converters. +See {Argument Converters}[./argument_converters_rdoc.html] +for both built-in and custom converters. From 4ff48f24c9b44740dd6c63bc5005db8959c21f80 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Fri, 9 Apr 2021 23:20:03 +0900 Subject: [PATCH 10/27] No document in rakelib --- rakelib/.document | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 rakelib/.document diff --git a/rakelib/.document b/rakelib/.document new file mode 100644 index 0000000..e69de29 From 01c24ca4f606a455b8d135a48e11a0371ef6d7c0 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 11 Apr 2021 08:24:03 +0900 Subject: [PATCH 11/27] Added `rdoc` task --- Rakefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Rakefile b/Rakefile index 74d2021..af769c6 100644 --- a/Rakefile +++ b/Rakefile @@ -8,3 +8,7 @@ Rake::TestTask.new(:test) do |t| end task :default => :test + +task :rdoc do + sh("rdoc", "--op", "rdoc") +end From 8be031b5392cb440f3df23304805c8c814265c59 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 11 Apr 2021 08:49:30 +0900 Subject: [PATCH 12/27] Fix relative paths --- doc/creates_option.rdoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/creates_option.rdoc b/doc/creates_option.rdoc index af1ac16..aaeb72d 100644 --- a/doc/creates_option.rdoc +++ b/doc/creates_option.rdoc @@ -1,7 +1,7 @@ Creates an option from the given parameters +params+. -See {Parameters for New Options}[doc/option_params_rdoc.html]. +See {Parameters for New Options}[./option_params_rdoc.html]. 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}[doc/option_params_rdoc.html#label-Option+Handlers]. +See {Option Handlers}[./option_params_rdoc.html#label-Option+Handlers]. From cccb28e0debbf0f96162291766d3ccafc2c558a3 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 11 Apr 2021 09:03:07 +0900 Subject: [PATCH 13/27] Moved rdoc files to doc/optparse --- doc/{ => optparse}/argument_converters.rdoc | 0 doc/{ => optparse}/creates_option.rdoc | 0 doc/{ => optparse}/option_params.rdoc | 0 doc/{ => optparse}/ruby/abbreviation.rb | 0 doc/{ => optparse}/ruby/argument_keywords.rb | 0 doc/{ => optparse}/ruby/argument_strings.rb | 0 doc/{ => optparse}/ruby/argv.rb | 0 doc/{ => optparse}/ruby/array.rb | 0 doc/{ => optparse}/ruby/block.rb | 0 doc/{ => optparse}/ruby/collected_options.rb | 0 doc/{ => optparse}/ruby/custom_converter.rb | 0 doc/{ => optparse}/ruby/date.rb | 0 doc/{ => optparse}/ruby/datetime.rb | 0 doc/{ => optparse}/ruby/decimal_integer.rb | 0 doc/{ => optparse}/ruby/decimal_numeric.rb | 0 doc/{ => optparse}/ruby/default_values.rb | 0 doc/{ => optparse}/ruby/descriptions.rb | 0 doc/{ => optparse}/ruby/explicit_array_values.rb | 0 doc/{ => optparse}/ruby/explicit_hash_values.rb | 0 doc/{ => optparse}/ruby/false_class.rb | 0 doc/{ => optparse}/ruby/float.rb | 0 doc/{ => optparse}/ruby/integer.rb | 0 doc/{ => optparse}/ruby/long_names.rb | 0 doc/{ => optparse}/ruby/long_optional.rb | 0 doc/{ => optparse}/ruby/long_required.rb | 0 doc/{ => optparse}/ruby/long_simple.rb | 0 doc/{ => optparse}/ruby/long_with_negation.rb | 0 doc/{ => optparse}/ruby/matched_values.rb | 0 doc/{ => optparse}/ruby/method.rb | 0 doc/{ => optparse}/ruby/missing_options.rb | 0 doc/{ => optparse}/ruby/mixed_names.rb | 0 doc/{ => optparse}/ruby/no_abbreviation.rb | 0 doc/{ => optparse}/ruby/numeric.rb | 0 doc/{ => optparse}/ruby/object.rb | 0 doc/{ => optparse}/ruby/octal_integer.rb | 0 doc/{ => optparse}/ruby/optional_argument.rb | 0 doc/{ => optparse}/ruby/proc.rb | 0 doc/{ => optparse}/ruby/regexp.rb | 0 doc/{ => optparse}/ruby/required_argument.rb | 0 doc/{ => optparse}/ruby/shellwords.rb | 0 doc/{ => optparse}/ruby/short_names.rb | 0 doc/{ => optparse}/ruby/short_optional.rb | 0 doc/{ => optparse}/ruby/short_range.rb | 0 doc/{ => optparse}/ruby/short_required.rb | 0 doc/{ => optparse}/ruby/short_simple.rb | 0 doc/{ => optparse}/ruby/string.rb | 0 doc/{ => optparse}/ruby/terminator.rb | 0 doc/{ => optparse}/ruby/time.rb | 0 doc/{ => optparse}/ruby/true_class.rb | 0 doc/{ => optparse}/ruby/uri.rb | 0 doc/{ => optparse}/tutorial.rdoc | 0 lib/optparse.rb | 14 +++++++------- lib/optparse/kwargs.rb | 2 +- 53 files changed, 8 insertions(+), 8 deletions(-) rename doc/{ => optparse}/argument_converters.rdoc (100%) rename doc/{ => optparse}/creates_option.rdoc (100%) rename doc/{ => optparse}/option_params.rdoc (100%) rename doc/{ => optparse}/ruby/abbreviation.rb (100%) rename doc/{ => optparse}/ruby/argument_keywords.rb (100%) rename doc/{ => optparse}/ruby/argument_strings.rb (100%) rename doc/{ => optparse}/ruby/argv.rb (100%) rename doc/{ => optparse}/ruby/array.rb (100%) rename doc/{ => optparse}/ruby/block.rb (100%) rename doc/{ => optparse}/ruby/collected_options.rb (100%) rename doc/{ => optparse}/ruby/custom_converter.rb (100%) rename doc/{ => optparse}/ruby/date.rb (100%) rename doc/{ => optparse}/ruby/datetime.rb (100%) rename doc/{ => optparse}/ruby/decimal_integer.rb (100%) rename doc/{ => optparse}/ruby/decimal_numeric.rb (100%) rename doc/{ => optparse}/ruby/default_values.rb (100%) rename doc/{ => optparse}/ruby/descriptions.rb (100%) rename doc/{ => optparse}/ruby/explicit_array_values.rb (100%) rename doc/{ => optparse}/ruby/explicit_hash_values.rb (100%) rename doc/{ => optparse}/ruby/false_class.rb (100%) rename doc/{ => optparse}/ruby/float.rb (100%) rename doc/{ => optparse}/ruby/integer.rb (100%) rename doc/{ => optparse}/ruby/long_names.rb (100%) rename doc/{ => optparse}/ruby/long_optional.rb (100%) rename doc/{ => optparse}/ruby/long_required.rb (100%) rename doc/{ => optparse}/ruby/long_simple.rb (100%) rename doc/{ => optparse}/ruby/long_with_negation.rb (100%) rename doc/{ => optparse}/ruby/matched_values.rb (100%) rename doc/{ => optparse}/ruby/method.rb (100%) rename doc/{ => optparse}/ruby/missing_options.rb (100%) rename doc/{ => optparse}/ruby/mixed_names.rb (100%) rename doc/{ => optparse}/ruby/no_abbreviation.rb (100%) rename doc/{ => optparse}/ruby/numeric.rb (100%) rename doc/{ => optparse}/ruby/object.rb (100%) rename doc/{ => optparse}/ruby/octal_integer.rb (100%) rename doc/{ => optparse}/ruby/optional_argument.rb (100%) rename doc/{ => optparse}/ruby/proc.rb (100%) rename doc/{ => optparse}/ruby/regexp.rb (100%) rename doc/{ => optparse}/ruby/required_argument.rb (100%) rename doc/{ => optparse}/ruby/shellwords.rb (100%) rename doc/{ => optparse}/ruby/short_names.rb (100%) rename doc/{ => optparse}/ruby/short_optional.rb (100%) rename doc/{ => optparse}/ruby/short_range.rb (100%) rename doc/{ => optparse}/ruby/short_required.rb (100%) rename doc/{ => optparse}/ruby/short_simple.rb (100%) rename doc/{ => optparse}/ruby/string.rb (100%) rename doc/{ => optparse}/ruby/terminator.rb (100%) rename doc/{ => optparse}/ruby/time.rb (100%) rename doc/{ => optparse}/ruby/true_class.rb (100%) rename doc/{ => optparse}/ruby/uri.rb (100%) rename doc/{ => optparse}/tutorial.rdoc (100%) diff --git a/doc/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc similarity index 100% rename from doc/argument_converters.rdoc rename to doc/optparse/argument_converters.rdoc diff --git a/doc/creates_option.rdoc b/doc/optparse/creates_option.rdoc similarity index 100% rename from doc/creates_option.rdoc rename to doc/optparse/creates_option.rdoc diff --git a/doc/option_params.rdoc b/doc/optparse/option_params.rdoc similarity index 100% rename from doc/option_params.rdoc rename to doc/optparse/option_params.rdoc diff --git a/doc/ruby/abbreviation.rb b/doc/optparse/ruby/abbreviation.rb similarity index 100% rename from doc/ruby/abbreviation.rb rename to doc/optparse/ruby/abbreviation.rb diff --git a/doc/ruby/argument_keywords.rb b/doc/optparse/ruby/argument_keywords.rb similarity index 100% rename from doc/ruby/argument_keywords.rb rename to doc/optparse/ruby/argument_keywords.rb diff --git a/doc/ruby/argument_strings.rb b/doc/optparse/ruby/argument_strings.rb similarity index 100% rename from doc/ruby/argument_strings.rb rename to doc/optparse/ruby/argument_strings.rb diff --git a/doc/ruby/argv.rb b/doc/optparse/ruby/argv.rb similarity index 100% rename from doc/ruby/argv.rb rename to doc/optparse/ruby/argv.rb diff --git a/doc/ruby/array.rb b/doc/optparse/ruby/array.rb similarity index 100% rename from doc/ruby/array.rb rename to doc/optparse/ruby/array.rb diff --git a/doc/ruby/block.rb b/doc/optparse/ruby/block.rb similarity index 100% rename from doc/ruby/block.rb rename to doc/optparse/ruby/block.rb diff --git a/doc/ruby/collected_options.rb b/doc/optparse/ruby/collected_options.rb similarity index 100% rename from doc/ruby/collected_options.rb rename to doc/optparse/ruby/collected_options.rb diff --git a/doc/ruby/custom_converter.rb b/doc/optparse/ruby/custom_converter.rb similarity index 100% rename from doc/ruby/custom_converter.rb rename to doc/optparse/ruby/custom_converter.rb diff --git a/doc/ruby/date.rb b/doc/optparse/ruby/date.rb similarity index 100% rename from doc/ruby/date.rb rename to doc/optparse/ruby/date.rb diff --git a/doc/ruby/datetime.rb b/doc/optparse/ruby/datetime.rb similarity index 100% rename from doc/ruby/datetime.rb rename to doc/optparse/ruby/datetime.rb diff --git a/doc/ruby/decimal_integer.rb b/doc/optparse/ruby/decimal_integer.rb similarity index 100% rename from doc/ruby/decimal_integer.rb rename to doc/optparse/ruby/decimal_integer.rb diff --git a/doc/ruby/decimal_numeric.rb b/doc/optparse/ruby/decimal_numeric.rb similarity index 100% rename from doc/ruby/decimal_numeric.rb rename to doc/optparse/ruby/decimal_numeric.rb diff --git a/doc/ruby/default_values.rb b/doc/optparse/ruby/default_values.rb similarity index 100% rename from doc/ruby/default_values.rb rename to doc/optparse/ruby/default_values.rb diff --git a/doc/ruby/descriptions.rb b/doc/optparse/ruby/descriptions.rb similarity index 100% rename from doc/ruby/descriptions.rb rename to doc/optparse/ruby/descriptions.rb diff --git a/doc/ruby/explicit_array_values.rb b/doc/optparse/ruby/explicit_array_values.rb similarity index 100% rename from doc/ruby/explicit_array_values.rb rename to doc/optparse/ruby/explicit_array_values.rb diff --git a/doc/ruby/explicit_hash_values.rb b/doc/optparse/ruby/explicit_hash_values.rb similarity index 100% rename from doc/ruby/explicit_hash_values.rb rename to doc/optparse/ruby/explicit_hash_values.rb diff --git a/doc/ruby/false_class.rb b/doc/optparse/ruby/false_class.rb similarity index 100% rename from doc/ruby/false_class.rb rename to doc/optparse/ruby/false_class.rb diff --git a/doc/ruby/float.rb b/doc/optparse/ruby/float.rb similarity index 100% rename from doc/ruby/float.rb rename to doc/optparse/ruby/float.rb diff --git a/doc/ruby/integer.rb b/doc/optparse/ruby/integer.rb similarity index 100% rename from doc/ruby/integer.rb rename to doc/optparse/ruby/integer.rb diff --git a/doc/ruby/long_names.rb b/doc/optparse/ruby/long_names.rb similarity index 100% rename from doc/ruby/long_names.rb rename to doc/optparse/ruby/long_names.rb diff --git a/doc/ruby/long_optional.rb b/doc/optparse/ruby/long_optional.rb similarity index 100% rename from doc/ruby/long_optional.rb rename to doc/optparse/ruby/long_optional.rb diff --git a/doc/ruby/long_required.rb b/doc/optparse/ruby/long_required.rb similarity index 100% rename from doc/ruby/long_required.rb rename to doc/optparse/ruby/long_required.rb diff --git a/doc/ruby/long_simple.rb b/doc/optparse/ruby/long_simple.rb similarity index 100% rename from doc/ruby/long_simple.rb rename to doc/optparse/ruby/long_simple.rb diff --git a/doc/ruby/long_with_negation.rb b/doc/optparse/ruby/long_with_negation.rb similarity index 100% rename from doc/ruby/long_with_negation.rb rename to doc/optparse/ruby/long_with_negation.rb diff --git a/doc/ruby/matched_values.rb b/doc/optparse/ruby/matched_values.rb similarity index 100% rename from doc/ruby/matched_values.rb rename to doc/optparse/ruby/matched_values.rb diff --git a/doc/ruby/method.rb b/doc/optparse/ruby/method.rb similarity index 100% rename from doc/ruby/method.rb rename to doc/optparse/ruby/method.rb diff --git a/doc/ruby/missing_options.rb b/doc/optparse/ruby/missing_options.rb similarity index 100% rename from doc/ruby/missing_options.rb rename to doc/optparse/ruby/missing_options.rb diff --git a/doc/ruby/mixed_names.rb b/doc/optparse/ruby/mixed_names.rb similarity index 100% rename from doc/ruby/mixed_names.rb rename to doc/optparse/ruby/mixed_names.rb diff --git a/doc/ruby/no_abbreviation.rb b/doc/optparse/ruby/no_abbreviation.rb similarity index 100% rename from doc/ruby/no_abbreviation.rb rename to doc/optparse/ruby/no_abbreviation.rb diff --git a/doc/ruby/numeric.rb b/doc/optparse/ruby/numeric.rb similarity index 100% rename from doc/ruby/numeric.rb rename to doc/optparse/ruby/numeric.rb diff --git a/doc/ruby/object.rb b/doc/optparse/ruby/object.rb similarity index 100% rename from doc/ruby/object.rb rename to doc/optparse/ruby/object.rb diff --git a/doc/ruby/octal_integer.rb b/doc/optparse/ruby/octal_integer.rb similarity index 100% rename from doc/ruby/octal_integer.rb rename to doc/optparse/ruby/octal_integer.rb diff --git a/doc/ruby/optional_argument.rb b/doc/optparse/ruby/optional_argument.rb similarity index 100% rename from doc/ruby/optional_argument.rb rename to doc/optparse/ruby/optional_argument.rb diff --git a/doc/ruby/proc.rb b/doc/optparse/ruby/proc.rb similarity index 100% rename from doc/ruby/proc.rb rename to doc/optparse/ruby/proc.rb diff --git a/doc/ruby/regexp.rb b/doc/optparse/ruby/regexp.rb similarity index 100% rename from doc/ruby/regexp.rb rename to doc/optparse/ruby/regexp.rb diff --git a/doc/ruby/required_argument.rb b/doc/optparse/ruby/required_argument.rb similarity index 100% rename from doc/ruby/required_argument.rb rename to doc/optparse/ruby/required_argument.rb diff --git a/doc/ruby/shellwords.rb b/doc/optparse/ruby/shellwords.rb similarity index 100% rename from doc/ruby/shellwords.rb rename to doc/optparse/ruby/shellwords.rb diff --git a/doc/ruby/short_names.rb b/doc/optparse/ruby/short_names.rb similarity index 100% rename from doc/ruby/short_names.rb rename to doc/optparse/ruby/short_names.rb diff --git a/doc/ruby/short_optional.rb b/doc/optparse/ruby/short_optional.rb similarity index 100% rename from doc/ruby/short_optional.rb rename to doc/optparse/ruby/short_optional.rb diff --git a/doc/ruby/short_range.rb b/doc/optparse/ruby/short_range.rb similarity index 100% rename from doc/ruby/short_range.rb rename to doc/optparse/ruby/short_range.rb diff --git a/doc/ruby/short_required.rb b/doc/optparse/ruby/short_required.rb similarity index 100% rename from doc/ruby/short_required.rb rename to doc/optparse/ruby/short_required.rb diff --git a/doc/ruby/short_simple.rb b/doc/optparse/ruby/short_simple.rb similarity index 100% rename from doc/ruby/short_simple.rb rename to doc/optparse/ruby/short_simple.rb diff --git a/doc/ruby/string.rb b/doc/optparse/ruby/string.rb similarity index 100% rename from doc/ruby/string.rb rename to doc/optparse/ruby/string.rb diff --git a/doc/ruby/terminator.rb b/doc/optparse/ruby/terminator.rb similarity index 100% rename from doc/ruby/terminator.rb rename to doc/optparse/ruby/terminator.rb diff --git a/doc/ruby/time.rb b/doc/optparse/ruby/time.rb similarity index 100% rename from doc/ruby/time.rb rename to doc/optparse/ruby/time.rb diff --git a/doc/ruby/true_class.rb b/doc/optparse/ruby/true_class.rb similarity index 100% rename from doc/ruby/true_class.rb rename to doc/optparse/ruby/true_class.rb diff --git a/doc/ruby/uri.rb b/doc/optparse/ruby/uri.rb similarity index 100% rename from doc/ruby/uri.rb rename to doc/optparse/ruby/uri.rb diff --git a/doc/tutorial.rdoc b/doc/optparse/tutorial.rdoc similarity index 100% rename from doc/tutorial.rdoc rename to doc/optparse/tutorial.rdoc diff --git a/lib/optparse.rb b/lib/optparse.rb index 0f92eba..2eedef5 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -1314,7 +1314,7 @@ def notwice(obj, prv, msg) # :call-seq: # make_switch(params, block = nil) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # def make_switch(opts, block = nil) short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] @@ -1452,7 +1452,7 @@ def make_switch(opts, block = nil) # :call-seq: # define(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # def define(*opts, &block) top.append(*(sw = make_switch(opts, block))) @@ -1462,7 +1462,7 @@ def define(*opts, &block) # :call-seq: # on(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # def on(*opts, &block) define(*opts, &block) @@ -1473,7 +1473,7 @@ def on(*opts, &block) # :call-seq: # define_head(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # def define_head(*opts, &block) top.prepend(*(sw = make_switch(opts, block))) @@ -1483,7 +1483,7 @@ def define_head(*opts, &block) # :call-seq: # on_head(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # # The new option is added at the head of the summary. # @@ -1496,7 +1496,7 @@ def on_head(*opts, &block) # :call-seq: # define_tail(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # def define_tail(*opts, &block) base.append(*(sw = make_switch(opts, block))) @@ -1507,7 +1507,7 @@ def define_tail(*opts, &block) # :call-seq: # on_tail(*params, &block) # - # :include: ../doc/creates_option.rdoc + # :include: ../doc/optparse/creates_option.rdoc # # The new option is added at the tail of the summary. # diff --git a/lib/optparse/kwargs.rb b/lib/optparse/kwargs.rb index d858faf..ccf20c6 100644 --- a/lib/optparse/kwargs.rb +++ b/lib/optparse/kwargs.rb @@ -5,7 +5,7 @@ class OptionParser # :call-seq: # define_by_keywords(options, method, **params) # - # :include: ../../doc/creates_option.rdoc + # :include: ../../doc/optparse/creates_option.rdoc # def define_by_keywords(options, meth, **opts) meth.parameters.each do |type, name| From 7e65ef3cfa3a38aaac3a61e1a82307427f1d27c1 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Mon, 12 Apr 2021 00:38:40 +0900 Subject: [PATCH 14/27] Fixed mismatched tag --- doc/optparse/tutorial.rdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index 7721dc6..3474f1e 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -44,7 +44,7 @@ The class also has: - {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 into}[#label-Keyword+Argument+into] +- {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] From f23d750d14936c0e3663f65ad1b97be82d232dae Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Mon, 12 Apr 2021 02:02:11 +0900 Subject: [PATCH 15/27] nodoc private methods --- lib/optparse.rb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/optparse.rb b/lib/optparse.rb index 2eedef5..2a8efb6 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -547,7 +547,7 @@ def initialize(pattern = nil, conv = nil, # Parses +arg+ and returns rest of +arg+ and matched portion to the # argument pattern. Yields when the pattern doesn't match substring. # - def parse_arg(arg) + def parse_arg(arg) # :nodoc: pattern or return nil, [arg] unless m = pattern.match(arg) yield(InvalidArgument, arg) @@ -572,7 +572,7 @@ def parse_arg(arg) # conversion. Yields at semi-error condition instead of raising an # exception. # - def conv_arg(arg, val = []) + def conv_arg(arg, val = []) # :nodoc: if conv val = conv.call(*val) else @@ -806,7 +806,7 @@ def reject(t) # +lopts+:: Long style option list. # +nlopts+:: Negated long style options list. # - def update(sw, sopts, lopts, nsw = nil, nlopts = nil) + def update(sw, sopts, lopts, nsw = nil, nlopts = nil) # :nodoc: sopts.each {|o| @short[o] = sw} if sopts lopts.each {|o| @long[o] = sw} if lopts nlopts.each {|o| @long[o] = nsw} if nsw and nlopts @@ -1300,7 +1300,7 @@ def to_a; summarize("#{banner}".split(/^/)) end # +prv+:: Previously specified argument. # +msg+:: Exception message. # - def notwice(obj, prv, msg) + def notwice(obj, prv, msg) # :nodoc: unless !prv or prv == obj raise(ArgumentError, "argument #{msg} given twice: #{obj}", ParseError.filter_backtrace(caller(2))) @@ -1732,7 +1732,7 @@ def self.getopts(*args) # Traverses @stack, sending each element method +id+ with +args+ and # +block+. # - def visit(id, *args, &block) + def visit(id, *args, &block) # :nodoc: @stack.reverse_each do |el| el.__send__(id, *args, &block) end @@ -1743,7 +1743,7 @@ def visit(id, *args, &block) # # Searches +key+ in @stack for +id+ hash and returns or yields the result. # - def search(id, key) + def search(id, key) # :nodoc: block_given = block_given? visit(:search, id, key) do |k| return block_given ? yield(k) : k @@ -1760,7 +1760,7 @@ def search(id, key) # +icase+:: Search case insensitive if true. # +pat+:: Optional pattern for completion. # - def complete(typ, opt, icase = false, *pat) + def complete(typ, opt, icase = false, *pat) # :nodoc: if pat.empty? search(typ, opt) {|sw| return [sw, opt]} # exact match or... end From 385dd4322de67a989e5d271ed7ddb96b2375956f Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Sun, 11 Apr 2021 23:43:02 -0500 Subject: [PATCH 16/27] Tutorial: explain custom argument converters (#19) --- doc/optparse/argument_converters.rdoc | 22 +++++++++++++-- doc/optparse/ruby/basic.rb | 16 +++++++++++ doc/optparse/ruby/match_converter.rb | 9 ++++++ doc/optparse/tutorial.rdoc | 40 +++++++++++++++++++++++++-- 4 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 doc/optparse/ruby/basic.rb create mode 100644 doc/optparse/ruby/match_converter.rb diff --git a/doc/optparse/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc index fc5a015..8ad29eb 100644 --- a/doc/optparse/argument_converters.rdoc +++ b/doc/optparse/argument_converters.rdoc @@ -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 /.*/m. +- 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 `
': invalid argument: --capitalize foo bar (OptionParser::InvalidArgument) diff --git a/doc/optparse/ruby/basic.rb b/doc/optparse/ruby/basic.rb new file mode 100644 index 0000000..617d337 --- /dev/null +++ b/doc/optparse/ruby/basic.rb @@ -0,0 +1,16 @@ +# 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. +parser.parse! diff --git a/doc/optparse/ruby/match_converter.rb b/doc/optparse/ruby/match_converter.rb new file mode 100644 index 0000000..13dc5fc --- /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/tutorial.rdoc b/doc/optparse/tutorial.rdoc index 3474f1e..ad8486d 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -1,6 +1,6 @@ == Tutorial -=== Why OptionParser? +=== Why \OptionParser? When a Ruby program executes, it captures its command-line arguments and options into variable ARGV. @@ -34,6 +34,7 @@ The class also has: === 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] @@ -50,6 +51,42 @@ The class also has: - {Default Values for Options}[#label-Default+Values+for+Options] - {Argument Converters}[#label-Argument+Converters] +=== 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, -x, +-y, and -z, 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. + +Executions: + + $ ruby basic.rb -x -z + ["x", true] + ["z", true] + $ ruby basic.rb -z -y -x + ["z", true] + ["y", true] + ["x", true] + === Defining Options A common way to define an option in \OptionParser @@ -361,7 +398,6 @@ 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 d07cb96a9616ae7489e41db7bb85e43a9b664831 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Mon, 12 Apr 2021 20:33:19 -0500 Subject: [PATCH 17/27] Rdoc for help (#21) --- doc/optparse/ruby/help.rb | 21 +++++ doc/optparse/ruby/help_banner.rb | 7 ++ doc/optparse/ruby/help_format.rb | 25 ++++++ doc/optparse/ruby/help_program_name.rb | 7 ++ doc/optparse/tutorial.rdoc | 105 +++++++++++++++++++++++++ 5 files changed, 165 insertions(+) create mode 100644 doc/optparse/ruby/help.rb create mode 100644 doc/optparse/ruby/help_banner.rb create mode 100644 doc/optparse/ruby/help_format.rb create mode 100644 doc/optparse/ruby/help_program_name.rb diff --git a/doc/optparse/ruby/help.rb b/doc/optparse/ruby/help.rb new file mode 100644 index 0000000..72f1b93 --- /dev/null +++ b/doc/optparse/ruby/help.rb @@ -0,0 +1,21 @@ +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 0000000..0943a3e --- /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 0000000..a2f1e85 --- /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 0000000..7b3fbff --- /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/tutorial.rdoc b/doc/optparse/tutorial.rdoc index ad8486d..a701462 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -50,6 +50,43 @@ The class also has: - {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] + +=== 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, -x, +-y, and -z, 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. + +Executions: + + $ ruby basic.rb -x -z + ["x", true] + ["z", true] + $ ruby basic.rb -z -y -x + ["z", true] + ["y", true] + ["x", true] === To Begin With @@ -422,3 +459,71 @@ Executions: You can also define custom converters. See {Argument Converters}[./argument_converters_rdoc.html] 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: +Usage: #{program_name} [options]; +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. From 9c5b3f244b723e0231ef07c56c59dabf56a9dd3f Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Thu, 15 Apr 2021 09:32:02 -0500 Subject: [PATCH 18/27] More on tutorial (#22) Adds argument abbreviation in option_params.rdoc. Adds entire Argument Values section to tutorial.rdoc. --- doc/optparse/option_params.rdoc | 14 +- doc/optparse/ruby/help.rb | 3 - .../ruby/{abbreviation.rb => name_abbrev.rb} | 0 doc/optparse/tutorial.rdoc | 142 +++++++++++++++--- 4 files changed, 135 insertions(+), 24 deletions(-) rename doc/optparse/ruby/{abbreviation.rb => name_abbrev.rb} (100%) diff --git a/doc/optparse/option_params.rdoc b/doc/optparse/option_params.rdoc index 0d06b41..c1f83ed 100644 --- a/doc/optparse/option_params.rdoc +++ b/doc/optparse/option_params.rdoc @@ -319,7 +319,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. @@ -335,8 +335,12 @@ Executions: explicit_array_values.rb:9:in `
': 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 `
': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) $ ruby explicit_array_values.rb -x baz explicit_array_values.rb:9:in `
': invalid argument: -x baz (OptionParser::InvalidArgument) @@ -344,8 +348,8 @@ Executions: ===== 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. @@ -361,6 +365,8 @@ Executions: explicit_hash_values.rb:9:in `
': 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 @@ -371,6 +377,8 @@ Executions: ["-y", 2] $ ruby explicit_hash_values.rb -y bat ["-y", 3] + $ ruby explicit_hash_values.rb -y ba + explicit_hash_values.rb:9:in `
': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) $ ruby explicit_hash_values.rb -y bam ["-y", nil] diff --git a/doc/optparse/ruby/help.rb b/doc/optparse/ruby/help.rb index 72f1b93..95bcde1 100644 --- a/doc/optparse/ruby/help.rb +++ b/doc/optparse/ruby/help.rb @@ -16,6 +16,3 @@ 'nec, pellentesque eu, pretium quis, sem.', ) parser.parse! - - - diff --git a/doc/optparse/ruby/abbreviation.rb b/doc/optparse/ruby/name_abbrev.rb similarity index 100% rename from doc/optparse/ruby/abbreviation.rb rename to doc/optparse/ruby/name_abbrev.rb diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index a701462..dfdc244 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -40,12 +40,18 @@ The class also has: - {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 into}[#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] @@ -264,34 +270,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 `
': ambiguous option: --d (OptionParser::AmbiguousOption) - $ ruby abbreviation.rb --dr - abbreviation.rb:9:in `
': ambiguous option: --dr (OptionParser::AmbiguousOption) - $ ruby abbreviation.rb --dry + $ ruby name_abbrev.rb --d + name_abbrev.rb:9:in `
': ambiguous option: --d (OptionParser::AmbiguousOption) + $ ruby name_abbrev.rb --dr + name_abbrev.rb:9:in `
': 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+. @@ -367,6 +373,106 @@ Executions: Omitting an optional argument does not raise an error. +=== 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 `
': 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 `
': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) + $ ruby explicit_array_values.rb -x baz + explicit_array_values.rb:9:in `
': 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 `
': 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 `
': 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 `
': 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 `
': invalid argument: --xxx bar (OptionParser::InvalidArgument) + === Keyword Argument +into+ In parsing options, you can add keyword option +into+ with a hash-like argument; From 7ef3d89e7859552daa057b6d5f42ffe3e562ae34 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Fri, 16 Apr 2021 12:57:55 +0900 Subject: [PATCH 19/27] Removed a duplicate section --- doc/optparse/tutorial.rdoc | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index dfdc244..8b17726 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -84,42 +84,6 @@ From these defined options, the parser automatically builds help text: When an option is found during parsing, the block defined for the option is called with the argument value. -Executions: - - $ ruby basic.rb -x -z - ["x", true] - ["z", true] - $ ruby basic.rb -z -y -x - ["z", true] - ["y", true] - ["x", true] - -=== 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, -x, --y, and -z, 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. - Executions: $ ruby basic.rb -x -z From 7f3195b9dbc3a984a5d3e928a9d70686484411c0 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Thu, 22 Apr 2021 07:27:06 -0500 Subject: [PATCH 20/27] More on tutorial (#23) - Removed a largish block of repeated text. - Added sections "Top List and Base List" and "Methods for Defining Options" (on, define, etc.). - Linked from class OptionParser doc to the tutorial. --- doc/optparse/ruby/basic.rb | 5 ++- doc/optparse/tutorial.rdoc | 79 +++++++++++++++++++++++++++++++++----- lib/optparse.rb | 10 ++++- 3 files changed, 81 insertions(+), 13 deletions(-) diff --git a/doc/optparse/ruby/basic.rb b/doc/optparse/ruby/basic.rb index 617d337..91d3762 100644 --- a/doc/optparse/ruby/basic.rb +++ b/doc/optparse/ruby/basic.rb @@ -12,5 +12,6 @@ parser.on('-z', 'Whether to Z') do |value| p ['z', value] end -# Parse the command line. -parser.parse! +# Parse the command line and return pared-down ARGV. +p parser.parse! + diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index 8b17726..d2124a9 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -27,10 +27,7 @@ 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 @@ -57,6 +54,8 @@ The class also has: - {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] === To Begin With @@ -83,16 +82,29 @@ From these defined options, the parser automatically builds help text: 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 `
': invalid option: -a (OptionParser::InvalidOption) === Defining Options @@ -151,11 +163,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 `
': invalid option: -z (OptionParser::InvalidOption) - ==== Long Option Names A long option name consists of two hyphens and a one or more characters @@ -597,3 +604,57 @@ Execution: -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 top list, given by \OptionParser#top. +- The base list, 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 \Option#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}[./option_params_rdoc.html]. + This method is unlike others here in that it: + - Accepts an array of parameters; + others accept a sequence of parameter arguments. + - 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+. diff --git a/lib/optparse.rb b/lib/optparse.rb index 2a8efb6..060b134 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -48,6 +48,10 @@ # # == OptionParser # +# === New to \OptionParser? +# +# See the {Tutorial}[./doc/optparse/tutorial_rdoc.html]. +# # === Introduction # # OptionParser is a class for command-line option analysis. It is much more @@ -415,8 +419,10 @@ # # === Further documentation # -# The above examples should be enough to learn how to use this class. If you -# have any questions, file a ticket at http://bugs.ruby-lang.org. +# The above examples, along with the accompanying +# {Tutorial}[./doc/optparse/tutorial_rdoc.html], +# should be enough to learn how to use this class. +# If you have any questions, file a ticket at http://bugs.ruby-lang.org. # class OptionParser OptionParser::Version = "0.1.1" From 40d51ccbad75ab5194ce5a3574b49fda41745849 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Thu, 22 Apr 2021 08:48:23 -0500 Subject: [PATCH 21/27] More on tutorial (#24) - Adds section "Parsing" to tutorial.rdoc. - Removes section "Terminators" from option_params.rdoc. (Terminator '--' is not an option parameter.) --- doc/optparse/option_params.rdoc | 20 ---- doc/optparse/ruby/parse.rb | 13 +++ doc/optparse/ruby/parse_bang.rb | 13 +++ doc/optparse/tutorial.rdoc | 179 +++++++++++++++++++++++++++++++- 4 files changed, 203 insertions(+), 22 deletions(-) create mode 100644 doc/optparse/ruby/parse.rb create mode 100644 doc/optparse/ruby/parse_bang.rb diff --git a/doc/optparse/option_params.rdoc b/doc/optparse/option_params.rdoc index c1f83ed..3e6cb1b 100644 --- a/doc/optparse/option_params.rdoc +++ b/doc/optparse/option_params.rdoc @@ -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 @@ -508,22 +507,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 -- 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 --my_option. - - :include: ruby/terminator.rb - -The first execution fails because --nosuch is not a defined option; -the second succeeds because -- causes that option to be ignored: - - $ ruby terminator.rb --my_option FOO --other_option BAR - ["FOO", String] - terminator.rb:6:in `
': invalid option: --other_option (OptionParser::InvalidOption) - $ ruby terminator.rb --my_option FOO -- --other_option BAR - ["FOO", String] diff --git a/doc/optparse/ruby/parse.rb b/doc/optparse/ruby/parse.rb new file mode 100644 index 0000000..a5d4329 --- /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 0000000..567bc73 --- /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 d2124a9..1d7c52b 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -55,7 +55,14 @@ The class also has method #help, which displays automatically-generated help tex - {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] +- {Defining Options}[#label-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 @@ -619,7 +626,7 @@ The stack includes: When \OptionParser builds its help text, the options in the top list precede those in the base list. -=== Methods for Defining Options +=== 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. @@ -658,3 +665,171 @@ here's the core method for defining an option: 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" (!): + +- 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 argv[0], +and ending, by default, at the end. + +Otherwise processing ends and the method returns when: + +- The terminator argument -- 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 ary.dup. +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 -- 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. From bf03038d953902569c11448717ab584c65e35a89 Mon Sep 17 00:00:00 2001 From: Burdette Lamar Date: Thu, 22 Apr 2021 14:22:11 -0500 Subject: [PATCH 22/27] Fix link in included file --- doc/optparse/creates_option.rdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/optparse/creates_option.rdoc b/doc/optparse/creates_option.rdoc index aaeb72d..131c877 100644 --- a/doc/optparse/creates_option.rdoc +++ b/doc/optparse/creates_option.rdoc @@ -1,5 +1,5 @@ Creates an option from the given parameters +params+. -See {Parameters for New Options}[./option_params_rdoc.html]. +See {Parameters for New Options}[./doc/optparse/option_params_rdoc.html]. The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, From 47417f1b4cb5d819aa54f305a4009f45d7a112c1 Mon Sep 17 00:00:00 2001 From: Olle Jonsson Date: Fri, 23 Apr 2021 13:04:25 +0200 Subject: [PATCH 23/27] Remove an errant { character (#26) --- doc/optparse/argument_converters.rdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/optparse/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc index 8ad29eb..ac659da 100644 --- a/doc/optparse/argument_converters.rdoc +++ b/doc/optparse/argument_converters.rdoc @@ -216,7 +216,7 @@ Executions: 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 +The argument is converted by method Kernel#Integer :include: ruby/decimal_numeric.rb From 6a2fa9737f5dab99c73a99a24472f620fff228ea Mon Sep 17 00:00:00 2001 From: Hiroshi SHIBATA Date: Sat, 11 Sep 2021 13:21:00 +0900 Subject: [PATCH 24/27] Bump up the latest version of CoreAssertions --- Rakefile | 13 +- test/lib/core_assertions.rb | 235 +++++++++++++++++++++++++++++++----- test/lib/envutil.rb | 31 +++-- 3 files changed, 234 insertions(+), 45 deletions(-) diff --git a/Rakefile b/Rakefile index af769c6..5a7afab 100644 --- a/Rakefile +++ b/Rakefile @@ -4,11 +4,14 @@ require "rake/testtask" Rake::TestTask.new(:test) do |t| t.libs << "test/lib" t.ruby_opts << "-rhelper" - t.test_files = FileList['test/**/test_*.rb'] + t.test_files = FileList["test/**/test_*.rb"] end -task :default => :test - -task :rdoc do - sh("rdoc", "--op", "rdoc") +task :sync_tool do + require 'fileutils' + FileUtils.cp "../ruby/tool/lib/core_assertions.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/envutil.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" end + +task :default => :test diff --git a/test/lib/core_assertions.rb b/test/lib/core_assertions.rb index 127ff49..4471525 100644 --- a/test/lib/core_assertions.rb +++ b/test/lib/core_assertions.rb @@ -24,23 +24,8 @@ def message msg = nil, ending = nil, &default end module CoreAssertions - if defined?(MiniTest) - require_relative '../../envutil' - # for ruby core testing - include MiniTest::Assertions - - # Compatibility hack for assert_raise - Test::Unit::AssertionFailedError = MiniTest::Assertion - else - module MiniTest - class Assertion < Exception; end - class Skip < Assertion; end - end - - require 'pp' - require_relative 'envutil' - include Test::Unit::Assertions - end + require_relative 'envutil' + require 'pp' def mu_pp(obj) #:nodoc: obj.pretty_inspect.chomp @@ -115,10 +100,10 @@ def syntax_check(code, fname, line) def assert_no_memory_leak(args, prepare, code, message=nil, limit: 2.0, rss: false, **opt) # TODO: consider choosing some appropriate limit for MJIT and stop skipping this once it does not randomly fail - pend 'assert_no_memory_leak may consider MJIT memory usage as leak' if defined?(RubyVM::MJIT) && RubyVM::MJIT.enabled? + pend 'assert_no_memory_leak may consider MJIT memory usage as leak' if defined?(RubyVM::JIT) && RubyVM::JIT.enabled? - require_relative '../../memory_status' - raise MiniTest::Skip, "unsupported platform" unless defined?(Memory::Status) + require_relative 'memory_status' + raise Test::Unit::PendedError, "unsupported platform" unless defined?(Memory::Status) token = "\e[7;1m#{$$.to_s}:#{Time.now.strftime('%s.%L')}:#{rand(0x10000).to_s(16)}:\e[m" token_dump = token.dump @@ -126,7 +111,7 @@ def assert_no_memory_leak(args, prepare, code, message=nil, limit: 2.0, rss: fal envs = args.shift if Array === args and Hash === args.first args = [ "--disable=gems", - "-r", File.expand_path("../../../memory_status", __FILE__), + "-r", File.expand_path("../memory_status", __FILE__), *args, "-v", "-", ] @@ -183,11 +168,11 @@ def assert_nothing_raised(*args) end begin line = __LINE__; yield - rescue MiniTest::Skip + rescue Test::Unit::PendedError raise rescue Exception => e bt = e.backtrace - as = e.instance_of?(MiniTest::Assertion) + as = e.instance_of?(Test::Unit::AssertionFailedError) if as ans = /\A#{Regexp.quote(__FILE__)}:#{line}:in /o bt.reject! {|ln| ans =~ ln} @@ -199,7 +184,7 @@ def assert_nothing_raised(*args) "Backtrace:\n" + e.backtrace.map{|frame| " #{frame}"}.join("\n") } - raise MiniTest::Assertion, msg.call, bt + raise Test::Unit::AssertionFailedError, msg.call, bt else raise end @@ -260,11 +245,12 @@ def assert_ruby_status(args, test_stdin="", message=nil, **opt) ABORT_SIGNALS = Signal.list.values_at(*%w"ILL ABRT BUS SEGV TERM") def separated_runner(out = nil) + include(*Test::Unit::TestCase.ancestors.select {|c| !c.is_a?(Class) }) out = out ? IO.new(out, 'w') : STDOUT at_exit { - out.puts [Marshal.dump($!)].pack('m'), "assertions=\#{self._assertions}" + out.puts [Marshal.dump($!)].pack('m'), "assertions=#{self._assertions}" } - Test::Unit::Runner.class_variable_set(:@@stop_auto_run, true) + Test::Unit::Runner.class_variable_set(:@@stop_auto_run, true) if defined?(Test::Unit::Runner) end def assert_separately(args, file = nil, line = nil, src, ignore_stderr: nil, **opt) @@ -276,14 +262,14 @@ def assert_separately(args, file = nil, line = nil, src, ignore_stderr: nil, **o capture_stdout = true unless /mswin|mingw/ =~ RUBY_PLATFORM capture_stdout = false - opt[:out] = MiniTest::Unit.output + opt[:out] = Test::Unit::Runner.output if defined?(Test::Unit::Runner) res_p, res_c = IO.pipe - opt[res_c.fileno] = res_c.fileno + opt[:ios] = [res_c] end src = < e - return e if exp.include? MiniTest::Skip + rescue Test::Unit::PendedError => e + return e if exp.include? Test::Unit::PendedError raise e rescue Exception => e expected = exp.any? { |ex| @@ -456,6 +463,121 @@ def assert_raise_with_message(exception, expected, msg = nil, &block) ex end + MINI_DIR = File.join(File.dirname(File.expand_path(__FILE__)), "minitest") #:nodoc: + + # :call-seq: + # assert(test, [failure_message]) + # + #Tests if +test+ is true. + # + #+msg+ may be a String or a Proc. If +msg+ is a String, it will be used + #as the failure message. Otherwise, the result of calling +msg+ will be + #used as the message if the assertion fails. + # + #If no +msg+ is given, a default message will be used. + # + # assert(false, "This was expected to be true") + def assert(test, *msgs) + case msg = msgs.first + when String, Proc + when nil + msgs.shift + else + bt = caller.reject { |s| s.start_with?(MINI_DIR) } + raise ArgumentError, "assertion message must be String or Proc, but #{msg.class} was given.", bt + end unless msgs.empty? + super + end + + # :call-seq: + # assert_respond_to( object, method, failure_message = nil ) + # + #Tests if the given Object responds to +method+. + # + #An optional failure message may be provided as the final argument. + # + # assert_respond_to("hello", :reverse) #Succeeds + # assert_respond_to("hello", :does_not_exist) #Fails + def assert_respond_to(obj, (meth, *priv), msg = nil) + unless priv.empty? + msg = message(msg) { + "Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}#{" privately" if priv[0]}" + } + return assert obj.respond_to?(meth, *priv), msg + end + #get rid of overcounting + if caller_locations(1, 1)[0].path.start_with?(MINI_DIR) + return if obj.respond_to?(meth) + end + super(obj, meth, msg) + end + + # :call-seq: + # assert_not_respond_to( object, method, failure_message = nil ) + # + #Tests if the given Object does not respond to +method+. + # + #An optional failure message may be provided as the final argument. + # + # assert_not_respond_to("hello", :reverse) #Fails + # assert_not_respond_to("hello", :does_not_exist) #Succeeds + def assert_not_respond_to(obj, (meth, *priv), msg = nil) + unless priv.empty? + msg = message(msg) { + "Expected #{mu_pp(obj)} (#{obj.class}) to not respond to ##{meth}#{" privately" if priv[0]}" + } + return assert !obj.respond_to?(meth, *priv), msg + end + #get rid of overcounting + if caller_locations(1, 1)[0].path.start_with?(MINI_DIR) + return unless obj.respond_to?(meth) + end + refute_respond_to(obj, meth, msg) + end + + # pattern_list is an array which contains regexp and :*. + # :* means any sequence. + # + # pattern_list is anchored. + # Use [:*, regexp, :*] for non-anchored match. + def assert_pattern_list(pattern_list, actual, message=nil) + rest = actual + anchored = true + pattern_list.each_with_index {|pattern, i| + if pattern == :* + anchored = false + else + if anchored + match = /\A#{pattern}/.match(rest) + else + match = pattern.match(rest) + end + unless match + msg = message(msg) { + expect_msg = "Expected #{mu_pp pattern}\n" + if /\n[^\n]/ =~ rest + actual_mesg = +"to match\n" + rest.scan(/.*\n+/) { + actual_mesg << ' ' << $&.inspect << "+\n" + } + actual_mesg.sub!(/\+\n\z/, '') + else + actual_mesg = "to match " + mu_pp(rest) + end + actual_mesg << "\nafter #{i} patterns with #{actual.length - rest.length} characters" + expect_msg + actual_mesg + } + assert false, msg + end + rest = match.post_match + anchored = true + end + } + if anchored + assert_equal("", rest) + end + end + def assert_warning(pat, msg = nil) result = nil stderr = EnvUtil.with_default_internal(pat.encoding) { @@ -472,7 +594,22 @@ def assert_warn(*args) assert_warning(*args) {$VERBOSE = false; yield} end + def assert_deprecated_warning(mesg = /deprecated/) + assert_warning(mesg) do + Warning[:deprecated] = true + yield + end + end + + def assert_deprecated_warn(mesg = /deprecated/) + assert_warn(mesg) do + Warning[:deprecated] = true + yield + end + end + class << (AssertFile = Struct.new(:failure_message).new) + include Assertions include CoreAssertions def assert_file_predicate(predicate, *args) if /\Anot_/ =~ predicate @@ -563,10 +700,20 @@ def assert_join_threads(threads, message = nil) if message msg = "#{message}\n#{msg}" end - raise MiniTest::Assertion, msg + raise Test::Unit::AssertionFailedError, msg end end + def assert_all?(obj, m = nil, &blk) + failed = [] + obj.each do |*a, &b| + unless blk.call(*a, &b) + failed << (a.size > 1 ? a : a[0]) + end + end + assert(failed.empty?, message(m) {failed.pretty_inspect}) + end + def assert_all_assertions(msg = nil) all = AllFailures.new yield all @@ -575,6 +722,14 @@ def assert_all_assertions(msg = nil) end alias all_assertions assert_all_assertions + def assert_all_assertions_foreach(msg = nil, *keys, &block) + all = AllFailures.new + all.foreach(*keys, &block) + ensure + assert(all.pass?, message(msg) {all.message.chomp(".")}) + end + alias all_assertions_foreach assert_all_assertions_foreach + def message(msg = nil, *args, &default) # :nodoc: if Proc === msg super(nil, *args) do @@ -592,6 +747,22 @@ def message(msg = nil, *args, &default) # :nodoc: super end end + + def diff(exp, act) + require 'pp' + q = PP.new(+"") + q.guard_inspect_key do + q.group(2, "expected: ") do + q.pp exp + end + q.text q.newline + q.group(2, "actual: ") do + q.pp act + end + q.flush + end + q.output + end end end end diff --git a/test/lib/envutil.rb b/test/lib/envutil.rb index 0dd86df..0391b90 100644 --- a/test/lib/envutil.rb +++ b/test/lib/envutil.rb @@ -47,12 +47,13 @@ def rubybin class << self attr_accessor :timeout_scale attr_reader :original_internal_encoding, :original_external_encoding, - :original_verbose + :original_verbose, :original_warning def capture_global_values @original_internal_encoding = Encoding.default_internal @original_external_encoding = Encoding.default_external @original_verbose = $VERBOSE + @original_warning = defined?(Warning.[]) ? %i[deprecated experimental].to_h {|i| [i, Warning[i]]} : nil end end @@ -86,7 +87,20 @@ def terminate(pid, signal = :TERM, pgroup = nil, reprieve = 1) when nil, false pgroup = pid end + + lldb = true if /darwin/ =~ RUBY_PLATFORM + while signal = signals.shift + + if lldb and [:ABRT, :KILL].include?(signal) + lldb = false + # sudo -n: --non-interactive + # lldb -p: attach + # -o: run command + system(*%W[sudo -n lldb -p #{pid} --batch -o bt\ all -o call\ rb_vmdebug_stack_dump_all_threads() -o quit]) + true + end + begin Process.kill signal, pgroup rescue Errno::EINVAL @@ -100,6 +114,8 @@ def terminate(pid, signal = :TERM, pgroup = nil, reprieve = 1) begin Timeout.timeout(reprieve) {Process.wait(pid)} rescue Timeout::Error + else + break end end end @@ -109,7 +125,7 @@ def terminate(pid, signal = :TERM, pgroup = nil, reprieve = 1) def invoke_ruby(args, stdin_data = "", capture_stdout = false, capture_stderr = false, encoding: nil, timeout: 10, reprieve: 1, timeout_error: Timeout::Error, - stdout_filter: nil, stderr_filter: nil, + stdout_filter: nil, stderr_filter: nil, ios: nil, signal: :TERM, rubybin: EnvUtil.rubybin, precommand: nil, **opt) @@ -125,6 +141,8 @@ def invoke_ruby(args, stdin_data = "", capture_stdout = false, capture_stderr = out_p.set_encoding(encoding) if out_p err_p.set_encoding(encoding) if err_p end + ios.each {|i, o = i|opt[i] = o} if ios + c = "C" child_env = {} LANG_ENVS.each {|lc| child_env[lc] = c} @@ -134,8 +152,9 @@ def invoke_ruby(args, stdin_data = "", capture_stdout = false, capture_stderr = if RUBYLIB and lib = child_env["RUBYLIB"] child_env["RUBYLIB"] = [lib, RUBYLIB].join(File::PATH_SEPARATOR) end + child_env['ASAN_OPTIONS'] = ENV['ASAN_OPTIONS'] if ENV['ASAN_OPTIONS'] args = [args] if args.kind_of?(String) - pid = spawn(child_env, *precommand, rubybin, *args, **opt) + pid = spawn(child_env, *precommand, rubybin, *args, opt) in_c.close out_c&.close out_c = nil @@ -182,11 +201,6 @@ def invoke_ruby(args, stdin_data = "", capture_stdout = false, capture_stderr = end module_function :invoke_ruby - alias rubyexec invoke_ruby - class << self - alias rubyexec invoke_ruby - end - def verbose_warning class << (stderr = "".dup) alias write concat @@ -199,6 +213,7 @@ def flush; end ensure stderr, $stderr = $stderr, stderr $VERBOSE = EnvUtil.original_verbose + EnvUtil.original_warning&.each {|i, v| Warning[i] = v} end module_function :verbose_warning From a3d05c1be8efb552b64f3d1af84b8b8dea8e0afb Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Wed, 29 Sep 2021 11:34:44 +0900 Subject: [PATCH 25/27] Revived `rdoc` task --- Rakefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Rakefile b/Rakefile index 5a7afab..922b54f 100644 --- a/Rakefile +++ b/Rakefile @@ -15,3 +15,7 @@ task :sync_tool do end task :default => :test + +task :rdoc do + sh("rdoc", "--op", "rdoc") +end From 0281b949c6cf86806a260ca6b39267d9b202fbf8 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Wed, 29 Sep 2021 11:45:11 +0900 Subject: [PATCH 26/27] Add the argument from where synchronize tools --- Rakefile | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Rakefile b/Rakefile index 922b54f..2262982 100644 --- a/Rakefile +++ b/Rakefile @@ -7,11 +7,10 @@ Rake::TestTask.new(:test) do |t| t.test_files = FileList["test/**/test_*.rb"] end -task :sync_tool do - require 'fileutils' - FileUtils.cp "../ruby/tool/lib/core_assertions.rb", "./test/lib" - FileUtils.cp "../ruby/tool/lib/envutil.rb", "./test/lib" - FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" +task :sync_tool, [:from] do |t, from: "../ruby"| + cp "#{from}/tool/lib/core_assertions.rb", "./test/lib" + cp "#{from}/tool/lib/envutil.rb", "./test/lib" + cp "#{from}/tool/lib/find_executable.rb", "./test/lib" end task :default => :test From 1226b670e60d5ec8ad4c1a6b73040c9fdcf40fe2 Mon Sep 17 00:00:00 2001 From: Hiroshi SHIBATA Date: Thu, 21 Oct 2021 20:38:56 +0900 Subject: [PATCH 27/27] Bump up optparse version to 0.2.0 --- lib/optparse.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/optparse.rb b/lib/optparse.rb index 060b134..61dd87f 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -425,7 +425,7 @@ # If you have any questions, file a ticket at http://bugs.ruby-lang.org. # class OptionParser - OptionParser::Version = "0.1.1" + OptionParser::Version = "0.2.0" # :stopdoc: NoArgument = [NO_ARGUMENT = :NONE, nil].freeze pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy