Merge pull request #16745 from issyl0/rubocop-todos-2

rubocop: Fix remaining TODOs for triaging Ruby 3 cops
This commit is contained in:
Issy Long 2024-02-26 16:19:14 +00:00 committed by GitHub
commit 7848bd3226
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
58 changed files with 159 additions and 172 deletions

View File

@ -171,6 +171,10 @@ Lint/UnusedMethodArgument:
Metrics: Metrics:
Enabled: false Enabled: false
# Disabled because it breaks Sorbet: "The declaration for `with` is missing parameter(s): & (RuntimeError)"
Naming/BlockForwarding:
Enabled: false
# Allow dashes in filenames. # Allow dashes in filenames.
Naming/FileName: Naming/FileName:
Regex: !ruby/regexp /^[\w\@\-\+\.]+(\.rb)?$/ Regex: !ruby/regexp /^[\w\@\-\+\.]+(\.rb)?$/
@ -289,6 +293,10 @@ Sorbet/TrueSigil:
Style/AndOr: Style/AndOr:
EnforcedStyle: always EnforcedStyle: always
# Disabled because it breaks Sorbet: "The declaration for `with` is missing parameter(s): & (RuntimeError)"
Style/ArgumentsForwarding:
Enabled: false
# Avoid leaking resources. # Avoid leaking resources.
Style/AutoResourceCleanup: Style/AutoResourceCleanup:
Enabled: true Enabled: true
@ -358,6 +366,9 @@ Style/HashAsLastArrayItem:
- "/**/Formula/**/*.rb" - "/**/Formula/**/*.rb"
- "**/Formula/**/*.rb" - "**/Formula/**/*.rb"
Style/HashSyntax:
EnforcedShorthandSyntax: either
Style/InverseMethods: Style/InverseMethods:
InverseMethods: InverseMethods:
:blank?: :present? :blank?: :present?
@ -460,17 +471,3 @@ Style/UnlessLogicalOperators:
# a bit confusing to non-Rubyists but useful for longer arrays # a bit confusing to non-Rubyists but useful for longer arrays
Style/WordArray: Style/WordArray:
MinSize: 4 MinSize: 4
# TODO: Enable these cops once https://github.com/Homebrew/brew/pull/16337#issuecomment-1855668516 is done.
Lint/RedundantDirGlobSort:
Enabled: false
Naming/BlockForwarding:
Enabled: false
Performance/BindCall:
Enabled: false
Performance/MapCompact:
Enabled: false
Style/ArgumentsForwarding:
Enabled: false
Style/HashSyntax:
EnforcedShorthandSyntax: either

View File

@ -169,10 +169,10 @@ module Cask
regex = Regexp.escape(search).gsub("\\*", ".*") regex = Regexp.escape(search).gsub("\\*", ".*")
system_command!("/bin/launchctl", args: ["list"]) system_command!("/bin/launchctl", args: ["list"])
.stdout.lines.drop(1) # skip stdout column headers .stdout.lines.drop(1) # skip stdout column headers
.map do |line| .filter_map do |line|
pid, _state, id = line.chomp.split(/\s+/) pid, _state, id = line.chomp.split(/\s+/)
id if pid.to_i.nonzero? && id.match?(regex) id if pid.to_i.nonzero? && id.match?(regex)
end.compact end
end end
sig { returns(String) } sig { returns(String) }

View File

@ -33,13 +33,13 @@ module Cask
# Load core casks from tokens so they load from the API when the core cask is not tapped. # Load core casks from tokens so they load from the API when the core cask is not tapped.
tokens_and_files = CoreCaskTap.instance.cask_tokens tokens_and_files = CoreCaskTap.instance.cask_tokens
tokens_and_files += Tap.reject(&:core_cask_tap?).flat_map(&:cask_files) tokens_and_files += Tap.reject(&:core_cask_tap?).flat_map(&:cask_files)
tokens_and_files.map do |token_or_file| tokens_and_files.filter_map do |token_or_file|
CaskLoader.load(token_or_file) CaskLoader.load(token_or_file)
rescue CaskUnreadableError => e rescue CaskUnreadableError => e
opoo e.message opoo e.message
nil nil
end.compact end
end end
def tap def tap

View File

@ -469,8 +469,7 @@ module Cask
token = ref token = ref
loaders = Tap.map { |tap| super("#{tap}/#{token}", warn: warn) } loaders = Tap.filter_map { |tap| super("#{tap}/#{token}", warn: warn) }
.compact
.select { _1.path.exist? } .select { _1.path.exist? }
case loaders.count case loaders.count

View File

@ -52,14 +52,14 @@ module Cask
sig { params(config: T.nilable(Config)).returns(T::Array[Cask]) } sig { params(config: T.nilable(Config)).returns(T::Array[Cask]) }
def self.casks(config: nil) def self.casks(config: nil)
tokens.sort.map do |token| tokens.sort.filter_map do |token|
CaskLoader.load(token, config: config, warn: false) CaskLoader.load(token, config: config, warn: false)
rescue TapCaskAmbiguityError => e rescue TapCaskAmbiguityError => e
T.must(e.loaders.first).load(config: config) T.must(e.loaders.first).load(config: config)
rescue rescue
# Don't blow up because of a single unavailable cask. # Don't blow up because of a single unavailable cask.
nil nil
end.compact end
end end
end end
end end

View File

@ -180,12 +180,11 @@ module Cask
raise CaskInvalidError.new(cask, "No default language specified.") if @language_blocks.default.nil? raise CaskInvalidError.new(cask, "No default language specified.") if @language_blocks.default.nil?
locales = cask.config.languages locales = cask.config.languages
.map do |language| .filter_map do |language|
Locale.parse(language) Locale.parse(language)
rescue Locale::ParserError rescue Locale::ParserError
nil nil
end end
.compact
locales.each do |locale| locales.each do |locale|
key = locale.detect(@language_blocks.keys) key = locale.detect(@language_blocks.keys)

View File

@ -102,11 +102,11 @@ class Caveats
private private
def keg def keg
@keg ||= [formula.prefix, formula.opt_prefix, formula.linked_keg].map do |d| @keg ||= [formula.prefix, formula.opt_prefix, formula.linked_keg].filter_map do |d|
Keg.new(d.resolved_path) Keg.new(d.resolved_path)
rescue rescue
nil nil
end.compact.first end.first
end end
def function_completion_caveats(shell) def function_completion_caveats(shell)

View File

@ -447,11 +447,11 @@ module Homebrew
def generate_usage_banner def generate_usage_banner
command_names = ["`#{@command_name}`"] command_names = ["`#{@command_name}`"]
aliases_to_skip = %w[instal uninstal] aliases_to_skip = %w[instal uninstal]
command_names += Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.map do |command_alias, command| command_names += Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.filter_map do |command_alias, command|
next if aliases_to_skip.include? command_alias next if aliases_to_skip.include? command_alias
"`#{command_alias}`" if command == @command_name "`#{command_alias}`" if command == @command_name
end.compact.sort end.sort
options = if @non_global_processed_options.empty? options = if @non_global_processed_options.empty?
"" ""
@ -469,12 +469,12 @@ module Homebrew
named_args = "" named_args = ""
if @named_args_type.present? && @named_args_type != :none if @named_args_type.present? && @named_args_type != :none
arg_type = if @named_args_type.is_a? Array arg_type = if @named_args_type.is_a? Array
types = @named_args_type.map do |type| types = @named_args_type.filter_map do |type|
next unless type.is_a? Symbol next unless type.is_a? Symbol
next SYMBOL_TO_USAGE_MAPPING[type] if SYMBOL_TO_USAGE_MAPPING.key?(type) next SYMBOL_TO_USAGE_MAPPING[type] if SYMBOL_TO_USAGE_MAPPING.key?(type)
"<#{type}>" "<#{type}>"
end.compact end
types << "<subcommand>" if @named_args_type.any?(String) types << "<subcommand>" if @named_args_type.any?(String)
types.join("|") types.join("|")
elsif SYMBOL_TO_USAGE_MAPPING.key? @named_args_type elsif SYMBOL_TO_USAGE_MAPPING.key? @named_args_type
@ -593,11 +593,11 @@ module Homebrew
end end
def check_named_args(args) def check_named_args(args)
types = Array(@named_args_type).map do |type| types = Array(@named_args_type).filter_map do |type|
next type if type.is_a? Symbol next type if type.is_a? Symbol
:subcommand :subcommand
end.compact.uniq end.uniq
exception = if @min_named_args && @max_named_args && @min_named_args == @max_named_args && exception = if @min_named_args && @max_named_args && @min_named_args == @max_named_args &&
args.size != @max_named_args args.size != @max_named_args
@ -650,7 +650,7 @@ module Homebrew
end end
# Only lowercase names, not paths, bottle filenames or URLs # Only lowercase names, not paths, bottle filenames or URLs
named_args.map do |arg| named_args.filter_map do |arg|
next if arg.match?(HOMEBREW_CASK_TAP_CASK_REGEX) next if arg.match?(HOMEBREW_CASK_TAP_CASK_REGEX)
begin begin
@ -658,7 +658,7 @@ module Homebrew
rescue FormulaUnavailableError, FormulaSpecificationError rescue FormulaUnavailableError, FormulaSpecificationError
nil nil
end end
end.compact.uniq(&:name) end.uniq(&:name)
end end
def only_casks?(argv) def only_casks?(argv)

View File

@ -39,12 +39,12 @@ module Homebrew
puts HOMEBREW_PREFIX puts HOMEBREW_PREFIX
else else
formulae = args.named.to_resolved_formulae formulae = args.named.to_resolved_formulae
prefixes = formulae.map do |f| prefixes = formulae.filter_map do |f|
next nil if args.installed? && !f.opt_prefix.exist? next nil if args.installed? && !f.opt_prefix.exist?
# this case will be short-circuited by brew.sh logic for a single formula # this case will be short-circuited by brew.sh logic for a single formula
f.opt_prefix f.opt_prefix
end.compact end
puts prefixes puts prefixes
if args.installed? if args.installed?
missing_formulae = formulae.reject(&:optlinked?) missing_formulae = formulae.reject(&:optlinked?)

View File

@ -40,7 +40,7 @@ module Homebrew
} }
kegs = if args.HEAD? kegs = if args.HEAD?
args.named.to_kegs.group_by(&:name).map do |name, resolved_kegs| args.named.to_kegs.group_by(&:name).filter_map do |name, resolved_kegs|
head_keg = resolved_kegs.find { |keg| keg.version.head? } head_keg = resolved_kegs.find { |keg| keg.version.head? }
next head_keg if head_keg.present? next head_keg if head_keg.present?
@ -49,7 +49,7 @@ module Homebrew
To install, run: To install, run:
brew install --HEAD #{name} brew install --HEAD #{name}
EOS EOS
end.compact end
else else
args.named.to_latest_kegs args.named.to_latest_kegs
end end

View File

@ -28,7 +28,7 @@ module Homebrew
if Homebrew::EnvConfig.no_install_from_api? || (!tap.core_tap? && !tap.core_cask_tap?) if Homebrew::EnvConfig.no_install_from_api? || (!tap.core_tap? && !tap.core_cask_tap?)
installed_formula_names = T.let(nil, T.nilable(T::Set[String])) installed_formula_names = T.let(nil, T.nilable(T::Set[String]))
installed_tap_formulae = tap.formula_names.map do |formula_name| installed_tap_formulae = tap.formula_names.filter_map do |formula_name|
# initialise lazily in case there's no formulae in this tap # initialise lazily in case there's no formulae in this tap
installed_formula_names ||= Set.new(Formula.installed_formula_names) installed_formula_names ||= Set.new(Formula.installed_formula_names)
next unless installed_formula_names.include?(formula_name) next unless installed_formula_names.include?(formula_name)
@ -43,10 +43,10 @@ module Homebrew
# Can't use Formula#any_version_installed? because it doesn't consider # Can't use Formula#any_version_installed? because it doesn't consider
# taps correctly. # taps correctly.
formula if formula.installed_kegs.any? { |keg| keg.tab.tap == tap } formula if formula.installed_kegs.any? { |keg| keg.tab.tap == tap }
end.compact end
installed_cask_tokens = T.let(nil, T.nilable(T::Set[String])) installed_cask_tokens = T.let(nil, T.nilable(T::Set[String]))
installed_tap_casks = tap.cask_tokens.map do |cask_token| installed_tap_casks = tap.cask_tokens.filter_map do |cask_token|
# initialise lazily in case there's no casks in this tap # initialise lazily in case there's no casks in this tap
installed_cask_tokens ||= Set.new(Cask::Caskroom.tokens) installed_cask_tokens ||= Set.new(Cask::Caskroom.tokens)
next unless installed_cask_tokens.include?(cask_token) next unless installed_cask_tokens.include?(cask_token)
@ -59,7 +59,7 @@ module Homebrew
end end
cask if cask.installed? cask if cask.installed?
end.compact end
if installed_tap_formulae.present? || installed_tap_casks.present? if installed_tap_formulae.present? || installed_tap_casks.present?
installed_names = (installed_tap_formulae + installed_tap_casks.map(&:token)).join("\n") installed_names = (installed_tap_formulae + installed_tap_casks.map(&:token)).join("\n")

View File

@ -711,7 +711,7 @@ class Reporter
header_regex = /^(---|\+\+\+) / header_regex = /^(---|\+\+\+) /
add_delete_characters = ["+", "-"].freeze add_delete_characters = ["+", "-"].freeze
diff_output.lines.map do |line| diff_output.lines.filter_map do |line|
next if line.match?(header_regex) next if line.match?(header_regex)
next unless add_delete_characters.include?(line[0]) next unless add_delete_characters.include?(line[0])
@ -719,7 +719,7 @@ class Reporter
.sub(/^-/, "D #{api_dir_prefix.basename}/") .sub(/^-/, "D #{api_dir_prefix.basename}/")
.sub(/$/, ".rb") .sub(/$/, ".rb")
.chomp .chomp
end.compact.join("\n") end.join("\n")
else else
Utils.popen_read( Utils.popen_read(
"git", "-C", tap.path, "diff-tree", "-r", "--name-status", "--diff-filter=AMDR", "git", "-C", tap.path, "diff-tree", "-r", "--name-status", "--diff-filter=AMDR",
@ -845,9 +845,9 @@ class ReporterHub
end end
def dump_new_cask_report def dump_new_cask_report
casks = select_formula_or_cask(:AC).sort.map do |name| casks = select_formula_or_cask(:AC).sort.filter_map do |name|
name.split("/").last unless cask_installed?(name) name.split("/").last unless cask_installed?(name)
end.compact end
output_dump_formula_or_cask_report "New Casks", casks output_dump_formula_or_cask_report "New Casks", casks
end end
@ -873,13 +873,13 @@ class ReporterHub
end end
def dump_deleted_formula_report(report_all) def dump_deleted_formula_report(report_all)
formulae = select_formula_or_cask(:D).sort.map do |name| formulae = select_formula_or_cask(:D).sort.filter_map do |name|
if installed?(name) if installed?(name)
pretty_uninstalled(name) pretty_uninstalled(name)
elsif report_all elsif report_all
name name
end end
end.compact end
title = if report_all title = if report_all
"Deleted Formulae" "Deleted Formulae"
@ -890,14 +890,14 @@ class ReporterHub
end end
def dump_deleted_cask_report(report_all) def dump_deleted_cask_report(report_all)
casks = select_formula_or_cask(:DC).sort.map do |name| casks = select_formula_or_cask(:DC).sort.filter_map do |name|
name = name.split("/").last name = name.split("/").last
if cask_installed?(name) if cask_installed?(name)
pretty_uninstalled(name) pretty_uninstalled(name)
elsif report_all elsif report_all
name name
end end
end.compact end
title = if report_all title = if report_all
"Deleted Casks" "Deleted Casks"

View File

@ -182,11 +182,11 @@ module Commands
return if path.blank? return if path.blank?
if (cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path)) if (cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path))
cmd_parser.processed_options.map do |short, long, _, desc, hidden| cmd_parser.processed_options.filter_map do |short, long, _, desc, hidden|
next if hidden next if hidden
[long || short, desc] [long || short, desc]
end.compact end
else else
options = [] options = []
comment_lines = path.read.lines.grep(/^#:/) comment_lines = path.read.lines.grep(/^#:/)

View File

@ -200,14 +200,14 @@ module Homebrew
sig { params(commands: T::Array[String]).returns(String) } sig { params(commands: T::Array[String]).returns(String) }
def self.generate_bash_completion_file(commands) def self.generate_bash_completion_file(commands)
variables = Variables.new( variables = Variables.new(
completion_functions: commands.map do |command| completion_functions: commands.filter_map do |command|
generate_bash_subcommand_completion command generate_bash_subcommand_completion command
end.compact, end,
function_mappings: commands.map do |command| function_mappings: commands.filter_map do |command|
next unless command_gets_completions? command next unless command_gets_completions? command
"#{command}) _brew_#{Commands.method_name command} ;;" "#{command}) _brew_#{Commands.method_name command} ;;"
end.compact, end,
) )
ERB.new((TEMPLATE_DIR/"bash.erb").read, trim_mode: ">").result(variables.instance_eval { binding }) ERB.new((TEMPLATE_DIR/"bash.erb").read, trim_mode: ">").result(variables.instance_eval { binding })
@ -276,13 +276,13 @@ module Homebrew
sig { params(commands: T::Array[String]).returns(String) } sig { params(commands: T::Array[String]).returns(String) }
def self.generate_zsh_completion_file(commands) def self.generate_zsh_completion_file(commands)
variables = Variables.new( variables = Variables.new(
aliases: Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.map do |alias_command, command| aliases: Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.filter_map do |alias_cmd, command|
alias_command = "'#{alias_command}'" if alias_command.start_with? "-" alias_cmd = "'#{alias_cmd}'" if alias_cmd.start_with? "-"
command = "'#{command}'" if command.start_with? "-" command = "'#{command}'" if command.start_with? "-"
"#{alias_command} #{command}" "#{alias_cmd} #{command}"
end.compact, end,
builtin_command_descriptions: commands.map do |command| builtin_command_descriptions: commands.filter_map do |command|
next if Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.key? command next if Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.key? command
description = Commands.command_description(command, short: true) description = Commands.command_description(command, short: true)
@ -290,11 +290,11 @@ module Homebrew
description = format_description description description = format_description description
"'#{command}:#{description}'" "'#{command}:#{description}'"
end.compact, end,
completion_functions: commands.map do |command| completion_functions: commands.filter_map do |command|
generate_zsh_subcommand_completion command generate_zsh_subcommand_completion command
end.compact, end,
) )
ERB.new((TEMPLATE_DIR/"zsh.erb").read, trim_mode: ">").result(variables.instance_eval { binding }) ERB.new((TEMPLATE_DIR/"zsh.erb").read, trim_mode: ">").result(variables.instance_eval { binding })
@ -307,11 +307,11 @@ module Homebrew
command_description = format_description Commands.command_description(command, short: true), fish: true command_description = format_description Commands.command_description(command, short: true), fish: true
lines = ["__fish_brew_complete_cmd '#{command}' '#{command_description}'"] lines = ["__fish_brew_complete_cmd '#{command}' '#{command_description}'"]
options = command_options(command).sort.map do |opt, desc| options = command_options(command).sort.filter_map do |opt, desc|
arg_line = "__fish_brew_complete_arg '#{command}' -l #{opt.sub(/^-+/, "")}" arg_line = "__fish_brew_complete_arg '#{command}' -l #{opt.sub(/^-+/, "")}"
arg_line += " -d '#{format_description desc, fish: true}'" if desc.present? arg_line += " -d '#{format_description desc, fish: true}'" if desc.present?
arg_line arg_line
end.compact end
subcommands = [] subcommands = []
named_args = [] named_args = []
@ -350,9 +350,9 @@ module Homebrew
sig { params(commands: T::Array[String]).returns(String) } sig { params(commands: T::Array[String]).returns(String) }
def self.generate_fish_completion_file(commands) def self.generate_fish_completion_file(commands)
variables = Variables.new( variables = Variables.new(
completion_functions: commands.map do |command| completion_functions: commands.filter_map do |command|
generate_fish_subcommand_completion command generate_fish_subcommand_completion command
end.compact, end,
) )
ERB.new((TEMPLATE_DIR/"fish.erb").read, trim_mode: ">").result(variables.instance_eval { binding }) ERB.new((TEMPLATE_DIR/"fish.erb").read, trim_mode: ">").result(variables.instance_eval { binding })

View File

@ -199,7 +199,7 @@ module Homebrew
end end
def self.bottle_output(bottle, root_url_using) def self.bottle_output(bottle, root_url_using)
cellars = bottle.checksums.map do |checksum| cellars = bottle.checksums.filter_map do |checksum|
cellar = checksum["cellar"] cellar = checksum["cellar"]
next unless cellar_parameter_needed? cellar next unless cellar_parameter_needed? cellar
@ -209,7 +209,7 @@ module Homebrew
when Symbol when Symbol
":#{cellar}" ":#{cellar}"
end end
end.compact end
tag_column = cellars.empty? ? 0 : "cellar: #{cellars.max_by(&:length)}, ".length tag_column = cellars.empty? ? 0 : "cellar: #{cellars.max_by(&:length)}, ".length
tags = bottle.checksums.map { |checksum| checksum["tag"] } tags = bottle.checksums.map { |checksum| checksum["tag"] }

View File

@ -74,12 +74,12 @@ module Homebrew
results[username] = scan_repositories(repos, username, args, from: from) results[username] = scan_repositories(repos, username, args, from: from)
grand_totals[username] = total(results[username]) grand_totals[username] = total(results[username])
contributions = contribution_types.map do |type| contributions = contribution_types.filter_map do |type|
type_count = grand_totals[username][type] type_count = grand_totals[username][type]
next if type_count.to_i.zero? next if type_count.to_i.zero?
"#{Utils.pluralize("time", type_count, include_count: true)} (#{type})" "#{Utils.pluralize("time", type_count, include_count: true)} (#{type})"
end.compact end
contributions << "#{Utils.pluralize("time", grand_totals[username].values.sum, include_count: true)} (total)" contributions << "#{Utils.pluralize("time", grand_totals[username].values.sum, include_count: true)} (total)"
puts [ puts [

View File

@ -102,9 +102,9 @@ module Homebrew
odie "Could not find #{name}! The formula or version may not have existed." if test_formula.nil? odie "Could not find #{name}! The formula or version may not have existed." if test_formula.nil?
else else
# Search in the root directory of <repo> as well as recursively in all of its subdirectories # Search in the root directory of <repo> as well as recursively in all of its subdirectories
files = Dir[repo/"{,**/}"].map do |dir| files = Dir[repo/"{,**/}"].filter_map do |dir|
Pathname.glob("#{dir}/#{name}.rb").find(&:file?) Pathname.glob("#{dir}/#{name}.rb").find(&:file?)
end.compact end
if files.empty? if files.empty?
ohai "Searching repository history" ohai "Searching repository history"

View File

@ -37,7 +37,7 @@ module Homebrew
CacheStoreDatabase.use(:linkage) do |db| CacheStoreDatabase.use(:linkage) do |db|
kegs = if args.named.to_default_kegs.empty? kegs = if args.named.to_default_kegs.empty?
Formula.installed.map(&:any_installed_keg).compact Formula.installed.filter_map(&:any_installed_keg)
else else
args.named.to_default_kegs args.named.to_default_kegs
end end

View File

@ -329,7 +329,7 @@ module Homebrew
"-r", "--name-only", "--diff-filter=AM", "-r", "--name-only", "--diff-filter=AM",
original_commit, "HEAD", "--", tap.formula_dir) original_commit, "HEAD", "--", tap.formula_dir)
.lines .lines
.map do |line| .filter_map do |line|
next unless line.end_with? ".rb\n" next unless line.end_with? ".rb\n"
name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}" name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}"
@ -342,12 +342,12 @@ module Homebrew
rescue FormulaUnavailableError rescue FormulaUnavailableError
nil nil
end end
end.compact end
casks = Utils.popen_read("git", "-C", tap.path, "diff-tree", casks = Utils.popen_read("git", "-C", tap.path, "diff-tree",
"-r", "--name-only", "--diff-filter=AM", "-r", "--name-only", "--diff-filter=AM",
original_commit, "HEAD", "--", tap.cask_dir) original_commit, "HEAD", "--", tap.cask_dir)
.lines .lines
.map do |line| .filter_map do |line|
next unless line.end_with? ".rb\n" next unless line.end_with? ".rb\n"
name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}" name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}"
@ -356,7 +356,7 @@ module Homebrew
rescue Cask::CaskUnavailableError rescue Cask::CaskUnavailableError
nil nil
end end
end.compact end
formulae + casks formulae + casks
end end

View File

@ -70,11 +70,11 @@ module Homebrew
# release notes without usernames, new contributors, or extra lines # release notes without usernames, new contributors, or extra lines
blog_post_notes = GitHub.generate_release_notes("Homebrew", "brew", new_version, blog_post_notes = GitHub.generate_release_notes("Homebrew", "brew", new_version,
previous_tag: latest_major_minor_version)["body"] previous_tag: latest_major_minor_version)["body"]
blog_post_notes = blog_post_notes.lines.map do |line| blog_post_notes = blog_post_notes.lines.filter_map do |line|
next unless (match = line.match(/^\* (.*) by @[\w-]+ in (.*)$/)) next unless (match = line.match(/^\* (.*) by @[\w-]+ in (.*)$/))
"- [#{match[1]}](#{match[2]})" "- [#{match[1]}](#{match[2]})"
end.compact.sort end.sort
puts blog_post_notes puts blog_post_notes
end end

View File

@ -77,7 +77,7 @@ module Homebrew
raise UsageError, "No files have been changed from the master branch!" if changed_files.blank? raise UsageError, "No files have been changed from the master branch!" if changed_files.blank?
filestub_regex = %r{Library/Homebrew/([\w/-]+).rb} filestub_regex = %r{Library/Homebrew/([\w/-]+).rb}
changed_files.scan(filestub_regex).map(&:last).map do |filestub| changed_files.scan(filestub_regex).map(&:last).filter_map do |filestub|
if filestub.start_with?("test/") if filestub.start_with?("test/")
# Only run tests on *_spec.rb files in test/ folder # Only run tests on *_spec.rb files in test/ folder
filestub.end_with?("_spec") ? Pathname("#{filestub}.rb") : nil filestub.end_with?("_spec") ? Pathname("#{filestub}.rb") : nil
@ -85,7 +85,7 @@ module Homebrew
# For all other changed .rb files guess the associated test file name # For all other changed .rb files guess the associated test file name
Pathname("test/#{filestub}_spec.rb") Pathname("test/#{filestub}_spec.rb")
end end
end.compact.select(&:exist?) end.select(&:exist?)
end end
def self.tests def self.tests

View File

@ -133,7 +133,7 @@ module Homebrew
"`HOMEBREW_NO_GITHUB_API` and `HOMEBREW_NO_ANALYTICS` to be unset" "`HOMEBREW_NO_GITHUB_API` and `HOMEBREW_NO_ANALYTICS` to be unset"
end end
formulae = analytics["items"].map do |i| formulae = analytics["items"].filter_map do |i|
f = i["formula"].split.first f = i["formula"].split.first
next if f.include?("/") next if f.include?("/")
next if formula_installs[f].present? next if formula_installs[f].present?
@ -144,7 +144,7 @@ module Homebrew
rescue FormulaUnavailableError rescue FormulaUnavailableError
nil nil
end end
end.compact end
@sort = " (sorted by installs in the last 90 days; top 10,000 only)" @sort = " (sorted by installs in the last 90 days; top 10,000 only)"
all_formulae = Formula.all(eval_all: args.eval_all?) all_formulae = Formula.all(eval_all: args.eval_all?)

View File

@ -545,11 +545,11 @@ module Homebrew
return if ENV["CI"] return if ENV["CI"]
return unless Utils::Git.available? return unless Utils::Git.available?
commands = Tap.select(&:installed?).map do |tap| commands = Tap.select(&:installed?).filter_map do |tap|
next if tap.git_repo.default_origin_branch? next if tap.git_repo.default_origin_branch?
"git -C $(brew --repo #{tap.name}) checkout #{tap.git_repo.origin_branch_name}" "git -C $(brew --repo #{tap.name}) checkout #{tap.git_repo.origin_branch_name}"
end.compact end
return if commands.blank? return if commands.blank?
@ -833,7 +833,7 @@ module Homebrew
def check_deleted_formula def check_deleted_formula
kegs = Keg.all kegs = Keg.all
deleted_formulae = kegs.map do |keg| deleted_formulae = kegs.filter_map do |keg|
tap = Tab.for_keg(keg).tap tap = Tab.for_keg(keg).tap
loadable = [ loadable = [
@ -858,7 +858,7 @@ module Homebrew
end end
keg.name unless loadable keg.name unless loadable
end.compact.uniq end.uniq
return if deleted_formulae.blank? return if deleted_formulae.blank?

View File

@ -354,9 +354,9 @@ class AbstractFileDownloadStrategy < AbstractDownloadStrategy
end end
if (uri_path = uri.path.presence) if (uri_path = uri.path.presence)
components[:path] = uri_path.split("/").map do |part| components[:path] = uri_path.split("/").filter_map do |part|
URI::DEFAULT_PARSER.unescape(part).presence URI::DEFAULT_PARSER.unescape(part).presence
end.compact end
end end
if search_query && (uri_query = uri.query.presence) if search_query && (uri_query = uri.query.presence)

View File

@ -267,7 +267,7 @@ module Kernel
end end
def which_all(cmd, path = ENV.fetch("PATH")) def which_all(cmd, path = ENV.fetch("PATH"))
PATH.new(path).map do |p| PATH.new(path).filter_map do |p|
begin begin
pcmd = File.expand_path(cmd, p) pcmd = File.expand_path(cmd, p)
rescue ArgumentError rescue ArgumentError
@ -276,7 +276,7 @@ module Kernel
next next
end end
Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd) Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end.compact.uniq end.uniq
end end
def which_editor(silent: false) def which_editor(silent: false)

View File

@ -25,12 +25,12 @@ module Superenv
def homebrew_extra_paths def homebrew_extra_paths
paths = generic_homebrew_extra_paths paths = generic_homebrew_extra_paths
paths += %w[binutils make].map do |f| paths += %w[binutils make].filter_map do |f|
bin = Formulary.factory(f).opt_bin bin = Formulary.factory(f).opt_bin
bin if bin.directory? bin if bin.directory?
rescue FormulaUnavailableError rescue FormulaUnavailableError
nil nil
end.compact end
paths paths
end end

View File

@ -36,8 +36,7 @@ module UnpackStrategy
volumes = result.stderr.chomp volumes = result.stderr.chomp
.split("\n") .split("\n")
.map { |l| l[/\A skipping: (.+) volume label\Z/, 1] } .filter_map { |l| l[/\A skipping: (.+) volume label\Z/, 1] }
.compact
return if volumes.empty? return if volumes.empty?

View File

@ -518,11 +518,11 @@ class Formula
# Returns any `@`-versioned Formula objects for any Formula (including versioned formulae). # Returns any `@`-versioned Formula objects for any Formula (including versioned formulae).
sig { returns(T::Array[Formula]) } sig { returns(T::Array[Formula]) }
def versioned_formulae def versioned_formulae
versioned_formulae_names.map do |name| versioned_formulae_names.filter_map do |name|
Formula[name] Formula[name]
rescue FormulaUnavailableError rescue FormulaUnavailableError
nil nil
end.compact.sort_by(&:version).reverse end.sort_by(&:version).reverse
end end
# A named {Resource} for the currently active {SoftwareSpec}. # A named {Resource} for the currently active {SoftwareSpec}.
@ -631,10 +631,10 @@ class Formula
end end
def latest_head_version def latest_head_version
head_versions = installed_prefixes.map do |pn| head_versions = installed_prefixes.filter_map do |pn|
pn_pkgversion = PkgVersion.parse(pn.basename.to_s) pn_pkgversion = PkgVersion.parse(pn.basename.to_s)
pn_pkgversion if pn_pkgversion.head? pn_pkgversion if pn_pkgversion.head?
end.compact end
head_versions.max_by do |pn_pkgversion| head_versions.max_by do |pn_pkgversion|
[Tab.for_keg(prefix(pn_pkgversion)).source_modified_time, pn_pkgversion.revision] [Tab.for_keg(prefix(pn_pkgversion)).source_modified_time, pn_pkgversion.revision]
@ -1934,7 +1934,7 @@ class Formula
raise ArgumentError, "Formula#all without `--eval-all` or HOMEBREW_EVAL_ALL" raise ArgumentError, "Formula#all without `--eval-all` or HOMEBREW_EVAL_ALL"
end end
(core_names + tap_files).map do |name_or_file| (core_names + tap_files).filter_map do |name_or_file|
Formulary.factory(name_or_file) Formulary.factory(name_or_file)
rescue FormulaUnavailableError, FormulaUnreadableError => e rescue FormulaUnavailableError, FormulaUnreadableError => e
# Don't let one broken formula break commands. But do complain. # Don't let one broken formula break commands. But do complain.
@ -1942,7 +1942,7 @@ class Formula
$stderr.puts e $stderr.puts e
nil nil
end.compact end
end end
# An array of all racks currently installed. # An array of all racks currently installed.
@ -2108,12 +2108,12 @@ class Formula
def runtime_dependencies(read_from_tab: true, undeclared: true) def runtime_dependencies(read_from_tab: true, undeclared: true)
deps = if read_from_tab && undeclared && deps = if read_from_tab && undeclared &&
(tab_deps = any_installed_keg&.runtime_dependencies) (tab_deps = any_installed_keg&.runtime_dependencies)
tab_deps.map do |d| tab_deps.filter_map do |d|
full_name = d["full_name"] full_name = d["full_name"]
next unless full_name next unless full_name
Dependency.new full_name Dependency.new full_name
end.compact end
end end
begin begin
deps ||= declared_runtime_dependencies unless undeclared deps ||= declared_runtime_dependencies unless undeclared
@ -2134,11 +2134,11 @@ class Formula
Formula.cache[:runtime_formula_dependencies][cache_key] ||= runtime_dependencies( Formula.cache[:runtime_formula_dependencies][cache_key] ||= runtime_dependencies(
read_from_tab: read_from_tab, read_from_tab: read_from_tab,
undeclared: undeclared, undeclared: undeclared,
).map do |d| ).filter_map do |d|
d.to_formula d.to_formula
rescue FormulaUnavailableError rescue FormulaUnavailableError
nil nil
end.compact end
end end
def runtime_installed_formula_dependents def runtime_installed_formula_dependents
@ -2192,7 +2192,7 @@ class Formula
{ {
dependable: dependable, dependable: dependable,
# Now find the list of specs each dependency was a part of. # Now find the list of specs each dependency was a part of.
specs: dependables.map { |spec, spec_deps| spec if spec_deps&.include?(dependable) }.compact, specs: dependables.filter_map { |spec, spec_deps| spec if spec_deps&.include?(dependable) },
} }
end end
end end

View File

@ -33,7 +33,7 @@ module Homebrew
@problems = [] @problems = []
@new_formula_problems = [] @new_formula_problems = []
@text = FormulaTextAuditor.new(formula.path) @text = FormulaTextAuditor.new(formula.path)
@specs = %w[stable head].map { |s| formula.send(s) }.compact @specs = %w[stable head].filter_map { |s| formula.send(s) }
@spdx_license_data = options[:spdx_license_data] @spdx_license_data = options[:spdx_license_data]
@spdx_exception_data = options[:spdx_exception_data] @spdx_exception_data = options[:spdx_exception_data]
@tap_audit = options[:tap_audit] @tap_audit = options[:tap_audit]

View File

@ -188,20 +188,19 @@ module FormulaCellarChecks
.select(&:directory?) .select(&:directory?)
.map(&:basename) .map(&:basename)
pythons = lib_subdirs.map do |p| pythons = lib_subdirs.filter_map do |p|
match = p.to_s.match(/^python(\d+\.\d+)$/) match = p.to_s.match(/^python(\d+\.\d+)$/)
next if match.blank? next if match.blank?
next if match.captures.blank? next if match.captures.blank?
match.captures.first match.captures.first
end.compact end
return if pythons.blank? return if pythons.blank?
python_deps = deps.map(&:name) python_deps = deps.map(&:name)
.grep(/^python(@.*)?$/) .grep(/^python(@.*)?$/)
.map { |d| Formula[d].version.to_s[/^\d+\.\d+/] } .filter_map { |d| Formula[d].version.to_s[/^\d+\.\d+/] }
.compact
return if python_deps.blank? return if python_deps.blank?
return if pythons.any? { |v| python_deps.include? v } return if pythons.any? { |v| python_deps.include? v }

View File

@ -779,9 +779,7 @@ module Formulary
name = ref name = ref
loaders = Tap.map { |tap| super("#{tap}/#{name}", warn: warn) } loaders = Tap.filter_map { |tap| super("#{tap}/#{name}", warn: warn) }.select { _1.path.exist? }
.compact
.select { _1.path.exist? }
case loaders.count case loaders.count
when 1 when 1

View File

@ -132,11 +132,11 @@ require "cli/args"
require "PATH" require "PATH"
ENV["HOMEBREW_PATH"] ||= ENV.fetch("PATH") ENV["HOMEBREW_PATH"] ||= ENV.fetch("PATH")
ORIGINAL_PATHS = PATH.new(ENV.fetch("HOMEBREW_PATH")).map do |p| ORIGINAL_PATHS = PATH.new(ENV.fetch("HOMEBREW_PATH")).filter_map do |p|
Pathname.new(p).expand_path Pathname.new(p).expand_path
rescue rescue
nil nil
end.compact.freeze end.freeze
require "exceptions" require "exceptions"
require "utils" require "utils"

View File

@ -244,7 +244,7 @@ module Homebrew
dry_run: false, dry_run: false,
skip_post_install: false skip_post_install: false
) )
formula_installers = formulae_to_install.map do |formula| formula_installers = formulae_to_install.filter_map do |formula|
Migrator.migrate_if_needed(formula, force: force, dry_run: dry_run) Migrator.migrate_if_needed(formula, force: force, dry_run: dry_run)
build_options = formula.build build_options = formula.build
@ -284,7 +284,7 @@ module Homebrew
ofail "#{formula}: #{e}" ofail "#{formula}: #{e}"
nil nil
end end
end.compact end
if dry_run if dry_run
if (formulae_name_to_install = formulae_to_install.map(&:name)) if (formulae_name_to_install = formulae_to_install.map(&:name))

View File

@ -52,12 +52,12 @@ module InstalledDependents
CaskDependent.new(dependent).runtime_dependencies.map(&:to_formula) CaskDependent.new(dependent).runtime_dependencies.map(&:to_formula)
end end
required_kegs = required.map do |f| required_kegs = required.filter_map do |f|
f_kegs = kegs_by_source[[f.name, f.tap]] f_kegs = kegs_by_source[[f.name, f.tap]]
next unless f_kegs next unless f_kegs
f_kegs.max_by(&:version) f_kegs.max_by(&:version)
end.compact end
next if required_kegs.empty? next if required_kegs.empty?

View File

@ -158,7 +158,7 @@ module Language
# Find any Python bindings provided by recursive dependencies # Find any Python bindings provided by recursive dependencies
formula_deps = formula.recursive_dependencies formula_deps = formula.recursive_dependencies
pth_contents = formula_deps.map do |d| pth_contents = formula_deps.filter_map do |d|
next if d.build? || d.test? next if d.build? || d.test?
# Do not add the main site-package provided by the brewed # Do not add the main site-package provided by the brewed
# Python formula, to keep the virtual-env's site-package pristine # Python formula, to keep the virtual-env's site-package pristine
@ -168,7 +168,7 @@ module Language
next unless dep_site_packages.exist? next unless dep_site_packages.exist?
"import site; site.addsitedir('#{dep_site_packages}')\n" "import site; site.addsitedir('#{dep_site_packages}')\n"
end.compact end
unless pth_contents.empty? unless pth_contents.empty?
(venv_root/Language::Python.site_packages(python)/"homebrew_deps.pth").write pth_contents.join (venv_root/Language::Python.site_packages(python)/"homebrew_deps.pth").write pth_contents.join
end end

View File

@ -83,7 +83,7 @@ module Homebrew
other_taps.each_value do |tap| other_taps.each_value do |tap|
tap_strategy_path = "#{tap.path}/livecheck/strategy" tap_strategy_path = "#{tap.path}/livecheck/strategy"
Dir["#{tap_strategy_path}/*.rb"].sort.each { require(_1) } if Dir.exist?(tap_strategy_path) Dir["#{tap_strategy_path}/*.rb"].each { require(_1) } if Dir.exist?(tap_strategy_path)
end end
end end

View File

@ -69,9 +69,9 @@ module Homebrew
return Strategy.handle_block_return(block_return_value) return Strategy.handle_block_return(block_return_value)
end end
items.map do |_key, item| items.filter_map do |_key, item|
item.bundle_version.nice_version item.bundle_version.nice_version
end.compact.uniq end.uniq
end end
# Uses {UnversionedCaskChecker} on the provided cask to identify # Uses {UnversionedCaskChecker} on the provided cask to identify

View File

@ -101,7 +101,7 @@ module Homebrew
return Strategy.handle_block_return(block_return_value) return Strategy.handle_block_return(block_return_value)
end end
tags.map do |tag| tags.filter_map do |tag|
if regex if regex
# Use the first capture group (the version) # Use the first capture group (the version)
# This code is not typesafe unless the regex includes a capture group # This code is not typesafe unless the regex includes a capture group
@ -111,7 +111,7 @@ module Homebrew
# version text # version text
tag[DEFAULT_REGEX, 1] tag[DEFAULT_REGEX, 1]
end end
end.compact.uniq end.uniq
end end
# Checks the Git tags for new versions. When a regex isn't provided, # Checks the Git tags for new versions. When a regex isn't provided,

View File

@ -105,7 +105,7 @@ module Homebrew
end end
content = [content] unless content.is_a?(Array) content = [content] unless content.is_a?(Array)
content.compact_blank.map do |release| content.compact_blank.filter_map do |release|
next if release["draft"] || release["prerelease"] next if release["draft"] || release["prerelease"]
value = T.let(nil, T.untyped) value = T.let(nil, T.untyped)
@ -116,7 +116,7 @@ module Homebrew
value = match[1] value = match[1]
end end
value value
end.compact.uniq end.uniq
end end
# Generates the GitHub API URL for the repository's recent releases # Generates the GitHub API URL for the repository's recent releases

View File

@ -51,7 +51,7 @@ module Homebrew
return Strategy.handle_block_return(block_return_value) return Strategy.handle_block_return(block_return_value)
end end
DEFAULT_HEADERS_TO_CHECK.map do |header_name| DEFAULT_HEADERS_TO_CHECK.filter_map do |header_name|
header_value = headers[header_name] header_value = headers[header_name]
next if header_value.blank? next if header_value.blank?
@ -61,7 +61,7 @@ module Homebrew
v = Version.parse(header_value, detected_from_url: true) v = Version.parse(header_value, detected_from_url: true)
v.null? ? nil : v.to_s v.null? ? nil : v.to_s
end end
end.compact.uniq end.uniq
end end
# Checks the final URL for new versions after following all redirections, # Checks the final URL for new versions after following all redirections,

View File

@ -60,14 +60,14 @@ module Homebrew
return [] if regex.blank? return [] if regex.blank?
content.scan(regex).map do |match| content.scan(regex).filter_map do |match|
case match case match
when String when String
match match
when Array when Array
match.first match.first
end end
end.compact.uniq end.uniq
end end
# Checks the content at the URL for new versions, using the provided # Checks the content at the URL for new versions, using the provided

View File

@ -85,7 +85,7 @@ module Homebrew
end end
end end
xml.get_elements("//rss//channel//item").map do |item| xml.get_elements("//rss//channel//item").filter_map do |item|
enclosure = item.elements["enclosure"] enclosure = item.elements["enclosure"]
if enclosure if enclosure
@ -144,7 +144,7 @@ module Homebrew
data[:pub_date] ||= Time.new(0) data[:pub_date] ||= Time.new(0)
Item.new(**data) Item.new(**data)
end.compact end
end end
# Filters out items that aren't suitable for Homebrew. # Filters out items that aren't suitable for Homebrew.

View File

@ -140,7 +140,7 @@ module Homebrew
def self.cmd_parser_manpage_lines(cmd_parser) def self.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, hidden| lines += cmd_parser.processed_options.filter_map do |short, long, _, desc, hidden|
next if hidden next if hidden
if long.present? if long.present?
@ -151,7 +151,7 @@ module Homebrew
end end
generate_option_doc(short, long, desc) generate_option_doc(short, long, desc)
end.compact end
lines lines
end end

View File

@ -134,12 +134,12 @@ module ELFShim
ldd_output = Utils.popen_read(ldd, path.expand_path.to_s).split("\n") ldd_output = Utils.popen_read(ldd, path.expand_path.to_s).split("\n")
return unless $CHILD_STATUS.success? return unless $CHILD_STATUS.success?
ldd_paths = ldd_output.map do |line| ldd_paths = ldd_output.filter_map do |line|
match = line.match(/\t.+ => (.+) \(.+\)|\t(.+) => not found/) match = line.match(/\t.+ => (.+) \(.+\)|\t(.+) => not found/)
next unless match next unless match
match.captures.compact.first match.captures.compact.first
end.compact end
@dylibs = ldd_paths.select do |ldd_path| @dylibs = ldd_paths.select do |ldd_path|
needed.include? File.basename(ldd_path) needed.include? File.basename(ldd_path)
end end

View File

@ -36,11 +36,11 @@ module RuboCop
def sort_array(source) def sort_array(source)
# Combine each comment with the line(s) below so that they remain in the same relative location # Combine each comment with the line(s) below so that they remain in the same relative location
combined_source = source.each_with_index.map do |line, index| combined_source = source.each_with_index.filter_map do |line, index|
next if line.strip.start_with?("#") next if line.strip.start_with?("#")
next recursively_find_comments(source, index, line) next recursively_find_comments(source, index, line)
end.compact end
# Separate the lines into those that should be sorted and those that should not # Separate the lines into those that should be sorted and those that should not
# ie. skip the opening and closing brackets of the array # ie. skip the opening and closing brackets of the array

View File

@ -89,13 +89,13 @@ module RuboCop
method_name = on_system_block.method_name method_name = on_system_block.method_name
child_nodes = on_system_body.begin_type? ? on_system_body.child_nodes : [on_system_body] child_nodes = on_system_body.begin_type? ? on_system_body.child_nodes : [on_system_body]
if child_nodes.all? { |n| n.send_type? || n.block_type? || n.lvasgn_type? } if child_nodes.all? { |n| n.send_type? || n.block_type? || n.lvasgn_type? }
method_names = child_nodes.map do |node| method_names = child_nodes.filter_map do |node|
next if node.lvasgn_type? next if node.lvasgn_type?
next if node.method_name == :patch next if node.method_name == :patch
next if on_system_methods.include? node.method_name next if on_system_methods.include? node.method_name
node.method_name node.method_name
end.compact end
next if method_names.empty? || allowed_methods.include?(method_names) next if method_names.empty? || allowed_methods.include?(method_names)
end end
offending_node(on_system_block) offending_node(on_system_block)

View File

@ -53,7 +53,7 @@ module Homebrew
results = search(Formula.full_names + aliases, string_or_regex).sort results = search(Formula.full_names + aliases, string_or_regex).sort
results |= Formula.fuzzy_search(string_or_regex).map { |n| Formulary.factory(n).full_name } results |= Formula.fuzzy_search(string_or_regex).map { |n| Formulary.factory(n).full_name }
results.map do |name| results.filter_map do |name|
formula, canonical_full_name = begin formula, canonical_full_name = begin
f = Formulary.factory(name) f = Formulary.factory(name)
[f, f.full_name] [f, f.full_name]
@ -69,7 +69,7 @@ module Homebrew
elsif formula.nil? || formula.valid_platform? elsif formula.nil? || formula.valid_platform?
name name
end end
end.compact end
end end
def self.search_casks(string_or_regex) def self.search_casks(string_or_regex)
@ -81,11 +81,11 @@ module Homebrew
end end
end end
cask_tokens = Tap.flat_map(&:cask_tokens).map do |c| cask_tokens = Tap.flat_map(&:cask_tokens).filter_map do |c|
next if c.start_with?("homebrew/cask/") && !Homebrew::EnvConfig.no_install_from_api? next if c.start_with?("homebrew/cask/") && !Homebrew::EnvConfig.no_install_from_api?
c.sub(%r{^homebrew/cask.*/}, "") c.sub(%r{^homebrew/cask.*/}, "")
end.compact end
cask_tokens |= Homebrew::API::Cask.all_casks.keys unless Homebrew::EnvConfig.no_install_from_api? cask_tokens |= Homebrew::API::Cask.all_casks.keys unless Homebrew::EnvConfig.no_install_from_api?
results = search(cask_tokens, string_or_regex) results = search(cask_tokens, string_or_regex)

View File

@ -228,13 +228,13 @@ class SoftwareSpec
def recursive_dependencies def recursive_dependencies
deps_f = [] deps_f = []
recursive_dependencies = deps.map do |dep| recursive_dependencies = deps.filter_map do |dep|
deps_f << dep.to_formula deps_f << dep.to_formula
dep dep
rescue TapFormulaUnavailableError rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap dependencies # Don't complain about missing cross-tap dependencies
next next
end.compact.uniq end.uniq
deps_f.compact.each do |f| deps_f.compact.each do |f|
f.recursive_dependencies.each do |dep| f.recursive_dependencies.each do |dep|
recursive_dependencies << dep unless recursive_dependencies.include?(dep) recursive_dependencies << dep unless recursive_dependencies.include?(dep)
@ -437,7 +437,7 @@ class Bottle
manifests = json["manifests"] manifests = json["manifests"]
raise ArgumentError, "Missing 'manifests' section." if manifests.blank? raise ArgumentError, "Missing 'manifests' section." if manifests.blank?
manifests_annotations = manifests.map { |m| m["annotations"] }.compact manifests_annotations = manifests.filter_map { |m| m["annotations"] }
raise ArgumentError, "Missing 'annotations' section." if manifests_annotations.blank? raise ArgumentError, "Missing 'annotations' section." if manifests_annotations.blank?
bottle_digest = @resource.checksum.hexdigest bottle_digest = @resource.checksum.hexdigest

View File

@ -64,7 +64,7 @@ RSpec.describe Homebrew::Diagnostic::Checks do
homebrew_path = homebrew_path =
"#{HOMEBREW_PREFIX}/bin#{File::PATH_SEPARATOR}" + "#{HOMEBREW_PREFIX}/bin#{File::PATH_SEPARATOR}" +
ENV["HOMEBREW_PATH"].gsub(/(?:^|#{Regexp.escape(File::PATH_SEPARATOR)})#{Regexp.escape(sbin)}/, "") ENV["HOMEBREW_PATH"].gsub(/(?:^|#{Regexp.escape(File::PATH_SEPARATOR)})#{Regexp.escape(sbin)}/, "")
stub_const("ORIGINAL_PATHS", PATH.new(homebrew_path).map { |path| Pathname.new(path).expand_path }.compact) stub_const("ORIGINAL_PATHS", PATH.new(homebrew_path).filter_map { |path| Pathname.new(path).expand_path })
expect(checks.check_user_path_1).to be_nil expect(checks.check_user_path_1).to be_nil
expect(checks.check_user_path_2).to be_nil expect(checks.check_user_path_2).to be_nil

View File

@ -8,8 +8,7 @@ module Homebrew
formula.versioned_formulae formula.versioned_formulae
.select(&:keg_only?) .select(&:keg_only?)
.select(&:linked?) .select(&:linked?)
.map(&:any_installed_keg) .filter_map(&:any_installed_keg)
.compact
.select(&:directory?) .select(&:directory?)
.each do |keg| .each do |keg|
unlink(keg, verbose: verbose) unlink(keg, verbose: verbose)

View File

@ -98,8 +98,7 @@ module UnpackStrategy
# For APFS, find the <physical-store> corresponding to <mount-path> # For APFS, find the <physical-store> corresponding to <mount-path>
eject_paths = disk_info.plist eject_paths = disk_info.plist
.fetch("APFSPhysicalStores", []) .fetch("APFSPhysicalStores", [])
.map { |store| store["APFSPhysicalStore"] } .filter_map { |store| store["APFSPhysicalStore"] }
.compact
.presence || [path] .presence || [path]
eject_paths.each do |eject_path| eject_paths.each do |eject_path|
@ -230,8 +229,7 @@ module UnpackStrategy
mounts = if plist.respond_to?(:fetch) mounts = if plist.respond_to?(:fetch)
plist.fetch("system-entities", []) plist.fetch("system-entities", [])
.map { |entity| entity["mount-point"] } .filter_map { |entity| entity["mount-point"] }
.compact
.map { |path| Mount.new(path) } .map { |path| Mount.new(path) }
else else
[] []

View File

@ -222,8 +222,8 @@ module Homebrew
top_level_info_plist_paths = top_level_info_plists(Pathname.glob(extract_dir/"**/Contents/Info.plist")) top_level_info_plist_paths = top_level_info_plists(Pathname.glob(extract_dir/"**/Contents/Info.plist"))
unique_info_plist_versions = unique_info_plist_versions =
top_level_info_plist_paths.map { |i| BundleVersion.from_info_plist(i)&.nice_version } top_level_info_plist_paths.filter_map { |i| BundleVersion.from_info_plist(i)&.nice_version }
.compact.uniq .uniq
return unique_info_plist_versions.first if unique_info_plist_versions.count == 1 return unique_info_plist_versions.first if unique_info_plist_versions.count == 1
package_info_path = extract_dir/"PackageInfo" package_info_path = extract_dir/"PackageInfo"

View File

@ -52,7 +52,7 @@ module Homebrew
raise CyclicDependencyError, dependency_graph.strongly_connected_components if Homebrew::EnvConfig.developer? raise CyclicDependencyError, dependency_graph.strongly_connected_components if Homebrew::EnvConfig.developer?
end end
formula_installers = formulae_to_install.map do |formula| formula_installers = formulae_to_install.filter_map do |formula|
Migrator.migrate_if_needed(formula, force: force, dry_run: dry_run) Migrator.migrate_if_needed(formula, force: force, dry_run: dry_run)
begin begin
fi = create_formula_installer( fi = create_formula_installer(
@ -114,7 +114,7 @@ module Homebrew
ofail "#{formula}: #{e}" ofail "#{formula}: #{e}"
nil nil
end end
end.compact end
formula_installers.each do |fi| formula_installers.each do |fi|
upgrade_formula(fi, dry_run: dry_run, verbose: verbose) upgrade_formula(fi, dry_run: dry_run, verbose: verbose)

View File

@ -65,7 +65,7 @@ module Homebrew
time = Time.now time = Time.now
begin begin
method.bind(self).call(*args, &block) method.bind_call(self, *args, &block)
ensure ensure
$times[name] ||= 0 $times[name] ||= 0
$times[name] += Time.now - time $times[name] += Time.now - time

View File

@ -211,7 +211,7 @@ module GitHub
reviews = result["repository"]["pullRequest"]["reviews"]["nodes"] reviews = result["repository"]["pullRequest"]["reviews"]["nodes"]
valid_associations = %w[MEMBER OWNER] valid_associations = %w[MEMBER OWNER]
reviews.map do |r| reviews.filter_map do |r|
next if commit.present? && commit != r["commit"]["oid"] next if commit.present? && commit != r["commit"]["oid"]
next unless valid_associations.include? r["authorAssociation"] next unless valid_associations.include? r["authorAssociation"]
@ -226,7 +226,7 @@ module GitHub
"name" => name, "name" => name,
"login" => r["author"]["login"], "login" => r["author"]["login"],
} }
end.compact end
end end
def self.dispatch_event(user, repo, event, **payload) def self.dispatch_event(user, repo, event, **payload)

View File

@ -392,11 +392,11 @@ module PyPI
def self.pip_report_to_packages(report) def self.pip_report_to_packages(report)
return [] if report.blank? return [] if report.blank?
report["install"].map do |package| report["install"].filter_map do |package|
name = normalize_python_package(package["metadata"]["name"]) name = normalize_python_package(package["metadata"]["name"])
version = package["metadata"]["version"] version = package["metadata"]["version"]
Package.new "#{name}==#{version}" Package.new "#{name}==#{version}"
end.compact end
end end
end end

View File

@ -44,14 +44,14 @@ module SPDX
licenses.push license_expression licenses.push license_expression
when Hash, Array when Hash, Array
if license_expression.is_a? Hash if license_expression.is_a? Hash
license_expression = license_expression.map do |key, value| license_expression = license_expression.filter_map do |key, value|
if key.is_a? String if key.is_a? String
licenses.push key licenses.push key
exceptions.push value[:with] exceptions.push value[:with]
next next
end end
value value
end.compact end
end end
license_expression.each do |license| license_expression.each do |license|

View File

@ -33,8 +33,7 @@ module Utils
.reject(&:test?) .reject(&:test?)
.map(&:to_formula) .map(&:to_formula)
cask_deps = cask_or_formula.requirements cask_deps = cask_or_formula.requirements
.map(&:cask) .filter_map(&:cask)
.compact
.map { |c| Cask::CaskLoader.load(c, config: nil) } .map { |c| Cask::CaskLoader.load(c, config: nil) }
end end