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/Rakefile b/Rakefile index 74d2021..2262982 100644 --- a/Rakefile +++ b/Rakefile @@ -4,7 +4,17 @@ 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 :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 + +task :rdoc do + sh("rdoc", "--op", "rdoc") +end diff --git a/doc/optparse/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc new file mode 100644 index 0000000..ac659da --- /dev/null +++ b/doc/optparse/argument_converters.rdoc @@ -0,0 +1,380 @@ +== 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: + +- 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 + +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] + +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/creates_option.rdoc b/doc/optparse/creates_option.rdoc new file mode 100644 index 0000000..131c877 --- /dev/null +++ b/doc/optparse/creates_option.rdoc @@ -0,0 +1,7 @@ +Creates an option from the given parameters +params+. +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, +the block is called with the argument given for the option, if any. +See {Option Handlers}[./option_params_rdoc.html#label-Option+Handlers]. diff --git a/doc/optparse/option_params.rdoc b/doc/optparse/option_params.rdoc new file mode 100644 index 0000000..3e6cb1b --- /dev/null +++ b/doc/optparse/option_params.rdoc @@ -0,0 +1,509 @@ +== 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] + - {Long Names with Negation}[#label-Long+Names+with+Negation] + - {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] +- {Descriptions}[#label-Descriptions] +- {Option Handlers}[#label-Option+Handlers] + - {Handler Blocks}[#label-Handler+Blocks] + - {Handler Procs}[#label-Handler+Procs] + - {Handler Methods}[#label-Handler+Methods] + +=== 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: ruby/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: ruby/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: ruby/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: ruby/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: ruby/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: ruby/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: ruby/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"] + +===== 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. + +File +mixed_names.rb+ defines a mixture of short and long names. + + :include: ruby/mixed_names.rb + +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 + 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: ruby/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: ruby/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, 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) + +=== 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]. + +=== 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: ruby/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] + +=== Option 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: ruby/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: ruby/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: ruby/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"] diff --git a/doc/optparse/ruby/argument_keywords.rb b/doc/optparse/ruby/argument_keywords.rb new file mode 100644 index 0000000..8533257 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/argument_strings.rb b/doc/optparse/ruby/argument_strings.rb new file mode 100644 index 0000000..77861dd --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/argv.rb b/doc/optparse/ruby/argv.rb new file mode 100644 index 0000000..12495cf --- /dev/null +++ b/doc/optparse/ruby/argv.rb @@ -0,0 +1,2 @@ +p ARGV + diff --git a/doc/optparse/ruby/array.rb b/doc/optparse/ruby/array.rb new file mode 100644 index 0000000..7c6c14f --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/basic.rb b/doc/optparse/ruby/basic.rb new file mode 100644 index 0000000..91d3762 --- /dev/null +++ b/doc/optparse/ruby/basic.rb @@ -0,0 +1,17 @@ +# Require the OptionParser code. +require 'optparse' +# Create an OptionParser object. +parser = OptionParser.new +# Define one or more options. +parser.on('-x', 'Whether to X') do |value| + p ['x', value] +end +parser.on('-y', 'Whether to Y') do |value| + p ['y', value] +end +parser.on('-z', 'Whether to Z') do |value| + p ['z', value] +end +# Parse the command line and return pared-down ARGV. +p parser.parse! + diff --git a/doc/optparse/ruby/block.rb b/doc/optparse/ruby/block.rb new file mode 100644 index 0000000..c4dfdeb --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/collected_options.rb b/doc/optparse/ruby/collected_options.rb new file mode 100644 index 0000000..2115e03 --- /dev/null +++ b/doc/optparse/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/optparse/ruby/custom_converter.rb b/doc/optparse/ruby/custom_converter.rb new file mode 100644 index 0000000..029da08 --- /dev/null +++ b/doc/optparse/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/optparse/ruby/date.rb b/doc/optparse/ruby/date.rb new file mode 100644 index 0000000..5994ad6 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/datetime.rb b/doc/optparse/ruby/datetime.rb new file mode 100644 index 0000000..b9b591d --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/decimal_integer.rb b/doc/optparse/ruby/decimal_integer.rb new file mode 100644 index 0000000..360bd28 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/decimal_numeric.rb b/doc/optparse/ruby/decimal_numeric.rb new file mode 100644 index 0000000..954da13 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/default_values.rb b/doc/optparse/ruby/default_values.rb new file mode 100644 index 0000000..24c26fa --- /dev/null +++ b/doc/optparse/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/optparse/ruby/descriptions.rb b/doc/optparse/ruby/descriptions.rb new file mode 100644 index 0000000..9aec80a --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/explicit_array_values.rb b/doc/optparse/ruby/explicit_array_values.rb new file mode 100644 index 0000000..64f930a --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/explicit_hash_values.rb b/doc/optparse/ruby/explicit_hash_values.rb new file mode 100644 index 0000000..9c9e6a4 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/false_class.rb b/doc/optparse/ruby/false_class.rb new file mode 100644 index 0000000..04fe335 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/float.rb b/doc/optparse/ruby/float.rb new file mode 100644 index 0000000..390df7f --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/help.rb b/doc/optparse/ruby/help.rb new file mode 100644 index 0000000..95bcde1 --- /dev/null +++ b/doc/optparse/ruby/help.rb @@ -0,0 +1,18 @@ +require 'optparse' +parser = OptionParser.new +parser.on( + '-x', '--xxx', + 'Adipiscing elit. Aenean commodo ligula eget.', + 'Aenean massa. Cum sociis natoque penatibus', + ) +parser.on( + '-y', '--yyy YYY', + 'Lorem ipsum dolor sit amet, consectetuer.' +) +parser.on( + '-z', '--zzz [ZZZ]', + 'Et magnis dis parturient montes, nascetur', + 'ridiculus mus. Donec quam felis, ultricies', + 'nec, pellentesque eu, pretium quis, sem.', + ) +parser.parse! diff --git a/doc/optparse/ruby/help_banner.rb b/doc/optparse/ruby/help_banner.rb new file mode 100644 index 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/ruby/integer.rb b/doc/optparse/ruby/integer.rb new file mode 100644 index 0000000..f10656f --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/long_names.rb b/doc/optparse/ruby/long_names.rb new file mode 100644 index 0000000..a49dbda --- /dev/null +++ b/doc/optparse/ruby/long_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--xxx', 'Long name') do |value| + p ['-xxx', value] +end +parser.on('--y1%', '--z2#', "Two long names") do |value| + p ['--y1% or --z2#', value] +end +parser.parse! diff --git a/doc/optparse/ruby/long_optional.rb b/doc/optparse/ruby/long_optional.rb new file mode 100644 index 0000000..38dd821 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/long_required.rb b/doc/optparse/ruby/long_required.rb new file mode 100644 index 0000000..b76c997 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/long_simple.rb b/doc/optparse/ruby/long_simple.rb new file mode 100644 index 0000000..4e489c4 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/long_with_negation.rb b/doc/optparse/ruby/long_with_negation.rb new file mode 100644 index 0000000..3f2913c --- /dev/null +++ b/doc/optparse/ruby/long_with_negation.rb @@ -0,0 +1,6 @@ +require 'optparse' +parser = OptionParser.new +parser.on('--[no-]binary', 'Long name with negation') do |value| + p [value, value.class] +end +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/ruby/matched_values.rb b/doc/optparse/ruby/matched_values.rb new file mode 100644 index 0000000..f184ca8 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/method.rb b/doc/optparse/ruby/method.rb new file mode 100644 index 0000000..3f02ff5 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/missing_options.rb b/doc/optparse/ruby/missing_options.rb new file mode 100644 index 0000000..9428463 --- /dev/null +++ b/doc/optparse/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/optparse/ruby/mixed_names.rb b/doc/optparse/ruby/mixed_names.rb new file mode 100644 index 0000000..67f81e7 --- /dev/null +++ b/doc/optparse/ruby/mixed_names.rb @@ -0,0 +1,12 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', '--xxx', 'Short and long, no argument') 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/optparse/ruby/name_abbrev.rb b/doc/optparse/ruby/name_abbrev.rb new file mode 100644 index 0000000..b438c1b --- /dev/null +++ b/doc/optparse/ruby/name_abbrev.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/optparse/ruby/no_abbreviation.rb b/doc/optparse/ruby/no_abbreviation.rb new file mode 100644 index 0000000..5464492 --- /dev/null +++ b/doc/optparse/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/optparse/ruby/numeric.rb b/doc/optparse/ruby/numeric.rb new file mode 100644 index 0000000..d7021f1 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/object.rb b/doc/optparse/ruby/object.rb new file mode 100644 index 0000000..0f5ae8b --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/octal_integer.rb b/doc/optparse/ruby/octal_integer.rb new file mode 100644 index 0000000..b9644a0 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/optional_argument.rb b/doc/optparse/ruby/optional_argument.rb new file mode 100644 index 0000000..456368a --- /dev/null +++ b/doc/optparse/ruby/optional_argument.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x [XXX]', '--xxx', 'Optional argument via short name') do |value| + p ['--xxx', value] +end +parser.on('-y', '--yyy [YYY]', 'Optional argument via long name') do |value| + p ['--yyy', value] +end +parser.parse! 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/ruby/proc.rb b/doc/optparse/ruby/proc.rb new file mode 100644 index 0000000..9c669fd --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/regexp.rb b/doc/optparse/ruby/regexp.rb new file mode 100644 index 0000000..6aba45c --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/required_argument.rb b/doc/optparse/ruby/required_argument.rb new file mode 100644 index 0000000..228a492 --- /dev/null +++ b/doc/optparse/ruby/required_argument.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x XXX', '--xxx', 'Required argument via short name') do |value| + p ['--xxx', value] +end +parser.on('-y', '--y YYY', 'Required argument via long name') do |value| + p ['--yyy', value] +end +parser.parse! diff --git a/doc/optparse/ruby/shellwords.rb b/doc/optparse/ruby/shellwords.rb new file mode 100644 index 0000000..d181d4a --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/short_names.rb b/doc/optparse/ruby/short_names.rb new file mode 100644 index 0000000..4a75651 --- /dev/null +++ b/doc/optparse/ruby/short_names.rb @@ -0,0 +1,9 @@ +require 'optparse' +parser = OptionParser.new +parser.on('-x', 'Short name') do |value| + p ['x', value] +end +parser.on('-1', '-%', 'Two short names') do |value| + p ['-1 or -%', value] +end +parser.parse! diff --git a/doc/optparse/ruby/short_optional.rb b/doc/optparse/ruby/short_optional.rb new file mode 100644 index 0000000..6eebf01 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/short_range.rb b/doc/optparse/ruby/short_range.rb new file mode 100644 index 0000000..f5b870a --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/short_required.rb b/doc/optparse/ruby/short_required.rb new file mode 100644 index 0000000..867c02c --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/short_simple.rb b/doc/optparse/ruby/short_simple.rb new file mode 100644 index 0000000..d3d489e --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/string.rb b/doc/optparse/ruby/string.rb new file mode 100644 index 0000000..fee84a1 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/terminator.rb b/doc/optparse/ruby/terminator.rb new file mode 100644 index 0000000..c718ac1 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/time.rb b/doc/optparse/ruby/time.rb new file mode 100644 index 0000000..aa8b0cf --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/true_class.rb b/doc/optparse/ruby/true_class.rb new file mode 100644 index 0000000..40db9d0 --- /dev/null +++ b/doc/optparse/ruby/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/optparse/ruby/uri.rb b/doc/optparse/ruby/uri.rb new file mode 100644 index 0000000..b492835 --- /dev/null +++ b/doc/optparse/ruby/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! diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc new file mode 100644 index 0000000..1d7c52b --- /dev/null +++ b/doc/optparse/tutorial.rdoc @@ -0,0 +1,835 @@ +== 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 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 method #help, which displays automatically-generated help text. + +=== Contents + +- {To Begin With}[#label-To+Begin+With] +- {Defining Options}[#label-Defining+Options] +- {Option Names}[#label-Option+Names] + - {Short Option Names}[#label-Short+Option+Names] + - {Long Option Names}[#label-Long+Option+Names] + - {Mixing Option Names}[#label-Mixing+Option+Names] + - {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] + - {Argument Abbreviations}[#label-Argument+Abbreviations] +- {Argument Values}[#label-Argument+Values] + - {Explicit Argument Values}[#label-Explicit+Argument+Values] + - {Explicit Values in Array}[#label-Explicit+Values+in+Array] + - {Explicit Values in Hash}[#label-Explicit+Values+in+Hash] + - {Argument Value Patterns}[#label-Argument+Value+Patterns] +- {Keyword Argument into}[#label-Keyword+Argument+into] + - {Collecting Options}[#label-Collecting+Options] + - {Checking for Missing Options}[#label-Checking+for+Missing+Options] + - {Default Values for Options}[#label-Default+Values+for+Options] +- {Argument Converters}[#label-Argument+Converters] +- {Help}[#label-Help] +- {Top List and Base List}[#label-Top+List+and+Base+List] +- {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 + +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. +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 + +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 short_names.rb --help + Usage: short_names [options] + -x Short name + -1, -% Two short names + $ 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] + +==== 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 --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% + ["--y1% or --z2#", true] + $ 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, +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 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 + 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 Name Abbreviations + +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/name_abbrev.rb + +Executions: + + $ ruby name_abbrev.rb --help + Usage: name_abbrev [options] + -n, --dry-run + -d, --draft + $ ruby name_abbrev.rb -n + ["--dry-run", true] + $ ruby name_abbrev.rb --dry-run + ["--dry-run", true] + $ ruby name_abbrev.rb -d + ["--draft", true] + $ ruby name_abbrev.rb --draft + ["--draft", true] + $ 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 name_abbrev.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. + +==== 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: ruby/required_argument.rb + +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 + ["--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: ruby/optional_argument.rb + +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 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; +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. + +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. + +=== 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. + +=== 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. + +=== 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+. + +=== 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. diff --git a/lib/optparse.rb b/lib/optparse.rb index 598ebd1..61dd87f 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 @@ -240,14 +244,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: # @@ -415,11 +419,13 @@ # # === 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" + OptionParser::Version = "0.2.0" # :stopdoc: NoArgument = [NO_ARGUMENT = :NONE, nil].freeze @@ -547,7 +553,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 +578,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 +812,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 +1306,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))) @@ -1314,64 +1320,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/optparse/creates_option.rdoc # def make_switch(opts, block = nil) short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] @@ -1509,6 +1458,8 @@ def make_switch(opts, block = nil) # :call-seq: # define(*params, &block) # + # :include: ../doc/optparse/creates_option.rdoc + # def define(*opts, &block) top.append(*(sw = make_switch(opts, block))) sw[0] @@ -1517,8 +1468,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/optparse/creates_option.rdoc # def on(*opts, &block) define(*opts, &block) @@ -1529,6 +1479,8 @@ def on(*opts, &block) # :call-seq: # define_head(*params, &block) # + # :include: ../doc/optparse/creates_option.rdoc + # def define_head(*opts, &block) top.prepend(*(sw = make_switch(opts, block))) sw[0] @@ -1537,7 +1489,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/optparse/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 +1502,8 @@ def on_head(*opts, &block) # :call-seq: # define_tail(*params, &block) # + # :include: ../doc/optparse/creates_option.rdoc + # def define_tail(*opts, &block) base.append(*(sw = make_switch(opts, block))) sw[0] @@ -1557,7 +1513,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/optparse/creates_option.rdoc + # + # The new option is added at the tail of the summary. # def on_tail(*opts, &block) define_tail(*opts, &block) @@ -1780,7 +1738,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 @@ -1791,7 +1749,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 @@ -1808,7 +1766,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 diff --git a/lib/optparse/kwargs.rb b/lib/optparse/kwargs.rb index 5a2def4..ccf20c6 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/optparse/creates_option.rdoc + # def define_by_keywords(options, meth, **opts) meth.parameters.each do |type, name| case type diff --git a/optparse.gemspec b/optparse.gemspec index 831c787..ae65966 100644 --- a/optparse.gemspec +++ b/optparse.gemspec @@ -22,12 +22,8 @@ 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.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.executables = [] spec.require_paths = ["lib"] end diff --git a/rakelib/.document b/rakelib/.document new file mode 100644 index 0000000..e69de29 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 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