diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index ee28f6b..065e78a 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -48,7 +48,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/push_gem.yml b/.github/workflows/push_gem.yml index 91c6864..ceaa5d0 100644 --- a/.github/workflows/push_gem.yml +++ b/.github/workflows/push_gem.yml @@ -23,11 +23,11 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1 + uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1 with: egress-policy: audit - - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 + - uses: actions/checkout@ff7abcd0c3c05ccf6adc123a8cd1fd4fb30fb493 # v4.1.4 - name: Set up Ruby uses: ruby/setup-ruby@a6e6f86333f0a2523ece813039b8b4be04560854 # v1.190.0 @@ -36,11 +36,11 @@ jobs: ruby-version: ruby - name: Publish to RubyGems - uses: rubygems/release-gem@612653d273a73bdae1df8453e090060bb4db5f31 # v1 + uses: rubygems/release-gem@a25424ba2ba8b387abc8ef40807c2c85b96cbe32 # v1.1.1 - name: Create GitHub release run: | tag_name="$(git describe --tags --abbrev=0)" gh release create "${tag_name}" --verify-tag --generate-notes env: - GITHUB_TOKEN: ${{ secrets.MATZBOT_GITHUB_WORKFLOW_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2736e12..250d3f1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,7 +28,7 @@ jobs: - { os: windows-latest, ruby: jruby } runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: diff --git a/.rdoc_options b/.rdoc_options index 79a8fce..24fe2d7 100644 --- a/.rdoc_options +++ b/.rdoc_options @@ -2,3 +2,4 @@ page_dir: doc main_page: README.md title: Documentation for OptionParser +op_dir: rdoc diff --git a/doc/optparse/argument_converters.rdoc b/doc/optparse/argument_converters.rdoc index 4b4b30e..5327298 100644 --- a/doc/optparse/argument_converters.rdoc +++ b/doc/optparse/argument_converters.rdoc @@ -377,4 +377,4 @@ 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) + match_converter.rb:9:in '
': invalid argument: --capitalize foo bar (OptionParser::InvalidArgument) diff --git a/doc/optparse/option_params.rdoc b/doc/optparse/option_params.rdoc index 35db8b5..575ee66 100644 --- a/doc/optparse/option_params.rdoc +++ b/doc/optparse/option_params.rdoc @@ -91,7 +91,7 @@ Executions: 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) + short_required.rb:6:in '
': missing argument: -x (OptionParser::MissingArgument) $ ruby short_required.rb -x FOO ["-x", "FOO"] @@ -181,7 +181,7 @@ Executions: Usage: long_required [options] --xxx XXX Long name with required argument $ ruby long_required.rb --xxx - long_required.rb:6:in `
': missing argument: --xxx (OptionParser::MissingArgument) + long_required.rb:6:in '
': missing argument: --xxx (OptionParser::MissingArgument) $ ruby long_required.rb --xxx FOO ["--xxx", "FOO"] @@ -243,11 +243,11 @@ Usage: mixed_names [options] $ ruby mixed_names.rb --xxx ["--xxx", true] $ ruby mixed_names.rb -y - mixed_names.rb:12:in `
': missing argument: -y (OptionParser::MissingArgument) + 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) + mixed_names.rb:12:in '
': missing argument: --yyy (OptionParser::MissingArgument) $ ruby mixed_names.rb --yyy BAR ["--yyy", "BAR"] $ ruby mixed_names.rb -z @@ -279,7 +279,7 @@ Executions: Usage: argument_keywords [options] -x, --xxx Required argument $ ruby argument_styles.rb --xxx - argument_styles.rb:6:in `
': missing argument: --xxx (OptionParser::MissingArgument) + argument_styles.rb:6:in '
': missing argument: --xxx (OptionParser::MissingArgument) $ ruby argument_styles.rb --xxx FOO ["--xxx", "FOO"] @@ -298,7 +298,7 @@ Executions: Usage: argument_strings [options] -x, --xxx=XXX Required argument $ ruby argument_strings.rb --xxx - argument_strings.rb:9:in `
': missing argument: --xxx (OptionParser::MissingArgument) + argument_strings.rb:9:in '
': missing argument: --xxx (OptionParser::MissingArgument) $ ruby argument_strings.rb --xxx FOO ["--xxx", "FOO"] @@ -331,7 +331,7 @@ Executions: -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) + 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 @@ -339,9 +339,9 @@ Executions: $ 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) + 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_array_values.rb:9:in '
': invalid argument: -x baz (OptionParser::InvalidArgument) ===== Explicit Values in Hash @@ -361,7 +361,7 @@ Executions: -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) + 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 @@ -369,7 +369,7 @@ Executions: $ 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) + 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 @@ -377,14 +377,15 @@ Executions: $ 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) + 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. +by specifying a +Regexp+ that the given argument must match, +or a +Range+ or +Array+ that the converted value must be included in. File +matched_values.rb+ defines options with matched argument values. @@ -395,12 +396,22 @@ Executions: $ ruby matched_values.rb --help Usage: matched_values [options] --xxx XXX Matched values + --yyy YYY Check by range + --zzz ZZZ Check by list $ ruby matched_values.rb --xxx foo ["--xxx", "foo"] $ ruby matched_values.rb --xxx FOO ["--xxx", "FOO"] $ ruby matched_values.rb --xxx bar - matched_values.rb:6:in `
': invalid argument: --xxx bar (OptionParser::InvalidArgument) + matched_values.rb:12:in '
': invalid argument: --xxx bar (OptionParser::InvalidArgument) + $ ruby matched_values.rb --yyy 1 + ["--yyy", 1] + $ ruby matched_values.rb --yyy 4 + matched_values.rb:12:in '
': invalid argument: --yyy 4 (OptionParser::InvalidArgument) + $ ruby matched_values.rb --zzz 1 + ["--zzz", 1] + $ ruby matched_values.rb --zzz 2 + matched_values.rb:12:in '
': invalid argument: --zzz 2 (OptionParser::InvalidArgument) === Argument Converters diff --git a/doc/optparse/ruby/matched_values.rb b/doc/optparse/ruby/matched_values.rb index f184ca8..a1aba14 100644 --- a/doc/optparse/ruby/matched_values.rb +++ b/doc/optparse/ruby/matched_values.rb @@ -3,4 +3,10 @@ parser.on('--xxx XXX', /foo/i, 'Matched values') do |value| p ['--xxx', value] end +parser.on('--yyy YYY', Integer, 'Check by range', 1..3) do |value| + p ['--yyy', value] +end +parser.on('--zzz ZZZ', Integer, 'Check by list', [1, 3, 4]) do |value| + p ['--zzz', value] +end parser.parse! diff --git a/doc/optparse/tutorial.rdoc b/doc/optparse/tutorial.rdoc index 6f56bbf..1134f94 100644 --- a/doc/optparse/tutorial.rdoc +++ b/doc/optparse/tutorial.rdoc @@ -111,7 +111,7 @@ Executions: ["x", true] ["input_file.txt", "output_file.txt"] $ ruby basic.rb -a - basic.rb:16:in `
': invalid option: -a (OptionParser::InvalidOption) + basic.rb:16:in '
': invalid option: -a (OptionParser::InvalidOption) === Defining Options @@ -232,11 +232,11 @@ Executions: $ ruby mixed_names.rb --xxx ["--xxx", true] $ ruby mixed_names.rb -y - mixed_names.rb:12:in `
': missing argument: -y (OptionParser::MissingArgument) + 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) + mixed_names.rb:12:in '
': missing argument: --yyy (OptionParser::MissingArgument) $ ruby mixed_names.rb --yyy BAR ["--yyy", "BAR"] $ ruby mixed_names.rb -z @@ -270,9 +270,9 @@ Executions: $ ruby name_abbrev.rb --draft ["--draft", true] $ ruby name_abbrev.rb --d - name_abbrev.rb:9:in `
': ambiguous option: --d (OptionParser::AmbiguousOption) + 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) + name_abbrev.rb:9:in '
': ambiguous option: --dr (OptionParser::AmbiguousOption) $ ruby name_abbrev.rb --dry ["--dry-run", true] $ ruby name_abbrev.rb --dra @@ -285,7 +285,7 @@ You can disable abbreviation using method +require_exact+. Executions: $ ruby no_abbreviation.rb --dry-ru - no_abbreviation.rb:10:in `
': invalid option: --dry-ru (OptionParser::InvalidOption) + no_abbreviation.rb:10:in '
': invalid option: --dry-ru (OptionParser::InvalidOption) $ ruby no_abbreviation.rb --dry-run ["--dry-run", true] @@ -323,7 +323,7 @@ Executions: Omitting a required argument raises an error: $ ruby required_argument.rb -x - required_argument.rb:9:in `
': missing argument: -x (OptionParser::MissingArgument) + required_argument.rb:9:in '
': missing argument: -x (OptionParser::MissingArgument) ==== Option with Optional Argument @@ -369,7 +369,7 @@ Executions: $ ruby argument_abbreviation.rb --xxx A ["--xxx", "ABC"] $ ruby argument_abbreviation.rb --xxx c - argument_abbreviation.rb:9:in `
': invalid argument: --xxx c (OptionParser::InvalidArgument) + argument_abbreviation.rb:9:in '
': invalid argument: --xxx c (OptionParser::InvalidArgument) $ ruby argument_abbreviation.rb --yyy a --yyy d ["--yyy", "XYZ"] ["--yyy", "FOO"] @@ -403,7 +403,7 @@ Executions: -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) + 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 @@ -411,9 +411,9 @@ Executions: $ 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) + 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_array_values.rb:9:in '
': invalid argument: -x baz (OptionParser::InvalidArgument) ===== Explicit Values in Hash @@ -433,7 +433,7 @@ Executions: -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) + 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 @@ -441,7 +441,7 @@ Executions: $ 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) + 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 @@ -449,7 +449,7 @@ Executions: $ 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) + explicit_hash_values.rb:9:in '
': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) $ ruby explicit_hash_values.rb -y bam ["-y", nil] @@ -472,7 +472,7 @@ Executions: $ 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) + matched_values.rb:6:in '
': invalid argument: --xxx bar (OptionParser::InvalidArgument) === Keyword Argument +into+ @@ -524,7 +524,7 @@ Executions: -y, --yyyYYY Short and long, required argument -z, --zzz [ZZZ] Short and long, optional argument $ ruby missing_options.rb --yyy FOO - missing_options.rb:11:in `
': Missing required options: [:xxx, :zzz] (RuntimeError) + missing_options.rb:11:in '
': Missing required options: [:xxx, :zzz] (RuntimeError) ==== Default Values for Options diff --git a/lib/optparse.rb b/lib/optparse.rb index 27e0843..ea6844b 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -7,6 +7,7 @@ # # See OptionParser for documentation. # +require 'set' unless defined?(Set) #-- # == Developer Documentation (not for RDoc output) @@ -142,7 +143,7 @@ # Used: # # $ ruby optparse-test.rb -r -# optparse-test.rb:9:in `
': missing argument: -r (OptionParser::MissingArgument) +# optparse-test.rb:9:in '
': missing argument: -r (OptionParser::MissingArgument) # $ ruby optparse-test.rb -r my-library # You required my-library! # @@ -235,7 +236,7 @@ # $ ruby optparse-test.rb --user 2 # # # $ ruby optparse-test.rb --user 3 -# optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError) +# optparse-test.rb:15:in 'block in find_user': No User Found for id 3 (RuntimeError) # # === Store options to a Hash # @@ -425,7 +426,7 @@ # class OptionParser # The version string - OptionParser::Version = "0.6.0" + OptionParser::Version = "0.7.0.dev.2" # :stopdoc: NoArgument = [NO_ARGUMENT = :NONE, nil].freeze @@ -461,6 +462,10 @@ def self.candidate(key, icase = false, pat = nil, &block) candidates end + def self.completable?(key) + String.try_convert(key) or defined?(key.id2name) + end + def candidate(key, icase = false, pat = nil, &_) Completion.candidate(key, icase, pat, &method(:each)) end @@ -496,7 +501,6 @@ def convert(opt = nil, val = nil, *) end end - # # Map from option/keyword string to object with completion. # @@ -504,7 +508,6 @@ class OptionMap < Hash include Completion end - # # Individual switch class. Not important to the user. # @@ -546,11 +549,11 @@ def self.pattern def initialize(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, - desc = ([] if short or long), block = nil, &_block) + desc = ([] if short or long), block = nil, values = nil, &_block) raise if Array === pattern block ||= _block - @pattern, @conv, @short, @long, @arg, @desc, @block = - pattern, conv, short, long, arg, desc, block + @pattern, @conv, @short, @long, @arg, @desc, @block, @values = + pattern, conv, short, long, arg, desc, block, values end # @@ -583,11 +586,15 @@ def parse_arg(arg) # :nodoc: # exception. # def conv_arg(arg, val = []) # :nodoc: + v, = *val if conv val = conv.call(*val) else val = proc {|v| v}.call(*val) end + if @values + @values.include?(val) or raise InvalidArgument, v + end return arg, block, val end private :conv_arg @@ -668,7 +675,7 @@ def compsys(sdone, ldone) # :nodoc: (sopts+lopts).each do |opt| # "(-x -c -r)-l[left justify]" - if /^--\[no-\](.+)$/ =~ opt + if /\A--\[no-\](.+)$/ =~ opt o = $1 yield("--#{o}", desc.join("")) yield("--no-#{o}", desc.join("")) @@ -1032,7 +1039,6 @@ def match(key) DefaultList.short['-'] = Switch::NoArgument.new {} DefaultList.long[''] = Switch::NoArgument.new {throw :terminate} - COMPSYS_HEADER = <<'XXX' # :nodoc: typeset -A opt_args @@ -1051,16 +1057,16 @@ def compsys(to, name = File.basename($0)) # :nodoc: end def help_exit - if STDOUT.tty? && (pager = ENV.values_at(*%w[RUBY_PAGER PAGER]).find {|e| e && !e.empty?}) + if $stdout.tty? && (pager = ENV.values_at(*%w[RUBY_PAGER PAGER]).find {|e| e && !e.empty?}) less = ENV["LESS"] - args = [{"LESS" => "#{!less || less.empty? ? '-' : less}Fe"}, pager, "w"] + args = [{"LESS" => "#{less} -Fe"}, pager, "w"] print = proc do |f| f.puts help rescue Errno::EPIPE # pager terminated end if Process.respond_to?(:fork) and false - IO.popen("-") {|f| f ? Process.exec(*args, in: f) : print.call(STDOUT)} + IO.popen("-") {|f| f ? Process.exec(*args, in: f) : print.call($stdout)} # unreachable end IO.popen(*args, &print) @@ -1102,7 +1108,7 @@ def help_exit # Officious['*-completion-zsh'] = proc do |parser| Switch::OptionalArgument.new do |arg| - parser.compsys(STDOUT, arg) + parser.compsys($stdout, arg) exit end end @@ -1288,7 +1294,15 @@ def banner # to $0. # def program_name - @program_name || File.basename($0, '.*') + @program_name || strip_ext(File.basename($0)) + end + + private def strip_ext(name) # :nodoc: + exts = /#{ + require "rbconfig" + Regexp.union(*RbConfig::CONFIG["EXECUTABLE_EXTS"]&.split(" ")) + }\z/o + name.sub(exts, "") end # for experimental cascading :-) @@ -1467,6 +1481,7 @@ def make_switch(opts, block = nil) klass = nil q, a = nil has_arg = false + values = nil opts.each do |o| # argument class @@ -1480,7 +1495,7 @@ def make_switch(opts, block = nil) end # directly specified pattern(any object possible to match) - if (!(String === o || Symbol === o)) and o.respond_to?(:match) + if !Completion.completable?(o) and o.respond_to?(:match) pattern = notwice(o, pattern, 'pattern') if pattern.respond_to?(:convert) conv = pattern.method(:convert).to_proc @@ -1494,7 +1509,12 @@ def make_switch(opts, block = nil) case o when Proc, Method block = notwice(o, block, 'block') - when Array, Hash + when Array, Hash, Set + if Array === o + o, v = o.partition {|v,| Completion.completable?(v)} + values = notwice(v, values, 'values') unless v.empty? + next if o.empty? + end case pattern when CompletingHash when nil @@ -1504,11 +1524,13 @@ def make_switch(opts, block = nil) raise ArgumentError, "argument pattern given twice" end o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}} + when Range + values = notwice(o, values, 'values') when Module raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4)) when *ArgumentStyle.keys style = notwice(ArgumentStyle[o], style, 'style') - when /^--no-([^\[\]=\s]*)(.+)?/ + when /\A--no-([^\[\]=\s]*)(.+)?/ q, a = $1, $2 o = notwice(a ? Object : TrueClass, klass, 'type') not_pattern, not_conv = search(:atype, o) unless not_style @@ -1519,7 +1541,7 @@ def make_switch(opts, block = nil) (q = q.downcase).tr!('_', '-') long << "no-#{q}" nolong << q - when /^--\[no-\]([^\[\]=\s]*)(.+)?/ + when /\A--\[no-\]([^\[\]=\s]*)(.+)?/ q, a = $1, $2 o = notwice(a ? Object : TrueClass, klass, 'type') if a @@ -1532,7 +1554,7 @@ def make_switch(opts, block = nil) not_pattern, not_conv = search(:atype, FalseClass) unless not_style not_style = Switch::NoArgument nolong << "no-#{o}" - when /^--([^\[\]=\s]*)(.+)?/ + when /\A--([^\[\]=\s]*)(.+)?/ q, a = $1, $2 if a o = notwice(NilClass, klass, 'type') @@ -1542,7 +1564,7 @@ def make_switch(opts, block = nil) ldesc << "--#{q}" (o = q.downcase).tr!('_', '-') long << o - when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ + when /\A-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ q, a = $1, $2 o = notwice(Object, klass, 'type') if a @@ -1553,7 +1575,7 @@ def make_switch(opts, block = nil) end sdesc << "-#{q}" short << Regexp.new(q) - when /^-(.)(.+)?/ + when /\A-(.)(.+)?/ q, a = $1, $2 if a o = notwice(NilClass, klass, 'type') @@ -1562,7 +1584,7 @@ def make_switch(opts, block = nil) end sdesc << "-#{q}" short << q - when /^=/ + when /\A=/ style = notwice(default_style.guess(arg = o), style, 'style') default_pattern, conv = search(:atype, Object) unless default_pattern else @@ -1571,12 +1593,18 @@ def make_switch(opts, block = nil) end default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern + if Range === values and klass + unless (!values.begin or klass === values.begin) and + (!values.end or klass === values.end) + raise ArgumentError, "range does not match class" + end + end if !(short.empty? and long.empty?) if has_arg and default_style == Switch::NoArgument default_style = Switch::RequiredArgument end s = (style || default_style).new(pattern || default_pattern, - conv, sdesc, ldesc, arg, desc, block) + conv, sdesc, ldesc, arg, desc, block, values) elsif !block if style or pattern raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller) @@ -1585,7 +1613,7 @@ def make_switch(opts, block = nil) else short << pattern s = (style || default_style).new(pattern, - conv, nil, nil, arg, desc, block) + conv, nil, nil, arg, desc, block, values) end return s, short, long, (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style), @@ -1827,7 +1855,7 @@ def permute(*argv, **keywords) # def permute!(argv = default_argv, **keywords) nonopts = [] - order!(argv, **keywords, &nonopts.method(:<<)) + order!(argv, **keywords) {|nonopt| nonopts << nonopt} argv[0, 0] = nonopts argv end @@ -1880,13 +1908,16 @@ def getopts(*args, symbolize_names: false, **keywords) single_options, *long_options = *args result = {} + setter = (symbolize_names ? + ->(name, val) {result[name.to_sym] = val} + : ->(name, val) {result[name] = val}) single_options.scan(/(.)(:)?/) do |opt, val| if val - result[opt] = nil + setter[opt, nil] define("-#{opt} VAL") else - result[opt] = false + setter[opt, false] define("-#{opt}") end end if single_options @@ -1895,16 +1926,16 @@ def getopts(*args, symbolize_names: false, **keywords) arg, desc = arg.split(';', 2) opt, val = arg.split(':', 2) if val - result[opt] = val.empty? ? nil : val + setter[opt, (val unless val.empty?)] define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact) else - result[opt] = false + setter[opt, false] define("--#{opt}", *[desc].compact) end end - parse_in_order(argv, result.method(:[]=), **keywords) - symbolize_names ? result.transform_keys(&:to_sym) : result + parse_in_order(argv, setter, **keywords) + result end # @@ -1954,7 +1985,7 @@ def complete(typ, opt, icase = false, *pat) # :nodoc: visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw} } exc = ambiguous ? AmbiguousOption : InvalidOption - raise exc.new(opt, additional: self.method(:additional_message).curry[typ]) + raise exc.new(opt, additional: proc {|o| additional_message(typ, o)}) end private :complete @@ -2019,19 +2050,27 @@ def candidate(word) def load(filename = nil, **keywords) unless filename basename = File.basename($0, '.*') - return true if load(File.expand_path(basename, '~/.options'), **keywords) rescue nil + return true if load(File.expand_path("~/.options/#{basename}"), **keywords) rescue nil basename << ".options" + if !(xdg = ENV['XDG_CONFIG_HOME']) or xdg.empty? + # https://specifications.freedesktop.org/basedir-spec/latest/#variables + # + # If $XDG_CONFIG_HOME is either not set or empty, a default + # equal to $HOME/.config should be used. + xdg = ['~/.config', true] + end return [ - # XDG - ENV['XDG_CONFIG_HOME'], - '~/.config', + xdg, + *ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR), # Haiku - '~/config/settings', - ].any? {|dir| + ['~/config/settings', true], + ].any? {|dir, expand| next if !dir or dir.empty? - load(File.expand_path(basename, dir), **keywords) rescue nil + filename = File.join(dir, basename) + filename = File.expand_path(filename) if expand + load(filename, **keywords) rescue nil } end begin @@ -2237,9 +2276,10 @@ def recover(argv) argv end + DIR = File.join(__dir__, '') def self.filter_backtrace(array) unless $DEBUG - array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~)) + array.delete_if {|bt| bt.start_with?(DIR)} end array end diff --git a/optparse.gemspec b/optparse.gemspec index 1aa54aa..6ea6b88 100644 --- a/optparse.gemspec +++ b/optparse.gemspec @@ -14,7 +14,10 @@ Gem::Specification.new do |spec| spec.email = ["nobu@ruby-lang.org"] spec.summary = %q{OptionParser is a class for command-line option analysis.} - spec.description = %q{OptionParser is a class for command-line option analysis.} + spec.description = File.open(File.join(__dir__, "README.md")) do |readme| + readme.gets("") # heading + readme.gets("").chomp + end rescue spec.summary spec.homepage = "https://github.com/ruby/optparse" spec.required_ruby_version = Gem::Requirement.new(">= 2.5.0") spec.licenses = ["Ruby", "BSD-2-Clause"] @@ -22,9 +25,9 @@ Gem::Specification.new do |spec| spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage - spec.files = Dir["{doc,lib,misc}/**/{*,.document}"] + - %w[README.md ChangeLog COPYING .document .rdoc_options] - spec.rdoc_options = ["--main=README.md", "--op=rdoc", "--page-dir=doc"] + dir, gemspec = File.split(__FILE__) + excludes = %W[#{gemspec} rakelib test/ Gemfile Rakefile .git* .editor*].map {|n| ":^"+n} + spec.files = IO.popen(%w[git ls-files -z --] + excludes, chdir: dir, &:read).split("\x0") spec.bindir = "exe" spec.executables = [] spec.require_paths = ["lib"] diff --git a/rakelib/changelogs.rake b/rakelib/changelogs.rake index 5e00c98..9be2e8a 100644 --- a/rakelib/changelogs.rake +++ b/rakelib/changelogs.rake @@ -23,7 +23,7 @@ end tags = IO.popen(%w[git tag -l v[0-9]*]).grep(/v(.*)/) {$1} unless tags.empty? tags.sort_by! {|tag| tag.scan(/\d+/).map(&:to_i)} - tags.pop if IO.popen(%W[git log --format=%H v#{tags.last}..HEAD --], &:read).empty? + tags.pop if IO.popen(%W[git rev-list --right-only --count v#{tags.last}..HEAD --], &:read).to_i == 0 tags.inject(nil) do |prev, tag| task("logs/ChangeLog-#{tag}") {|t| changelog[t.name, tag, prev]} tag diff --git a/rakelib/version.rake b/rakelib/version.rake index eb430b0..583530d 100644 --- a/rakelib/version.rake +++ b/rakelib/version.rake @@ -28,9 +28,21 @@ class << (helper = Bundler::GemHelper.instance) def bump(major, minor = 0, teeny = 0, pre: nil) self.version = [major, minor, teeny, pre].compact.join(".") end + + def next_prerelease(*prefix, num) + if num + [*prefix, num.succ] + else + "dev.1" + end + end end -major, minor, teeny = helper.gemspec.version.segments +major, minor, teeny, *prerelease = helper.gemspec.version.segments + +task "bump:dev", [:pre] do |t, pre: helper.next_prerelease(*prerelease)| + helper.bump(major, minor, teeny, pre: pre) +end task "bump:teeny", [:pre] do |t, pre: nil| helper.bump(major, minor, teeny+1, pre: pre) diff --git a/test/optparse/test_load.rb b/test/optparse/test_load.rb index 0ebe855..f664cfb 100644 --- a/test/optparse/test_load.rb +++ b/test/optparse/test_load.rb @@ -31,7 +31,13 @@ def assert_load(result) assert_equal({test: result}, into) end + def assert_load_nothing + assert !new_parser.load + assert_nil @result + end + def setup_options(env, dir, suffix = nil) + env.update({'HOME'=>@tmpdir}) optdir = File.join(@tmpdir, dir) FileUtils.mkdir_p(optdir) file = File.join(optdir, [@basename, suffix].join("")) @@ -41,7 +47,7 @@ def setup_options(env, dir, suffix = nil) begin yield dir, optdir ensure - File.unlink(file) + File.unlink(file) rescue nil Dir.rmdir(optdir) rescue nil end else @@ -50,7 +56,7 @@ def setup_options(env, dir, suffix = nil) end def setup_options_home(&block) - setup_options({'HOME'=>@tmpdir}, ".options", &block) + setup_options({}, ".options", &block) end def setup_options_xdg_config_home(&block) @@ -58,7 +64,7 @@ def setup_options_xdg_config_home(&block) end def setup_options_home_config(&block) - setup_options({'HOME'=>@tmpdir}, ".config", ".options", &block) + setup_options({}, ".config", ".options", &block) end def setup_options_xdg_config_dirs(&block) @@ -66,7 +72,11 @@ def setup_options_xdg_config_dirs(&block) end def setup_options_home_config_settings(&block) - setup_options({'HOME'=>@tmpdir}, "config/settings", ".options", &block) + setup_options({}, "config/settings", ".options", &block) + end + + def setup_options_home_options(envname, &block) + setup_options({envname => '~/options'}, "options", ".options", &block) end def test_load_home_options @@ -91,7 +101,7 @@ def test_load_home_options end def test_load_xdg_config_home - result, = setup_options_xdg_config_home + result, dir = setup_options_xdg_config_home assert_load(result) setup_options_home_config do @@ -105,6 +115,11 @@ def test_load_xdg_config_home setup_options_home_config_settings do assert_load(result) end + + File.unlink("#{dir}/#{@basename}.options") + setup_options_home_config do + assert_load_nothing + end end def test_load_home_config @@ -118,6 +133,11 @@ def test_load_home_config setup_options_home_config_settings do assert_load(result) end + + setup_options_xdg_config_home do |_, dir| + File.unlink("#{dir}/#{@basename}.options") + assert_load_nothing + end end def test_load_xdg_config_dirs @@ -135,7 +155,34 @@ def test_load_home_config_settings end def test_load_nothing - assert !new_parser.load - assert_nil @result + setup_options({}, "") do + assert_load_nothing + end + end + + def test_not_expand_path_basename + basename = @basename + @basename = "~" + $test_optparse_basename = "/" + @basename + alias $test_optparse_prog $0 + alias $0 $test_optparse_basename + setup_options({'HOME'=>@tmpdir+"/~options"}, "", "options") do + assert_load_nothing + end + ensure + alias $0 $test_optparse_prog + @basename = basename + end + + def test_not_expand_path_xdg_config_home + setup_options_home_options('XDG_CONFIG_HOME') do + assert_load_nothing + end + end + + def test_not_expand_path_xdg_config_dirs + setup_options_home_options('XDG_CONFIG_DIRS') do + assert_load_nothing + end end end diff --git a/test/optparse/test_optparse.rb b/test/optparse/test_optparse.rb index 7f35cb4..ff33400 100644 --- a/test/optparse/test_optparse.rb +++ b/test/optparse/test_optparse.rb @@ -184,10 +184,9 @@ def test_help_pager File.open(File.join(dir, "options.rb"), "w") do |f| f.puts "#{<<~"begin;"}\n#{<<~'end;'}" begin; - stdout = STDOUT.dup + stdout = $stdout.dup def stdout.tty?; true; end - Object.__send__(:remove_const, :STDOUT) - STDOUT = stdout + $stdout = stdout ARGV.options do |opt| end; 100.times {|i| f.puts " opt.on('--opt-#{i}') {}"} @@ -217,4 +216,16 @@ def stdout.tty?; true; end end end end + + def test_program_name + program = $0 + $0 = "rdbg3.5" + assert_equal "rdbg3.5", OptionParser.new.program_name + RbConfig::CONFIG["EXECUTABLE_EXTS"]&.split(" ") do |ext| + $0 = "rdbg3.5" + ext + assert_equal "rdbg3.5", OptionParser.new.program_name + end + ensure + $0 = program + end end diff --git a/test/optparse/test_placearg.rb b/test/optparse/test_placearg.rb index a8a11e6..d5be5a6 100644 --- a/test/optparse/test_placearg.rb +++ b/test/optparse/test_placearg.rb @@ -7,6 +7,10 @@ def setup @opt.def_option("-x [VAL]") {|x| @flag = x} @opt.def_option("--option [VAL]") {|x| @flag = x} @opt.def_option("-T [level]", /^[0-4]$/, Integer) {|x| @topt = x} + @opt.def_option("--enum [VAL]", [:Alpha, :Bravo, :Charlie]) {|x| @enum = x} + @opt.def_option("--enumval [VAL]", [[:Alpha, 1], [:Bravo, 2], [:Charlie, 3]]) {|x| @enum = x} + @opt.def_option("--integer [VAL]", Integer, [1, 2, 3]) {|x| @integer = x} + @opt.def_option("--range [VAL]", Integer, 1..3) {|x| @range = x} @topt = nil @opt.def_option("-n") {} @opt.def_option("--regexp [REGEXP]", Regexp) {|x| @reopt = x} @@ -93,4 +97,25 @@ def test_lambda assert_equal(%w"", no_error {@opt.parse!(%w"--lambda")}) assert_equal(nil, @flag) end + + def test_enum + assert_equal([], no_error {@opt.parse!(%w"--enum=A")}) + assert_equal(:Alpha, @enum) + end + + def test_enum_pair + assert_equal([], no_error {@opt.parse!(%w"--enumval=A")}) + assert_equal(1, @enum) + end + + def test_enum_conversion + assert_equal([], no_error {@opt.parse!(%w"--integer=1")}) + assert_equal(1, @integer) + end + + def test_enum_range + assert_equal([], no_error {@opt.parse!(%w"--range=1")}) + assert_equal(1, @range) + assert_raise(OptionParser::InvalidArgument) {@opt.parse!(%w"--range=4")} + end end diff --git a/test/optparse/test_switch.rb b/test/optparse/test_switch.rb new file mode 100644 index 0000000..b06f4e3 --- /dev/null +++ b/test/optparse/test_switch.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: false + +require 'test/unit' +require 'optparse' + + +class TestOptionParserSwitch < Test::Unit::TestCase + + def setup + @parser = OptionParser.new + end + + def assert_invalidarg_error(msg, &block) + exc = assert_raise(OptionParser::InvalidArgument) do + yield + end + assert_equal "invalid argument: #{msg}", exc.message + end + + def test_make_switch__enum_array + p = @parser + p.on("--enum=", ["aa", "bb", "cc"]) + p.permute(["--enum=bb"], into: (opts={})) + assert_equal({:enum=>"bb"}, opts) + assert_invalidarg_error("--enum=dd") do + p.permute(["--enum=dd"], into: (opts={})) + end + end + + def test_make_switch__enum_hash + p = @parser + p.on("--hash=", {"aa"=>"AA", "bb"=>"BB"}) + p.permute(["--hash=bb"], into: (opts={})) + assert_equal({:hash=>"BB"}, opts) + assert_invalidarg_error("--hash=dd") do + p.permute(["--hash=dd"], into: (opts={})) + end + end + + def test_make_switch__enum_set + p = @parser + p.on("--set=", Set.new(["aa", "bb", "cc"])) + p.permute(["--set=bb"], into: (opts={})) + assert_equal({:set=>"bb"}, opts) + assert_invalidarg_error("--set=dd") do + p.permute(["--set=dd"], into: (opts={})) + end + end + +end