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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,19 +12,18 @@ module Homebrew
Show lists of built-in and external commands. Show lists of built-in and external commands.
EOS EOS
switch :quiet, switch "-q", "--quiet",
description: "List only the names of commands without category headers." description: "List only the names of commands without category headers."
switch "--include-aliases", switch "--include-aliases",
depends_on: "--quiet", depends_on: "--quiet",
description: "Include aliases of internal commands." description: "Include aliases of internal commands."
switch :verbose
switch :debug
max_named 0 max_named 0
end end
end end
def commands def commands
commands_args.parse args = commands_args.parse
if args.quiet? if args.quiet?
puts Formatter.columns(Commands.commands(aliases: args.include_aliases?)) 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 Show Homebrew and system configuration info useful for debugging. If you file
a bug report, you will be required to provide this information. a bug report, you will be required to provide this information.
EOS EOS
switch :verbose
switch :debug
max_named 0 max_named 0
end end
end end

View File

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

View File

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

View File

@ -23,13 +23,11 @@ module Homebrew
"if provided as arguments." "if provided as arguments."
switch "-D", "--audit-debug", switch "-D", "--audit-debug",
description: "Enable debugging and profiling of audit methods." description: "Enable debugging and profiling of audit methods."
switch :verbose
switch :debug
end end
end end
def doctor def doctor
doctor_args.parse args = doctor_args.parse
inject_dump_stats!(Diagnostic::Checks, /^check_*/) if args.audit_debug? 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." description: "Fetch development version instead of stable version."
switch "-f", "--force", switch "-f", "--force",
description: "Remove a previously cached version and re-fetch." 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 "\ 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." "seeing if an existing VCS cache has been updated."
switch "--retry", switch "--retry",
@ -38,7 +38,7 @@ module Homebrew
switch "--force-bottle", switch "--force-bottle",
description: "Download a bottle if it exists for the current or newest version of macOS, "\ description: "Download a bottle if it exists for the current or newest version of macOS, "\
"even if it would not be used during installation." "even if it would not be used during installation."
switch :debug
conflicts "--devel", "--HEAD" conflicts "--devel", "--HEAD"
conflicts "--build-from-source", "--build-bottle", "--force-bottle" conflicts "--build-from-source", "--build-bottle", "--force-bottle"
min_named :formula min_named :formula

View File

@ -28,8 +28,7 @@ module Homebrew
switch "-p", "--private", switch "-p", "--private",
description: "The Gist will be marked private and will not appear in listings but will "\ description: "The Gist will be marked private and will not appear in listings but will "\
"be accessible with its link." "be accessible with its link."
switch :verbose
switch :debug
named :formula named :formula
end end
end end
@ -142,7 +141,7 @@ module Homebrew
end end
def gist_logs def gist_logs
gist_logs_args.parse args = gist_logs_args.parse
Install.perform_preinstall_checks(all_fatal: true) Install.perform_preinstall_checks(all_fatal: true)
Install.perform_build_from_source_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 Open <formula>'s homepage in a browser, or open Homebrew's own homepage
if no formula is provided. if no formula is provided.
EOS EOS
switch :debug
end end
end end
def home def home
home_args.parse args = home_args.parse
if args.no_named? if args.no_named?
exec_browser HOMEBREW_WWW exec_browser HOMEBREW_WWW

View File

@ -52,15 +52,15 @@ module Homebrew
switch "--all", switch "--all",
depends_on: "--json", depends_on: "--json",
description: "Print JSON of all available formulae." description: "Print JSON of all available formulae."
switch :verbose, switch "-v", "--verbose",
description: "Show more verbose analytics data for <formula>." description: "Show more verbose analytics data for <formula>."
switch :debug
conflicts "--installed", "--all" conflicts "--installed", "--all"
end end
end end
def info def info
info_args.parse args = info_args.parse
if args.days.present? if args.days.present?
raise UsageError, "--days must be one of #{VALID_DAYS.join(", ")}" unless VALID_DAYS.include?(args.days) 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? raise FormulaUnspecifiedError if args.no_named?
end end
print_json print_json(args: args)
elsif args.github? elsif args.github?
raise FormulaUnspecifiedError if args.no_named? raise FormulaUnspecifiedError if args.no_named?
exec_browser(*args.formulae.map { |f| github_info(f) }) exec_browser(*args.formulae.map { |f| github_info(f) })
else else
print_info print_info(args: args)
end end
end end
def print_info def print_info(args:)
if args.no_named? if args.no_named?
if args.analytics? if args.analytics?
Utils::Analytics.output(args: args) Utils::Analytics.output(args: args)
@ -126,7 +126,7 @@ module Homebrew
end end
end end
def print_json def print_json(args:)
ff = if args.all? ff = if args.all?
Formula.sort Formula.sort
elsif args.installed? 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 Unless `HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
installed formulae or, every 30 days, for all formulae. installed formulae or, every 30 days, for all formulae.
EOS EOS
switch :debug, switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB "\ description: "If brewing fails, open an interactive debugging session with access to IRB "\
"or a shell inside the temporary build directory." "or a shell inside the temporary build directory."
flag "--env=", flag "--env=",
@ -74,7 +74,7 @@ module Homebrew
switch "-f", "--force", switch "-f", "--force",
description: "Install without checking for previously installed keg-only or "\ description: "Install without checking for previously installed keg-only or "\
"non-migrated versions." "non-migrated versions."
switch :verbose, switch "-v", "--verbose",
description: "Print the verification and postinstall steps." description: "Print the verification and postinstall steps."
switch "--display-times", switch "--display-times",
env: :display_install_times, env: :display_install_times,

View File

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

View File

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

View File

@ -45,14 +45,13 @@ module Homebrew
description: "Reverse the order of the sort to list the oldest entries first." description: "Reverse the order of the sort to list the oldest entries first."
switch "-t", switch "-t",
description: "Sort by time modified, listing most recently modified first." 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 } ["--unbrewed", "--multiple", "--pinned", "-l", "-r", "-t"].each { |flag| conflicts "--cask", flag }
end end
end end
def list def list
list_args.parse args = list_args.parse
return list_casks if args.cask? return list_casks if args.cask?
@ -76,7 +75,14 @@ module Homebrew
puts Formatter.columns(full_names) puts Formatter.columns(full_names)
else else
ENV["CLICOLOR"] = nil 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 end
elsif args.verbose? || !$stdout.tty? elsif args.verbose? || !$stdout.tty?
system_command! "find", args: args.kegs.map(&:to_s) + %w[-not -type d -print], print_stdout: true 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 end
def log def log
log_args.parse args = log_args.parse
# As this command is simplifying user-run commands then let's just use a # As this command is simplifying user-run commands then let's just use a
# user path, too. # user path, too.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,13 +20,11 @@ module Homebrew
description: "Verify any alias symlinks in each tap." description: "Verify any alias symlinks in each tap."
switch "--syntax", switch "--syntax",
description: "Syntax-check all of Homebrew's Ruby files (if no `<tap>` is passed)." description: "Syntax-check all of Homebrew's Ruby files (if no `<tap>` is passed)."
switch :verbose
switch :debug
end end
end end
def readall def readall
readall_args.parse args = readall_args.parse
if args.syntax? && args.no_named? if args.syntax? && args.no_named?
scan_files = "#{HOMEBREW_LIBRARY_PATH}/**/*.rb" 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 Unless `HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
reinstalled formulae or, every 30 days, for all formulae. reinstalled formulae or, every 30 days, for all formulae.
EOS EOS
switch :debug, switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB "\ description: "If brewing fails, open an interactive debugging session with access to IRB "\
"or a shell inside the temporary build directory." "or a shell inside the temporary build directory."
switch "-s", "--build-from-source", switch "-s", "--build-from-source",
@ -43,7 +43,7 @@ module Homebrew
switch "-f", "--force", switch "-f", "--force",
description: "Install without checking for previously installed keg-only or "\ description: "Install without checking for previously installed keg-only or "\
"non-migrated versions." "non-migrated versions."
switch :verbose, switch "-v", "--verbose",
description: "Print the verification and postinstall steps." description: "Print the verification and postinstall steps."
switch "--display-times", switch "--display-times",
env: :display_install_times, env: :display_install_times,

View File

@ -51,14 +51,13 @@ module Homebrew
switch s, switch s,
description: "Search for <text> in the given package manager's list." description: "Search for <text> in the given package manager's list."
end end
switch :verbose
switch :debug
conflicts(*package_manager_switches) conflicts(*package_manager_switches)
end end
end end
def search def search
search_args.parse args = search_args.parse
if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] } if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] }
_, url = package_manager _, 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. Symlink all of the specified <version> of <formula>'s installation into Homebrew's prefix.
EOS EOS
switch :verbose
switch :debug
named 2 named 2
end end
end end
def switch def switch
switch_args.parse args = switch_args.parse
name = args.named.first name = args.named.first
rack = Formulary.to_rack(name) 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 "\ 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 "\ "value for <version> is `v1`. See the docs for examples of using the JSON "\
"output: <https://docs.brew.sh/Querying-Brew>" "output: <https://docs.brew.sh/Querying-Brew>"
switch :debug
end end
end end
def tap_info def tap_info
tap_info_args.parse args = tap_info_args.parse
taps = if args.installed? taps = if args.installed?
Tap Tap

View File

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

View File

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

View File

@ -18,14 +18,13 @@ module Homebrew
switch "-n", "--dry-run", switch "-n", "--dry-run",
description: "List files which would be unlinked without actually unlinking or "\ description: "List files which would be unlinked without actually unlinking or "\
"deleting any files." "deleting any files."
switch :verbose
switch :debug
min_named :keg min_named :keg
end end
end end
def unlink def unlink
unlink_args.parse args = unlink_args.parse
mode = OpenStruct.new mode = OpenStruct.new
mode.dry_run = true if args.dry_run? 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>. Unpin <formula>, allowing them to be upgraded by `brew upgrade` <formula>.
See also `pin`. See also `pin`.
EOS EOS
switch :verbose
switch :debug
min_named :formula min_named :formula
end end
end end
def unpin def unpin
unpin_args.parse args = unpin_args.parse
args.resolved_formulae.each do |f| args.resolved_formulae.each do |f|
if f.pinned? if f.pinned?

View File

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

View File

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

View File

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

View File

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

View File

@ -76,15 +76,14 @@ module Homebrew
"to the formula file." "to the formula file."
flag "--root-url=", flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default." 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" conflicts "--no-rebuild", "--keep-old"
min_named 1 min_named 1
end end
end end
def bottle def bottle
bottle_args.parse args = bottle_args.parse
return merge if args.merge? 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>." description: "Specify the new git commit <revision> corresponding to the specified <tag>."
switch "-f", "--force", switch "-f", "--force",
description: "Ignore duplicate open PRs. Remove all mirrors if --mirror= was not specified." description: "Ignore duplicate open PRs. Remove all mirrors if --mirror= was not specified."
switch :quiet
switch :verbose
switch :debug
conflicts "--no-audit", "--strict" conflicts "--no-audit", "--strict"
conflicts "--url", "--tag" conflicts "--url", "--tag"
max_named 1 max_named 1
@ -111,7 +109,7 @@ module Homebrew
end end
def bump_formula_pr 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 # As this command is simplifying user-run commands then let's just use a
# user path, too. # user path, too.

View File

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

View File

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

View File

@ -13,14 +13,13 @@ module Homebrew
Display the path to the file being used when invoking `brew` <cmd>. Display the path to the file being used when invoking `brew` <cmd>.
EOS EOS
switch :verbose
switch :debug
min_named 1 min_named 1
end end
end end
def command def command
command_args.parse args = command_args.parse
args.named.each do |cmd| args.named.each do |cmd|
path = Commands.path(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>." description: "Generate the new formula within the given tap, specified as <user>`/`<repo>."
switch "-f", "--force", switch "-f", "--force",
description: "Ignore errors for disallowed formula names and named that shadow aliases." 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" conflicts "--autotools", "--cmake", "--crystal", "--go", "--meson", "--node", "--perl", "--python", "--rust"
named 1 named 1
end end

View File

@ -19,14 +19,13 @@ module Homebrew
description: "Explicitly set the <name> of the package being installed." description: "Explicitly set the <name> of the package being installed."
flag "--version=", flag "--version=",
description: "Explicitly set the <version> of the package being installed." description: "Explicitly set the <version> of the package being installed."
switch :verbose
switch :debug
max_named 0 max_named 0
end end
end end
def diy def diy
diy_args.parse args = diy_args.parse
path = Pathname.getwd 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 Open <formula> in the editor set by `EDITOR` or `HOMEBREW_EDITOR`, or open the
Homebrew repository for editing if no formula is provided. Homebrew repository for editing if no formula is provided.
EOS EOS
switch :verbose
switch :debug
end end
end end
def edit def edit
edit_args.parse args = edit_args.parse
unless (HOMEBREW_REPOSITORY/".git").directory? unless (HOMEBREW_REPOSITORY/".git").directory?
raise <<~EOS raise <<~EOS

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,14 +13,13 @@ module Homebrew
Generate the template files for a new tap. Generate the template files for a new tap.
EOS EOS
switch :verbose
switch :debug
named 1 named 1
end end
end end
def tap_new def tap_new
tap_new_args.parse args = tap_new_args.parse
tap_name = args.named.first tap_name = args.named.first
tap = Tap.fetch(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." description: "Retain the temporary files created for the test."
switch "--retry", switch "--retry",
description: "Retry if a testing fails." description: "Retry if a testing fails."
switch :verbose
switch :debug
conflicts "--devel", "--HEAD" conflicts "--devel", "--HEAD"
min_named :formula min_named :formula
end end
end end
def test def test
test_args.parse args = test_args.parse
require "formula_assertions" require "formula_assertions"
require "formula_free_port" require "formula_free_port"

View File

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

View File

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

View File

@ -26,7 +26,7 @@ module Homebrew
end end
def update_license_data def update_license_data
update_license_data_args.parse args = update_license_data_args.parse
ohai "Updating SPDX license data..." ohai "Updating SPDX license data..."
latest_tag = GitHub.open_api(SPDX_API_URL)["tag_name"] 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." description: "Use the specified <commit> as the start commit."
flag "--before=", flag "--before=",
description: "Use the commit at the specified <date> as the start commit." description: "Use the commit at the specified <date> as the start commit."
switch :verbose
switch :debug
max_named 0 max_named 0
end end
end end
def update_test def update_test
update_test_args.parse args = update_test_args.parse
ENV["HOMEBREW_UPDATE_TEST"] = "1" ENV["HOMEBREW_UPDATE_TEST"] = "1"

View File

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

View File

@ -40,30 +40,30 @@ module Homebrew
module Help module Help
module_function module_function
def help(cmd = nil, flags = {}) def help(cmd = nil, empty_argv: false, usage_error: nil)
# 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
# Handle `brew` (no arguments).
if flags[:empty_argv]
$stderr.puts HOMEBREW_HELP
exit 1
end
# Handle `brew (-h|--help|--usage|-?|help)` (no other arguments).
if cmd.nil? if cmd.nil?
# Handle `brew` (no arguments).
if empty_argv
$stderr.puts HOMEBREW_HELP
exit 1
end
# Handle `brew (-h|--help|--usage|-?|help)` (no other arguments).
puts HOMEBREW_HELP puts HOMEBREW_HELP
exit 0 exit 0
end 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. # Resume execution in `brew.rb` for unknown commands.
return if path.nil? return if path.nil?

View File

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

View File

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

View File

@ -50,7 +50,7 @@ describe FormulaInstaller do
specify "basic bottle install" do specify "basic bottle install" do
allow(DevelopmentTools).to receive(:installed?).and_return(false) 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| temporarily_install_bottle(TestballBottle.new) do |f|
# Copied directly from formula_installer_spec.rb # Copied directly from formula_installer_spec.rb
# as we expect the same behavior. # 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`). Use `git merge` to apply updates (rather than `git rebase`).
* `--preinstall`: * `--preinstall`:
Run on auto-updates (e.g. before `brew install`). Skips some slower steps. 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`*] ### `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. Read the `Brewfile` from this location. Use `--file=-` to pipe to stdin/stdout.
* `--global`: * `--global`:
Read the `Brewfile` from `~/.Brewfile`. Read the `Brewfile` from `~/.Brewfile`.
* `-v`, `--verbose`:
`install` prints output from commands as they are run. `check` lists all missing dependencies.
* `--no-upgrade`: * `--no-upgrade`:
`install` won't run `brew upgrade` on outdated dependencies. Note they may still be upgraded by `brew install` if needed. `install` won't run `brew upgrade` on outdated dependencies. Note they may still be upgraded by `brew install` if needed.
* `-f`, `--force`: * `-f`, `--force`:

View File

@ -682,6 +682,10 @@ Use \fBgit merge\fR to apply updates (rather than \fBgit rebase\fR)\.
\fB\-\-preinstall\fR \fB\-\-preinstall\fR
Run on auto\-updates (e\.g\. before \fBbrew install\fR)\. Skips some slower steps\. 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]" .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\. 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\. Read the \fBBrewfile\fR from \fB~/\.Brewfile\fR\.
. .
.TP .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 \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\. \fBinstall\fR won\'t run \fBbrew upgrade\fR on outdated dependencies\. Note they may still be upgraded by \fBbrew install\fR if needed\.
. .