Refactor CLI::Parser.

This commit is contained in:
Markus Reiter 2020-07-30 18:40:10 +02:00
parent acd5e58363
commit d4c2ffd705
80 changed files with 307 additions and 333 deletions

View File

@ -55,6 +55,8 @@ begin
end
end
Homebrew.args = Homebrew::CLI::Parser.new.parse(ignore_invalid_options: true)
path = PATH.new(ENV["PATH"])
homebrew_path = PATH.new(ENV["HOMEBREW_PATH"])
@ -117,7 +119,7 @@ begin
odie "Unknown command: #{cmd}" if !possible_tap || possible_tap.installed?
# Unset HOMEBREW_HELP to avoid confusing the tap
ENV.delete("HOMEBREW_HELP") if help_flag
with_env HOMEBREW_HELP: nil do
tap_commands = []
cgroup = Utils.popen_read("cat", "/proc/1/cgroup")
if %w[azpl_job actions_job docker garden kubepods].none? { |container| cgroup.include?(container) }
@ -126,7 +128,8 @@ begin
end
tap_commands += %W[#{HOMEBREW_BREW_FILE} tap #{possible_tap.name}]
safe_system(*tap_commands)
ENV["HOMEBREW_HELP"] = "1" if help_flag
end
exec HOMEBREW_BREW_FILE, cmd, *ARGV
end
rescue UsageError => e

View File

@ -336,6 +336,8 @@ fi
for arg in "$@"
do
[[ $arg = "--" ]] && break
if [[ $arg = "--help" || $arg = "-h" || $arg = "--usage" || $arg = "-?" ]]
then
export HOMEBREW_HELP="1"

View File

@ -10,7 +10,7 @@ module Homebrew
# undefine tap to allow --tap argument
undef tap
def initialize(argv = ARGV.freeze, set_default_args: false)
def initialize(argv = ARGV.dup.freeze, set_default_args: false)
super()
@processed_options = []
@ -58,10 +58,6 @@ module Homebrew
@flags_only = args_flags_only(cli_args)
end
def passthrough
options_only - CLI::Parser.global_options.values.map(&:first).flatten
end
def named
named_args || []
end

View File

@ -13,10 +13,6 @@ module Homebrew
class Parser
attr_reader :processed_options, :hide_from_man_page
def self.parse(argv = ARGV.freeze, allow_no_named_args: false, &block)
new(argv, &block).parse(allow_no_named_args: allow_no_named_args)
end
def self.from_cmd_path(cmd_path)
cmd_args_method_name = Commands.args_method_name(cmd_path)
@ -30,15 +26,16 @@ module Homebrew
end
def self.global_options
{
quiet: [["-q", "--quiet"], :quiet, "Suppress any warnings."],
verbose: [["-v", "--verbose"], :verbose, "Make some output more verbose."],
debug: [["-d", "--debug"], :debug, "Display any debugging information."],
}
[
["-q", "--quiet", "Suppress any warnings."],
["-v", "--verbose", "Make some output more verbose."],
["-d", "--debug", "Display any debugging information."],
]
end
def initialize(argv = ARGV.freeze, &block)
def initialize(argv = ARGV.dup.freeze, &block)
@parser = OptionParser.new
@argv = argv
@args = Homebrew::CLI::Args.new(@argv)
@ -50,25 +47,31 @@ module Homebrew
@min_named_args = nil
@min_named_type = nil
@hide_from_man_page = false
instance_eval(&block)
self.class.global_options.each do |short, long, desc|
switch short, long, description: desc
end
instance_eval(&block) if block_given?
post_initialize
end
def post_initialize
# Disable default handling of `--version` switch.
@parser.base.long.delete("version")
# Disable default handling of `--help` switch.
@parser.on_tail("-h", "--help", "Show this message.") do
puts generate_help_text
exit 0
raise OptionParser::InvalidOption
end
end
def switch(*names, description: nil, env: nil, required_for: nil, depends_on: nil)
global_switch = names.first.is_a?(Symbol)
names, env, default_description = common_switch(*names) if global_switch
if description.nil? && global_switch
description = default_description
elsif description.nil?
description = option_to_description(*names)
end
return if global_switch
description = option_to_description(*names) if description.nil?
process_option(*names, description)
@parser.on(*names, *wrap_option_desc(description)) do
enable_switch(*names, from: :args)
@ -153,31 +156,54 @@ module Homebrew
@parser.to_s
end
def parse(argv = @argv, allow_no_named_args: false)
def parse(argv = @argv, ignore_invalid_options: false)
raise "Arguments were already parsed!" if @args_parsed
i = 0
remaining = []
argv, non_options = split_double_dash(argv)
while i < argv.count
begin
named_args = @parser.parse(argv)
rescue OptionParser::InvalidOption => e
begin
arg = argv[i]
remaining << arg unless @parser.parse([arg]).empty?
rescue OptionParser::MissingArgument
raise if i + 1 >= argv.count
args = argv[i..(i + 1)]
@parser.parse(args)
i += 1
end
rescue OptionParser::InvalidOption
if ignore_invalid_options
remaining << arg
else
$stderr.puts generate_help_text
raise e
raise
end
end
i += 1
end
named_args = if ignore_invalid_options
[]
else
remaining + non_options
end
check_constraint_violations
check_named_args(named_args, allow_no_named_args: allow_no_named_args)
check_named_args(named_args)
@args.freeze_named_args!(named_args)
@args.freeze_processed_options!(@processed_options)
Homebrew.args = @args
@args_parsed = true
@args
end
def global_option?(name, desc)
Homebrew::CLI::Parser.global_options.key?(name.to_sym) &&
Homebrew::CLI::Parser.global_options[name.to_sym].last == desc
end
def generate_help_text
@parser.to_s
.sub(/^/, "#{Tty.bold}Usage: brew#{Tty.reset} ")
@ -188,7 +214,7 @@ module Homebrew
end
def formula_options
formulae.each do |f|
formulae(@argv).each do |f|
next if f.options.empty?
f.options.each do |o|
@ -256,11 +282,6 @@ module Homebrew
end
end
# These are common/global switches accessible throughout Homebrew
def common_switch(name)
Homebrew::CLI::Parser.global_options.fetch(name, name)
end
def option_passed?(name)
@args[name.to_sym] || @args["#{name}?".to_sym]
end
@ -328,8 +349,10 @@ module Homebrew
check_constraints
end
def check_named_args(args, allow_no_named_args: false)
def check_named_args(args)
min_exception = case @min_named_type
when :cask
Cask::CaskUnspecifiedError.new
when :formula
FormulaUnspecifiedError.new
when :keg
@ -337,8 +360,8 @@ module Homebrew
else
MinNamedArgumentsError.new(@min_named_args)
end
raise min_exception if !allow_no_named_args && !@min_named_args.nil? && args.size < @min_named_args
raise MaxNamedArgumentsError, @max_named_args if !@max_named_args.nil? && args.size > @max_named_args
raise min_exception if @min_named_args && args.size < @min_named_args
raise MaxNamedArgumentsError, @max_named_args if @max_named_args && args.size > @max_named_args
end
def process_option(*args)
@ -346,11 +369,21 @@ module Homebrew
@processed_options << [option.short.first, option.long.first, option.arg, option.desc.first]
end
def formulae
named_args = @argv.reject { |arg| arg.start_with?("-") }
spec = if @argv.include?("--HEAD")
def split_double_dash(argv)
if sep = argv.index("--")
[argv.take(sep), argv.drop(sep + 1)]
else
[argv, []]
end
end
def formulae(argv)
argv, named_argv = split_double_dash(argv)
named_args = argv.reject { |arg| arg.start_with?("-") } + named_argv
spec = if argv.include?("--HEAD")
:head
elsif @argv.include?("--devel")
elsif argv.include?("--devel")
:devel
else
:stable

View File

@ -20,7 +20,7 @@ module Homebrew
end
def __cellar
__cellar_args.parse
args = __cellar_args.parse
if args.no_named?
puts HOMEBREW_CELLAR

View File

@ -20,7 +20,7 @@ module Homebrew
end
def __prefix
__prefix_args.parse
args = __prefix_args.parse
if args.no_named?
puts HOMEBREW_PREFIX

View File

@ -18,7 +18,7 @@ module Homebrew
end
def __repository
__repository_args.parse
args = __repository_args.parse
if args.no_named?
puts HOMEBREW_REPOSITORY

View File

@ -22,14 +22,12 @@ module Homebrew
`brew analytics regenerate-uuid`:
Regenerate the UUID used for Homebrew's analytics.
EOS
switch :verbose
switch :debug
max_named 1
end
end
def analytics
analytics_args.parse
args = analytics_args.parse
case args.named.first
when nil, "state"

View File

@ -27,13 +27,11 @@ module Homebrew
"If you want to delete those too: `rm -rf \"$(brew --cache)\"`"
switch "--prune-prefix",
description: "Only prune the symlinks and directories from the prefix and remove no other files."
switch :verbose
switch :debug
end
end
def cleanup
cleanup_args.parse
args = cleanup_args.parse
cleanup = Cleanup.new(*args.named, dry_run: args.dry_run?, scrub: args.s?, days: args.prune&.to_i)
if args.prune_prefix?

View File

@ -12,19 +12,18 @@ module Homebrew
Show lists of built-in and external commands.
EOS
switch :quiet,
switch "-q", "--quiet",
description: "List only the names of commands without category headers."
switch "--include-aliases",
depends_on: "--quiet",
description: "Include aliases of internal commands."
switch :verbose
switch :debug
max_named 0
end
end
def commands
commands_args.parse
args = commands_args.parse
if args.quiet?
puts Formatter.columns(Commands.commands(aliases: args.include_aliases?))

View File

@ -14,8 +14,7 @@ module Homebrew
Show Homebrew and system configuration info useful for debugging. If you file
a bug report, you will be required to provide this information.
EOS
switch :verbose
switch :debug
max_named 0
end
end

View File

@ -53,15 +53,14 @@ module Homebrew
description: "Switch into the mode used by the `--all` option, but only list dependencies "\
"for each provided <formula>, one formula per line. This is used for "\
"debugging the `--installed`/`--all` display mode."
switch :verbose
switch :debug
conflicts "--installed", "--all"
formula_options
end
end
def deps
deps_args.parse
args = deps_args.parse
Formulary.enable_factory_cache!

View File

@ -28,14 +28,14 @@ module Homebrew
switch "-d", "--description",
description: "Search just descriptions for <text>. If <text> is flanked by slashes, "\
"it is interpreted as a regular expression."
switch :verbose
conflicts "--search", "--name", "--description"
min_named 1
end
end
def desc
desc_args.parse
args = desc_args.parse
search_type = if args.search?
:either

View File

@ -23,13 +23,11 @@ module Homebrew
"if provided as arguments."
switch "-D", "--audit-debug",
description: "Enable debugging and profiling of audit methods."
switch :verbose
switch :debug
end
end
def doctor
doctor_args.parse
args = doctor_args.parse
inject_dump_stats!(Diagnostic::Checks, /^check_*/) if args.audit_debug?

View File

@ -23,7 +23,7 @@ module Homebrew
description: "Fetch development version instead of stable version."
switch "-f", "--force",
description: "Remove a previously cached version and re-fetch."
switch :verbose,
switch "-v", "--verbose",
description: "Do a verbose VCS checkout, if the URL represents a VCS. This is useful for "\
"seeing if an existing VCS cache has been updated."
switch "--retry",
@ -38,7 +38,7 @@ module Homebrew
switch "--force-bottle",
description: "Download a bottle if it exists for the current or newest version of macOS, "\
"even if it would not be used during installation."
switch :debug
conflicts "--devel", "--HEAD"
conflicts "--build-from-source", "--build-bottle", "--force-bottle"
min_named :formula

View File

@ -28,8 +28,7 @@ module Homebrew
switch "-p", "--private",
description: "The Gist will be marked private and will not appear in listings but will "\
"be accessible with its link."
switch :verbose
switch :debug
named :formula
end
end
@ -142,7 +141,7 @@ module Homebrew
end
def gist_logs
gist_logs_args.parse
args = gist_logs_args.parse
Install.perform_preinstall_checks(all_fatal: true)
Install.perform_build_from_source_checks(all_fatal: true)

View File

@ -15,12 +15,11 @@ module Homebrew
Open <formula>'s homepage in a browser, or open Homebrew's own homepage
if no formula is provided.
EOS
switch :debug
end
end
def home
home_args.parse
args = home_args.parse
if args.no_named?
exec_browser HOMEBREW_WWW

View File

@ -52,15 +52,15 @@ module Homebrew
switch "--all",
depends_on: "--json",
description: "Print JSON of all available formulae."
switch :verbose,
switch "-v", "--verbose",
description: "Show more verbose analytics data for <formula>."
switch :debug
conflicts "--installed", "--all"
end
end
def info
info_args.parse
args = info_args.parse
if args.days.present?
raise UsageError, "--days must be one of #{VALID_DAYS.join(", ")}" unless VALID_DAYS.include?(args.days)
@ -83,17 +83,17 @@ module Homebrew
raise FormulaUnspecifiedError if args.no_named?
end
print_json
print_json(args: args)
elsif args.github?
raise FormulaUnspecifiedError if args.no_named?
exec_browser(*args.formulae.map { |f| github_info(f) })
else
print_info
print_info(args: args)
end
end
def print_info
def print_info(args:)
if args.no_named?
if args.analytics?
Utils::Analytics.output(args: args)
@ -126,7 +126,7 @@ module Homebrew
end
end
def print_json
def print_json(args:)
ff = if args.all?
Formula.sort
elsif args.installed?

View File

@ -24,7 +24,7 @@ module Homebrew
Unless `HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
installed formulae or, every 30 days, for all formulae.
EOS
switch :debug,
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB "\
"or a shell inside the temporary build directory."
flag "--env=",
@ -74,7 +74,7 @@ module Homebrew
switch "-f", "--force",
description: "Install without checking for previously installed keg-only or "\
"non-migrated versions."
switch :verbose,
switch "-v", "--verbose",
description: "Print the verification and postinstall steps."
switch "--display-times",
env: :display_install_times,

View File

@ -14,7 +14,7 @@ module Homebrew
List installed formulae that are not dependencies of another installed formula.
EOS
switch :debug
max_named 0
end
end

View File

@ -23,14 +23,13 @@ module Homebrew
"`brew link --overwrite` without actually linking or deleting any files."
switch "-f", "--force",
description: "Allow keg-only formulae to be linked."
switch :verbose
switch :debug
min_named :keg
end
end
def link
link_args.parse
args = link_args.parse
mode = OpenStruct.new

View File

@ -45,14 +45,13 @@ module Homebrew
description: "Reverse the order of the sort to list the oldest entries first."
switch "-t",
description: "Sort by time modified, listing most recently modified first."
switch :verbose
switch :debug
["--unbrewed", "--multiple", "--pinned", "-l", "-r", "-t"].each { |flag| conflicts "--cask", flag }
end
end
def list
list_args.parse
args = list_args.parse
return list_casks if args.cask?
@ -76,7 +75,14 @@ module Homebrew
puts Formatter.columns(full_names)
else
ENV["CLICOLOR"] = nil
safe_system "ls", *args.passthrough << HOMEBREW_CELLAR
ls_args = []
ls_args << "-1" if args.public_send(:'1?')
ls_args << "-l" if args.l?
ls_args << "-r" if args.r?
ls_args << "-t" if args.t?
safe_system "ls", *ls_args, HOMEBREW_CELLAR
end
elsif args.verbose? || !$stdout.tty?
system_command! "find", args: args.kegs.map(&:to_s) + %w[-not -type d -print], print_stdout: true

View File

@ -27,7 +27,7 @@ module Homebrew
end
def log
log_args.parse
args = log_args.parse
# As this command is simplifying user-run commands then let's just use a
# user path, too.

View File

@ -17,8 +17,7 @@ module Homebrew
switch "-f", "--force",
description: "Treat installed <formula> and provided <formula> as if they are from "\
"the same taps and migrate them anyway."
switch :verbose
switch :debug
min_named :formula
end
end

View File

@ -20,13 +20,11 @@ module Homebrew
comma_array "--hide",
description: "Act as if none of the specified <hidden> are installed. <hidden> should be "\
"a comma-separated list of formulae."
switch :verbose
switch :debug
end
end
def missing
missing_args.parse
args = missing_args.parse
return unless HOMEBREW_CELLAR.exist?

View File

@ -23,13 +23,13 @@ module Homebrew
description: "Show options for all available formulae."
flag "--command=",
description: "Show options for the specified <command>."
switch :debug
conflicts "--installed", "--all", "--command"
end
end
def options
options_args.parse
args = options_args.parse
if args.all?
puts_options Formula.to_a.sort

View File

@ -17,9 +17,9 @@ module Homebrew
List installed formulae that have an updated version available. By default, version
information is displayed in interactive shells, and suppressed otherwise.
EOS
switch :quiet,
switch "-q", "--quiet",
description: "List only the names of outdated kegs (takes precedence over `--verbose`)."
switch :verbose,
switch "-v", "--verbose",
description: "Include detailed version information."
flag "--json",
description: "Print output in JSON format. There are two versions: v1 and v2. " \
@ -35,16 +35,16 @@ module Homebrew
description: "Treat all arguments as formulae."
switch "--cask",
description: "Treat all arguments as casks."
switch :debug
conflicts "--quiet", "--verbose", "--json"
conflicts "--formula", "--cask"
end
end
def outdated
outdated_args.parse
args = outdated_args.parse
case json_version
case json_version(args.json)
when :v1, :default
# TODO: enable for next major/minor release
# odeprecated "brew outdated --json#{json_version == :v1 ? "=v1" : ""}", "brew outdated --json=v2"
@ -55,7 +55,7 @@ module Homebrew
outdated_casks
end
puts JSON.generate(json_info(outdated))
puts JSON.generate(json_info(outdated, args: args))
when :v2
formulae, casks = if args.formula?
@ -67,8 +67,8 @@ module Homebrew
end
json = {
"formulae" => json_info(formulae),
"casks" => json_info(casks),
"formulae" => json_info(formulae, args: args),
"casks" => json_info(casks, args: args),
}
puts JSON.generate(json)
@ -127,7 +127,7 @@ module Homebrew
end
end
def json_info(formulae_or_casks)
def json_info(formulae_or_casks, args:)
formulae_or_casks.map do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
f = formula_or_cask
@ -156,7 +156,7 @@ module Homebrew
($stdout.tty? || args.verbose?) && !args.quiet?
end
def json_version
def json_version(version)
version_hash = {
nil => nil,
true => :default,
@ -164,9 +164,9 @@ module Homebrew
"v2" => :v2,
}
raise UsageError, "invalid JSON version: #{args.json}" unless version_hash.include? args.json
raise UsageError, "invalid JSON version: #{version}" unless version_hash.include?(version)
version_hash[args.json]
version_hash[version]
end
def outdated_formulae

View File

@ -14,13 +14,13 @@ module Homebrew
Pin the specified <formula>, preventing them from being upgraded when
issuing the `brew upgrade` <formula> command. See also `unpin`.
EOS
switch :debug
min_named :formula
end
end
def pin
pin_args.parse
args = pin_args.parse
args.resolved_formulae.each do |f|
if f.pinned?

View File

@ -14,8 +14,7 @@ module Homebrew
Rerun the post-install steps for <formula>.
EOS
switch :verbose
switch :debug
min_named :keg
end
end

View File

@ -20,13 +20,11 @@ module Homebrew
description: "Verify any alias symlinks in each tap."
switch "--syntax",
description: "Syntax-check all of Homebrew's Ruby files (if no `<tap>` is passed)."
switch :verbose
switch :debug
end
end
def readall
readall_args.parse
args = readall_args.parse
if args.syntax? && args.no_named?
scan_files = "#{HOMEBREW_LIBRARY_PATH}/**/*.rb"

View File

@ -26,7 +26,7 @@ module Homebrew
Unless `HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
reinstalled formulae or, every 30 days, for all formulae.
EOS
switch :debug,
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB "\
"or a shell inside the temporary build directory."
switch "-s", "--build-from-source",
@ -43,7 +43,7 @@ module Homebrew
switch "-f", "--force",
description: "Install without checking for previously installed keg-only or "\
"non-migrated versions."
switch :verbose,
switch "-v", "--verbose",
description: "Print the verification and postinstall steps."
switch "--display-times",
env: :display_install_times,

View File

@ -51,14 +51,13 @@ module Homebrew
switch s,
description: "Search for <text> in the given package manager's list."
end
switch :verbose
switch :debug
conflicts(*package_manager_switches)
end
end
def search
search_args.parse
args = search_args.parse
if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] }
_, url = package_manager

View File

@ -14,14 +14,13 @@ module Homebrew
Symlink all of the specified <version> of <formula>'s installation into Homebrew's prefix.
EOS
switch :verbose
switch :debug
named 2
end
end
def switch
switch_args.parse
args = switch_args.parse
name = args.named.first
rack = Formulary.to_rack(name)

View File

@ -20,12 +20,11 @@ module Homebrew
description: "Print a JSON representation of <tap>. Currently the default and only accepted "\
"value for <version> is `v1`. See the docs for examples of using the JSON "\
"output: <https://docs.brew.sh/Querying-Brew>"
switch :debug
end
end
def tap_info
tap_info_args.parse
args = tap_info_args.parse
taps = if args.installed?
Tap

View File

@ -36,14 +36,13 @@ module Homebrew
description: "Migrate tapped formulae from symlink-based to directory-based structure."
switch "--list-pinned",
description: "List all pinned taps."
switch :quiet
switch :debug
max_named 2
end
end
def tap
tap_args.parse
args = tap_args.parse
if args.repair?
Tap.each(&:link_completions_and_manpages)

View File

@ -24,7 +24,7 @@ module Homebrew
switch "--ignore-dependencies",
description: "Don't fail uninstall, even if <formula> is a dependency of any installed "\
"formulae."
switch :debug
min_named :formula
end
end

View File

@ -18,14 +18,13 @@ module Homebrew
switch "-n", "--dry-run",
description: "List files which would be unlinked without actually unlinking or "\
"deleting any files."
switch :verbose
switch :debug
min_named :keg
end
end
def unlink
unlink_args.parse
args = unlink_args.parse
mode = OpenStruct.new
mode.dry_run = true if args.dry_run?

View File

@ -14,14 +14,13 @@ module Homebrew
Unpin <formula>, allowing them to be upgraded by `brew upgrade` <formula>.
See also `pin`.
EOS
switch :verbose
switch :debug
min_named :formula
end
end
def unpin
unpin_args.parse
args = unpin_args.parse
args.resolved_formulae.each do |f|
if f.pinned?

View File

@ -12,13 +12,13 @@ module Homebrew
Remove a tapped formula repository.
EOS
switch :debug
min_named 1
end
end
def untap
untap_args.parse
args = untap_args.parse
args.named.each do |tapname|
tap = Tap.fetch(tapname)

View File

@ -30,9 +30,7 @@ module Homebrew
switch "-f", "--force",
description: "Treat installed and updated formulae as if they are from "\
"the same taps and migrate them anyway."
switch :quiet
switch :verbose
switch :debug
hide_from_man_page!
end
end

View File

@ -23,7 +23,7 @@ module Homebrew
Unless `HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
upgraded formulae or, every 30 days, for all formulae.
EOS
switch :debug,
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB "\
"or a shell inside the temporary build directory."
switch "-s", "--build-from-source",
@ -46,7 +46,7 @@ module Homebrew
switch "-f", "--force",
description: "Install without checking for previously installed keg-only or "\
"non-migrated versions."
switch :verbose,
switch "-v", "--verbose",
description: "Print the verification and postinstall steps."
switch "--display-times",
env: :display_install_times,
@ -71,7 +71,7 @@ module Homebrew
named_casks_specified = !casks.empty? && formulae.empty?
upgrade_outdated_formulae(formulae, args: args) unless named_casks_specified
upgrade_outdated_casks(casks) unless named_formulae_specified
upgrade_outdated_casks(casks, args: args) unless named_formulae_specified
end
def upgrade_outdated_formulae(formulae, args:)
@ -132,7 +132,7 @@ module Homebrew
Homebrew.messages.display_messages(display_times: args.display_times?)
end
def upgrade_outdated_casks(casks)
def upgrade_outdated_casks(casks, args:)
cask_upgrade = Cask::Cmd::Upgrade.new(casks)
cask_upgrade.force = args.force?
cask_upgrade.dry_run = args.dry_run?

View File

@ -38,14 +38,14 @@ module Homebrew
description: "Show usage of <formula> by development builds."
switch "--HEAD",
description: "Show usage of <formula> by HEAD builds."
switch :debug
conflicts "--devel", "--HEAD"
min_named :formula
end
end
def uses
uses_args.parse
args = uses_args.parse
odeprecated "brew uses --devel" if args.devel?
odeprecated "brew uses --HEAD" if args.HEAD?

View File

@ -61,8 +61,7 @@ module Homebrew
comma_array "--except-cops",
description: "Specify a comma-separated <cops> list to skip checking for violations of the listed "\
"RuboCop cops."
switch :verbose
switch :debug
conflicts "--only", "--except"
conflicts "--only-cops", "--except-cops", "--strict"
conflicts "--only-cops", "--except-cops", "--only"

View File

@ -76,15 +76,14 @@ module Homebrew
"to the formula file."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
switch :verbose
switch :debug
conflicts "--no-rebuild", "--keep-old"
min_named 1
end
end
def bottle
bottle_args.parse
args = bottle_args.parse
return merge if args.merge?

View File

@ -65,9 +65,7 @@ module Homebrew
description: "Specify the new git commit <revision> corresponding to the specified <tag>."
switch "-f", "--force",
description: "Ignore duplicate open PRs. Remove all mirrors if --mirror= was not specified."
switch :quiet
switch :verbose
switch :debug
conflicts "--no-audit", "--strict"
conflicts "--url", "--tag"
max_named 1
@ -111,7 +109,7 @@ module Homebrew
end
def bump_formula_pr
bump_formula_pr_args.parse
args = bump_formula_pr_args.parse
# As this command is simplifying user-run commands then let's just use a
# user path, too.

View File

@ -18,9 +18,7 @@ module Homebrew
description: "Print what would be done rather than doing it."
flag "--message=",
description: "Append <message> to the default commit message."
switch :quiet
switch :verbose
switch :debug
named :formula
end
end

View File

@ -17,7 +17,7 @@ module Homebrew
end
def cat
cat_args.parse
args = cat_args.parse
cd HOMEBREW_REPOSITORY
pager = if Homebrew::EnvConfig.bat?
@ -26,6 +26,6 @@ module Homebrew
else
"cat"
end
safe_system pager, args.formulae_paths.first, *args.passthrough
safe_system pager, args.formulae_paths.first
end
end

View File

@ -13,14 +13,13 @@ module Homebrew
Display the path to the file being used when invoking `brew` <cmd>.
EOS
switch :verbose
switch :debug
min_named 1
end
end
def command
command_args.parse
args = command_args.parse
args.named.each do |cmd|
path = Commands.path(cmd)

View File

@ -56,8 +56,7 @@ module Homebrew
description: "Generate the new formula within the given tap, specified as <user>`/`<repo>."
switch "-f", "--force",
description: "Ignore errors for disallowed formula names and named that shadow aliases."
switch :verbose
switch :debug
conflicts "--autotools", "--cmake", "--crystal", "--go", "--meson", "--node", "--perl", "--python", "--rust"
named 1
end

View File

@ -19,14 +19,13 @@ module Homebrew
description: "Explicitly set the <name> of the package being installed."
flag "--version=",
description: "Explicitly set the <version> of the package being installed."
switch :verbose
switch :debug
max_named 0
end
end
def diy
diy_args.parse
args = diy_args.parse
path = Pathname.getwd

View File

@ -14,13 +14,11 @@ module Homebrew
Open <formula> in the editor set by `EDITOR` or `HOMEBREW_EDITOR`, or open the
Homebrew repository for editing if no formula is provided.
EOS
switch :verbose
switch :debug
end
end
def edit
edit_args.parse
args = edit_args.parse
unless (HOMEBREW_REPOSITORY/".git").directory?
raise <<~EOS

View File

@ -91,13 +91,13 @@ module Homebrew
description: "Extract the specified <version> of <formula> instead of the most recent."
switch "-f", "--force",
description: "Overwrite the destination formula if it already exists."
switch :debug
named 2
end
end
def extract
extract_args.parse
args = extract_args.parse
if args.named.first !~ HOMEBREW_TAP_FORMULA_REGEX
name = args.named.first.downcase

View File

@ -13,14 +13,13 @@ module Homebrew
Display the path where <formula> is located.
EOS
switch :verbose
switch :debug
min_named :formula
end
end
def formula
formula_args.parse
args = formula_args.parse
args.formulae_paths.each(&method(:puts))
end

View File

@ -13,7 +13,7 @@ module Homebrew
Install Homebrew's Bundler gems.
EOS
switch :debug
max_named 0
end
end

View File

@ -19,7 +19,7 @@ module Homebrew
def irb_args
# work around IRB modifying ARGV.
Homebrew::CLI::Parser.new(ARGV.dup.freeze) do
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`irb` [<options>]
@ -34,7 +34,7 @@ module Homebrew
end
def irb
irb_args.parse
args = irb_args.parse
if args.examples?
puts "'v8'.f # => instance of the v8 formula"
@ -56,6 +56,8 @@ module Homebrew
require "keg"
require "cask/all"
puts ARGV.inspect
ohai "Interactive Homebrew Shell"
puts "Example commands available with: brew irb --examples"
if args.pry?

View File

@ -24,13 +24,11 @@ module Homebrew
switch "--cached",
description: "Print the cached linkage values stored in `HOMEBREW_CACHE`, set by a previous "\
"`brew linkage` run."
switch :verbose
switch :debug
end
end
def linkage
linkage_args.parse
args = linkage_args.parse
CacheStoreDatabase.use(:linkage) do |db|
kegs = if args.kegs.empty?

View File

@ -169,7 +169,7 @@ module Homebrew
def cmd_parser_manpage_lines(cmd_parser)
lines = [format_usage_banner(cmd_parser.usage_banner_text)]
lines += cmd_parser.processed_options.map do |short, long, _, desc|
next if !long.nil? && cmd_parser.global_option?(cmd_parser.option_to_name(long), desc)
next if !long.nil? && Homebrew::CLI::Parser.global_options.include?([short, long, desc])
generate_option_doc(short, long, desc)
end.reject(&:blank?)
@ -191,7 +191,7 @@ module Homebrew
end
# Omit the common global_options documented separately in the man page.
next if line.match?(/--(debug|force|help|quiet|verbose) /)
next if line.match?(/--(debug|help|quiet|verbose) /)
# Format one option or a comma-separated pair of short and long options.
lines << line.gsub(/^ +(-+[a-z-]+), (-+[a-z-]+) +/, "* `\\1`, `\\2`:\n ")
@ -203,8 +203,7 @@ module Homebrew
def global_options_manpage
lines = ["These options are applicable across multiple subcommands.\n"]
lines += Homebrew::CLI::Parser.global_options.values.map do |names, _, desc|
short, long = names
lines += Homebrew::CLI::Parser.global_options.map do |short, long, desc|
generate_option_doc(short, long, desc)
end
lines.join("\n")

View File

@ -19,8 +19,7 @@ module Homebrew
description: "Upload to the specified Bintray repository (default: `mirror`)."
switch "--no-publish",
description: "Upload to Bintray, but don't publish."
switch :verbose
switch :debug
hide_from_man_page!
min_named :formula
end

View File

@ -25,8 +25,7 @@ module Homebrew
description: "Run `brew pr-publish` on matching pull requests."
switch "--ignore-failures",
description: "Include pull requests that have failing status checks."
switch :verbose
switch :debug
max_named 0
end
end

View File

@ -18,13 +18,13 @@ module Homebrew
description: "Target tap repository (default: `homebrew/core`)."
flag "--workflow=",
description: "Target workflow filename (default: `publish-commit-bottles.yml`)."
switch :verbose
min_named 1
end
end
def pr_publish
pr_publish_args.parse
args = pr_publish_args.parse
tap = Tap.fetch(Homebrew.args.tap || CoreTap.instance.name)
workflow = Homebrew.args.workflow || "publish-commit-bottles.yml"

View File

@ -49,8 +49,7 @@ module Homebrew
flag "--bintray-mirror=",
description: "Use the specified Bintray repository to automatically mirror stable URLs "\
"defined in the formulae (default: `mirror`)."
switch :verbose
switch :debug
min_named 1
end
end

View File

@ -27,8 +27,6 @@ module Homebrew
description: "Upload to the specified Bintray organisation (default: `homebrew`)."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
switch :verbose
switch :debug
end
end

View File

@ -37,8 +37,7 @@ module Homebrew
description: "Do not warn if pulling to a branch besides master (useful for testing)."
switch "--no-pbcopy",
description: "Do not copy anything to the system clipboard."
switch :verbose
switch :debug
min_named 1
end
end
@ -48,7 +47,7 @@ module Homebrew
odie "You meant `git pull --rebase`." if ARGV[0] == "--rebase"
pull_args.parse
args = pull_args.parse
# Passthrough Git environment variables for e.g. git am
Utils.set_git_name_email!(author: false, committer: true)

View File

@ -21,7 +21,7 @@ module Homebrew
end
def release_notes
release_notes_args.parse
args = release_notes_args.parse
previous_tag = args.named.first
previous_tag ||= Utils.popen_read(

View File

@ -17,8 +17,6 @@ module Homebrew
description: "Load a library using `require`."
switch "-e",
description: "Execute the given text string as a script."
switch :verbose
switch :debug
end
end

View File

@ -20,8 +20,7 @@ module Homebrew
EOS
flag "--env=",
description: "Use the standard `PATH` instead of superenv's when `std` is passed."
switch :verbose
switch :debug
max_named 0
end
end

View File

@ -29,14 +29,13 @@ module Homebrew
comma_array "--except-cops",
description: "Specify a comma-separated <cops> list to skip checking for violations of the "\
"listed RuboCop cops."
switch :verbose
switch :debug
conflicts "--only-cops", "--except-cops"
end
end
def style
style_args.parse
args = style_args.parse
target = if args.no_named?
nil

View File

@ -13,14 +13,13 @@ module Homebrew
Generate the template files for a new tap.
EOS
switch :verbose
switch :debug
named 1
end
end
def tap_new
tap_new_args.parse
args = tap_new_args.parse
tap_name = args.named.first
tap = Tap.fetch(args.named.first)

View File

@ -27,15 +27,14 @@ module Homebrew
description: "Retain the temporary files created for the test."
switch "--retry",
description: "Retry if a testing fails."
switch :verbose
switch :debug
conflicts "--devel", "--HEAD"
min_named :formula
end
end
def test
test_args.parse
args = test_args.parse
require "formula_assertions"
require "formula_free_port"

View File

@ -29,14 +29,13 @@ module Homebrew
"specific line."
flag "--seed=",
description: "Randomise tests with the specified <value> instead of a random seed."
switch :verbose
switch :debug
max_named 0
end
end
def tests
tests_args.parse
args = tests_args.parse
Homebrew.install_bundler_gems!
gem_user_dir = Gem.user_dir

View File

@ -24,15 +24,14 @@ module Homebrew
"patches for the software."
switch "-f", "--force",
description: "Overwrite the destination directory if it already exists."
switch :verbose
switch :debug
conflicts "--git", "--patch"
min_named :formula
end
end
def unpack
unpack_args.parse
args = unpack_args.parse
formulae = args.formulae

View File

@ -26,7 +26,7 @@ module Homebrew
end
def update_license_data
update_license_data_args.parse
args = update_license_data_args.parse
ohai "Updating SPDX license data..."
latest_tag = GitHub.open_api(SPDX_API_URL)["tag_name"]

View File

@ -21,14 +21,13 @@ module Homebrew
description: "Use the specified <commit> as the start commit."
flag "--before=",
description: "Use the commit at the specified <date> as the start commit."
switch :verbose
switch :debug
max_named 0
end
end
def update_test
update_test_args.parse
args = update_test_args.parse
ENV["HOMEBREW_UPDATE_TEST"] = "1"

View File

@ -13,7 +13,7 @@ module Homebrew
Install and commit Homebrew's vendored gems.
EOS
switch :debug
max_named 0
end
end

View File

@ -40,30 +40,30 @@ module Homebrew
module Help
module_function
def help(cmd = nil, flags = {})
# Resolve command aliases and find file containing the implementation.
path = Commands.path(cmd) if cmd
# Display command-specific (or generic) help in response to `UsageError`.
if (error_message = flags[:usage_error])
$stderr.puts path ? command_help(cmd, path) : HOMEBREW_HELP
$stderr.puts
onoe error_message
exit 1
end
def help(cmd = nil, empty_argv: false, usage_error: nil)
if cmd.nil?
# Handle `brew` (no arguments).
if flags[:empty_argv]
if empty_argv
$stderr.puts HOMEBREW_HELP
exit 1
end
# Handle `brew (-h|--help|--usage|-?|help)` (no other arguments).
if cmd.nil?
puts HOMEBREW_HELP
exit 0
end
# Resolve command aliases and find file containing the implementation.
path = Commands.path(cmd)
# Display command-specific (or generic) help in response to `UsageError`.
if usage_error
$stderr.puts path ? command_help(cmd, path) : HOMEBREW_HELP
$stderr.puts
onoe usage_error
exit 1
end
# Resume execution in `brew.rb` for unknown commands.
return if path.nil?

View File

@ -6,7 +6,6 @@ describe Homebrew::CLI::Parser do
describe "test switch options" do
subject(:parser) {
described_class.new do
switch :verbose, description: "Flag for verbosity"
switch "--more-verbose", description: "Flag for higher verbosity"
switch "--pry", env: :pry
end
@ -17,26 +16,25 @@ describe Homebrew::CLI::Parser do
end
it "parses short option" do
parser.parse(["-v"])
expect(Homebrew.args).to be_verbose
args = parser.parse(["-v"])
expect(args).to be_verbose
end
it "parses a single valid option" do
parser.parse(["--verbose"])
expect(Homebrew.args).to be_verbose
args = parser.parse(["--verbose"])
expect(args).to be_verbose
end
it "parses a valid option along with few unnamed args" do
args = %w[--verbose unnamed args]
parser.parse(args)
expect(Homebrew.args).to be_verbose
expect(args).to eq %w[--verbose unnamed args]
args = parser.parse(%w[--verbose unnamed args])
expect(args).to be_verbose
expect(args.named).to eq %w[unnamed args]
end
it "parses a single option and checks other options to be nil" do
parser.parse(["--verbose"])
expect(Homebrew.args).to be_verbose
expect(Homebrew.args.more_verbose?).to be nil
args = parser.parse(["--verbose"])
expect(args).to be_verbose
expect(args.more_verbose?).to be nil
end
it "raises an exception and outputs help text when an invalid option is passed" do
@ -45,13 +43,8 @@ describe Homebrew::CLI::Parser do
end
it "maps environment var to an option" do
parser.parse([])
expect(Homebrew.args.pry?).to be true
end
it ":verbose with custom description" do
_, _, _, desc = parser.processed_options.find { |short, _| short == "-v" }
expect(desc).to eq "Flag for verbosity"
args = parser.parse([])
expect(args.pry?).to be true
end
end
@ -64,8 +57,8 @@ describe Homebrew::CLI::Parser do
}
it "parses a long flag option with its argument" do
parser.parse(["--filename=random.txt"])
expect(Homebrew.args.filename).to eq "random.txt"
args = parser.parse(["--filename=random.txt"])
expect(args.filename).to eq "random.txt"
end
it "raises an exception when a flag's required value is not passed" do
@ -73,8 +66,8 @@ describe Homebrew::CLI::Parser do
end
it "parses a comma array flag option" do
parser.parse(["--files=random1.txt,random2.txt"])
expect(Homebrew.args.files).to eq %w[random1.txt random2.txt]
args = parser.parse(["--files=random1.txt,random2.txt"])
expect(args.files).to eq %w[random1.txt random2.txt]
end
end
@ -86,9 +79,9 @@ describe Homebrew::CLI::Parser do
}
it "parses a short flag option with its argument" do
parser.parse(["--filename=random.txt"])
expect(Homebrew.args.filename).to eq "random.txt"
expect(Homebrew.args.f).to eq "random.txt"
args = parser.parse(["--filename=random.txt"])
expect(args.filename).to eq "random.txt"
expect(args.f).to eq "random.txt"
end
end
@ -118,14 +111,14 @@ describe Homebrew::CLI::Parser do
end
it "raises no exception" do
parser.parse(["--flag1=flag1", "--flag2=flag2"])
expect(Homebrew.args.flag1).to eq "flag1"
expect(Homebrew.args.flag2).to eq "flag2"
args = parser.parse(["--flag1=flag1", "--flag2=flag2"])
expect(args.flag1).to eq "flag1"
expect(args.flag2).to eq "flag2"
end
it "raises no exception for optional dependency" do
parser.parse(["--flag3=flag3"])
expect(Homebrew.args.flag3).to eq "flag3"
args = parser.parse(["--flag3=flag3"])
expect(args.flag3).to eq "flag3"
end
end
@ -169,22 +162,22 @@ describe Homebrew::CLI::Parser do
end
it "raises no exception" do
parser.parse(["--switch-a", "--switch-c"])
expect(Homebrew.args.switch_a?).to be true
expect(Homebrew.args.switch_c?).to be true
args = parser.parse(["--switch-a", "--switch-c"])
expect(args.switch_a?).to be true
expect(args.switch_c?).to be true
end
it "raises no exception for optional dependency" do
parser.parse(["--switch-b"])
expect(Homebrew.args.switch_b?).to be true
args = parser.parse(["--switch-b"])
expect(args.switch_b?).to be true
end
it "prioritizes cli arguments over env vars when they conflict" do
allow(Homebrew::EnvConfig).to receive(:switch_a?).and_return(true)
allow(Homebrew::EnvConfig).to receive(:switch_b?).and_return(false)
parser.parse(["--switch-b"])
expect(Homebrew.args.switch_a).to be_falsy
expect(Homebrew.args).to be_switch_b
args = parser.parse(["--switch-b"])
expect(args.switch_a).to be_falsy
expect(args).to be_switch_b
end
it "raises an exception on constraint violation when both are env vars" do
@ -214,38 +207,32 @@ describe Homebrew::CLI::Parser 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]
args = parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
expect(args.options_only).to eq %w[--verbose --foo --bar=value -s]
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
it "#passthrough" do
parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
expect(Homebrew.args.passthrough).to eq %w[--foo --bar=value -s]
args = parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
expect(args.flags_only).to eq %w[--verbose --foo --bar=value]
end
it "#formulae raises an error when a Formula is unavailable" do
parser.parse(["mxcl"])
expect { Homebrew.args.formulae }.to raise_error FormulaUnavailableError
args = parser.parse(["mxcl"])
expect { args.formulae }.to raise_error FormulaUnavailableError
end
it "#formulae returns an empty array when there are no Formulae" do
parser.parse([])
expect(Homebrew.args.formulae).to be_empty
args = parser.parse([])
expect(args.formulae).to be_empty
end
it "#casks returns an empty array when there are no matching casks" do
parser.parse([])
expect(Homebrew.args.casks).to eq []
args = parser.parse([])
expect(args.casks).to eq []
end
context "kegs" do
@ -255,24 +242,24 @@ describe Homebrew::CLI::Parser do
end
it "when there are matching kegs returns an array of Kegs" do
parser.parse(["mxcl"])
expect(Homebrew.args.kegs.length).to eq 1
args = parser.parse(["mxcl"])
expect(args.kegs.length).to eq 1
end
it "when there are no matching kegs returns an array of Kegs" do
parser.parse([])
expect(Homebrew.args.kegs).to be_empty
args = parser.parse([])
expect(args.kegs).to be_empty
end
end
it "#named returns an array of non-option arguments" do
parser.parse(["foo", "-v", "-s"])
expect(Homebrew.args.named).to eq ["foo"]
args = parser.parse(["foo", "-v", "-s"])
expect(args.named).to eq ["foo"]
end
it "#named returns an empty array when there are no named arguments" do
parser.parse([])
expect(Homebrew.args.named).to be_empty
args = parser.parse([])
expect(args.named).to be_empty
end
end
end

View File

@ -14,7 +14,8 @@ shared_examples "parseable arguments" do
it "can parse arguments" do
require "dev-cmd/#{command_name}" unless require? "cmd/#{command_name}"
expect { Homebrew.send(method_name).parse({}, allow_no_named_args: true) }
.not_to raise_error
parser = Homebrew.public_send(method_name)
expect(parser).to respond_to(:parse)
end
end

View File

@ -50,7 +50,7 @@ describe FormulaInstaller do
specify "basic bottle install" do
allow(DevelopmentTools).to receive(:installed?).and_return(false)
Homebrew.install_args.parse("testball_bottle")
Homebrew.install_args.parse(["testball_bottle"])
temporarily_install_bottle(TestballBottle.new) do |f|
# Copied directly from formula_installer_spec.rb
# as we expect the same behavior.

View File

@ -525,6 +525,8 @@ Fetch the newest version of Homebrew and all formulae from GitHub using `git`(1)
Use `git merge` to apply updates (rather than `git rebase`).
* `--preinstall`:
Run on auto-updates (e.g. before `brew install`). Skips some slower steps.
* `-f`, `--force`:
Always do a slower, full update check (even if unnecessary).
### `update-reset` [*`repository`*]
@ -1190,8 +1192,6 @@ flags which will help find keg-only dependencies like `openssl`, `icu4c`, etc.
Read the `Brewfile` from this location. Use `--file=-` to pipe to stdin/stdout.
* `--global`:
Read the `Brewfile` from `~/.Brewfile`.
* `-v`, `--verbose`:
`install` prints output from commands as they are run. `check` lists all missing dependencies.
* `--no-upgrade`:
`install` won't run `brew upgrade` on outdated dependencies. Note they may still be upgraded by `brew install` if needed.
* `-f`, `--force`:

View File

@ -682,6 +682,10 @@ Use \fBgit merge\fR to apply updates (rather than \fBgit rebase\fR)\.
\fB\-\-preinstall\fR
Run on auto\-updates (e\.g\. before \fBbrew install\fR)\. Skips some slower steps\.
.
.TP
\fB\-f\fR, \fB\-\-force\fR
Always do a slower, full update check (even if unnecessary)\.
.
.SS "\fBupdate\-reset\fR [\fIrepository\fR]"
Fetch and reset Homebrew and all tap repositories (or any specified \fIrepository\fR) using \fBgit\fR(1) to their latest \fBorigin/master\fR\.
.
@ -1535,10 +1539,6 @@ Read the \fBBrewfile\fR from this location\. Use \fB\-\-file=\-\fR to pipe to st
Read the \fBBrewfile\fR from \fB~/\.Brewfile\fR\.
.
.TP
\fB\-v\fR, \fB\-\-verbose\fR
\fBinstall\fR prints output from commands as they are run\. \fBcheck\fR lists all missing dependencies\.
.
.TP
\fB\-\-no\-upgrade\fR
\fBinstall\fR won\'t run \fBbrew upgrade\fR on outdated dependencies\. Note they may still be upgraded by \fBbrew install\fR if needed\.
.