From d18b122272f8b67b62f0398f730a9a0faf3655b7 Mon Sep 17 00:00:00 2001 From: Gautham Goli Date: Sun, 22 Sep 2019 20:13:11 +0530 Subject: [PATCH] cli_args: Fix options_only and flags_only --- Library/Homebrew/cli/args.rb | 36 ++++++++++++++++++++++++ Library/Homebrew/cli/parser.rb | 1 + Library/Homebrew/test/cli/parser_spec.rb | 21 ++++++++++++++ 3 files changed, 58 insertions(+) diff --git a/Library/Homebrew/cli/args.rb b/Library/Homebrew/cli/args.rb index bcb3563cd4..a85d1e5a07 100644 --- a/Library/Homebrew/cli/args.rb +++ b/Library/Homebrew/cli/args.rb @@ -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 diff --git a/Library/Homebrew/cli/parser.rb b/Library/Homebrew/cli/parser.rb index 5d69ae0cf4..1e76709170 100644 --- a/Library/Homebrew/cli/parser.rb +++ b/Library/Homebrew/cli/parser.rb @@ -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 diff --git a/Library/Homebrew/test/cli/parser_spec.rb b/Library/Homebrew/test/cli/parser_spec.rb index a0cfa8c5cf..d0ef7ad2fc 100644 --- a/Library/Homebrew/test/cli/parser_spec.rb +++ b/Library/Homebrew/test/cli/parser_spec.rb @@ -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