cli_args: Fix options_only and flags_only
This commit is contained in:
parent
39dabb4171
commit
d18b122272
@ -5,12 +5,48 @@ require "ostruct"
|
||||
module Homebrew
|
||||
module CLI
|
||||
class Args < OpenStruct
|
||||
attr_accessor :processed_options
|
||||
# undefine tap to allow --tap argument
|
||||
undef tap
|
||||
|
||||
def initialize(argv:)
|
||||
super
|
||||
@argv = argv
|
||||
@processed_options = []
|
||||
end
|
||||
|
||||
def option_to_name(option)
|
||||
option.sub(/\A--?/, "")
|
||||
.tr("-", "_")
|
||||
end
|
||||
|
||||
def cli_args
|
||||
return @cli_args unless @cli_args.nil?
|
||||
|
||||
@cli_args = []
|
||||
processed_options.each do |short, long|
|
||||
option = long || short
|
||||
switch = "#{option_to_name(option)}?".to_sym
|
||||
flag = option_to_name(option).to_sym
|
||||
if @table[switch].instance_of? TrueClass
|
||||
@cli_args << option
|
||||
elsif @table[flag].instance_of? TrueClass
|
||||
@cli_args << option
|
||||
elsif @table[flag].instance_of? String
|
||||
@cli_args << option + "=" + @table[flag]
|
||||
elsif @table[flag].instance_of? Array
|
||||
@cli_args << option + "=" + @table[flag].join(",")
|
||||
end
|
||||
end
|
||||
@cli_args
|
||||
end
|
||||
|
||||
def options_only
|
||||
@options_only ||= cli_args.select { |arg| arg.start_with?("-") }
|
||||
end
|
||||
|
||||
def flags_only
|
||||
@flags_only ||= cli_args.select { |arg| arg.start_with?("--") }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@ -139,6 +139,7 @@ module Homebrew
|
||||
check_constraint_violations
|
||||
@args[:remaining] = remaining_args
|
||||
@args_parsed = true
|
||||
@args.processed_options = @processed_options
|
||||
Homebrew.args = @args
|
||||
cmdline_args.freeze
|
||||
@parser
|
||||
|
||||
@ -210,4 +210,25 @@ describe Homebrew::CLI::Parser do
|
||||
expect { parser.parse(["--switch-b"]) }.to raise_error(RuntimeError, /Arguments were already parsed!/)
|
||||
end
|
||||
end
|
||||
|
||||
describe "test argv extensions" do
|
||||
subject(:parser) {
|
||||
described_class.new do
|
||||
switch "--foo"
|
||||
flag "--bar"
|
||||
switch "-s"
|
||||
switch :verbose
|
||||
end
|
||||
}
|
||||
|
||||
it "#options_only" do
|
||||
parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
|
||||
expect(Homebrew.args.options_only).to eq %w[--foo --bar=value -s --verbose]
|
||||
end
|
||||
|
||||
it "#flags_only" do
|
||||
parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
|
||||
expect(Homebrew.args.flags_only).to eq %w[--foo --bar=value --verbose]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user