Merge pull request #4797 from MikeMcQuaid/rubocop-tweaks

.rubocop: tweak rules.
This commit is contained in:
Mike McQuaid 2018-09-02 21:13:23 +01:00 committed by GitHub
commit 3b91c5f1ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 266 additions and 236 deletions

View File

@ -7,12 +7,15 @@ AllCops:
require: ./Homebrew/rubocops.rb require: ./Homebrew/rubocops.rb
# enable all formulae audits
FormulaAudit: FormulaAudit:
Enabled: true Enabled: true
# enable all formulae strict audits
FormulaAuditStrict: FormulaAuditStrict:
Enabled: true Enabled: true
# disable all formulae strict audits by default
NewFormulaAudit: NewFormulaAudit:
Enabled: false Enabled: false
@ -20,18 +23,19 @@ NewFormulaAudit:
Layout/AlignParameters: Layout/AlignParameters:
Enabled: false Enabled: false
# favour parens-less DSL-style arguments
Lint/AmbiguousOperator:
Enabled: false
# this is a bit less "floaty"
Layout/CaseIndentation: Layout/CaseIndentation:
EnforcedStyle: end EnforcedStyle: end
Layout/EmptyLineBetweenDefs: # this is a bit less "floaty"
AllowAdjacentOneLineDefs: true
Layout/EndAlignment: Layout/EndAlignment:
EnforcedStyleAlignWith: variable EnforcedStyleAlignWith: start_of_line
Layout/IndentArray:
EnforcedStyle: special_inside_parentheses
# enforce use of <<~EOS
Layout/IndentHeredoc: Layout/IndentHeredoc:
EnforcedStyle: squiggly EnforcedStyle: squiggly
@ -39,22 +43,29 @@ Layout/IndentHeredoc:
Layout/SpaceAroundOperators: Layout/SpaceAroundOperators:
Enabled: false Enabled: false
# favor parens-less DSL-style arguments # use spaces for indentation; detect tabs
Lint/AmbiguousOperator: Layout/Tab:
Enabled: false Enabled: true
# so many of these in formulae and can't be autocorrected # favour parens-less DSL-style arguments
Lint/AmbiguousRegexpLiteral:
Enabled: false
# favor parens-less DSL-style arguments
Lint/AmbiguousBlockAssociation: Lint/AmbiguousBlockAssociation:
Enabled: false Enabled: false
# so many of these in formulae and can't be autocorrected
# TODO: fix these as `ruby -w` complains about them.
Lint/AmbiguousRegexpLiteral:
Enabled: false
# assignment in conditions are useful sometimes # assignment in conditions are useful sometimes
# TODO: add parentheses for these and remove
Lint/AssignmentInCondition: Lint/AssignmentInCondition:
Enabled: false Enabled: false
# we output how to use interpolated strings too often
Lint/InterpolationCheck:
Enabled: false
# so many of these in formulae and can't be autocorrected # so many of these in formulae and can't be autocorrected
Lint/ParenthesesAsGroupedExpression: Lint/ParenthesesAsGroupedExpression:
Enabled: false Enabled: false
@ -62,58 +73,64 @@ Lint/ParenthesesAsGroupedExpression:
# most metrics don't make sense to apply for formulae/taps # most metrics don't make sense to apply for formulae/taps
Metrics/AbcSize: Metrics/AbcSize:
Enabled: false Enabled: false
Metrics/BlockLength: Metrics/BlockLength:
Enabled: false Enabled: false
Metrics/ClassLength: Metrics/ClassLength:
Enabled: false Enabled: false
Metrics/CyclomaticComplexity: Metrics/CyclomaticComplexity:
Enabled: false Enabled: false
Metrics/MethodLength:
Enabled: false
# Metrics/ModuleLength:
# Enabled: false
Metrics/PerceivedComplexity:
Enabled: false
# keyword arguments don't have the same readability problems
Metrics/ParameterLists:
CountKeywordArgs: false
# GitHub diff UI wraps beyond 118 characters (so that's the goal)
Metrics/LineLength: Metrics/LineLength:
# 118 is the goal as GitHub diff UI wraps beyond that
Max: 189 Max: 189
# ignore manpage comments and long single-line strings # ignore manpage comments and long single-line strings
IgnoredPatterns: ['#: ', ' url "', ' mirror "', ' plist_options :'] IgnoredPatterns: ['#: ', ' url "', ' mirror "', ' plist_options :']
Metrics/MethodLength: # dashes in filenames are typical
Enabled: false Naming/FileName:
Regex: !ruby/regexp /^[\w\@\-\+\.]+(\.rb)?$/
Metrics/ModuleLength: # implicitly allow EOS as we use it everywhere
Enabled: false Naming/HeredocDelimiterNaming:
Blacklist:
- END, EOD, EOF
Metrics/ParameterLists: # we have too many variables like sha256 where this harms readability
CountKeywordArgs: false Naming/VariableNumber:
Metrics/PerceivedComplexity:
Enabled: false Enabled: false
# makes code less readable for minor performance increases # makes code less readable for minor performance increases
Performance/Caller: Performance/Caller:
Enabled: false Enabled: false
Style/Alias: # we're doing this already so why not
EnforcedStyle: prefer_alias Performance/CaseWhenSplat:
Enabled: true
Style/AsciiComments:
Enabled: false
# enable to avoid leaking resources
Style/AutoResourceCleanup: Style/AutoResourceCleanup:
Enabled: true Enabled: true
# this is a little more obvious what's going on
Style/BarePercentLiterals: Style/BarePercentLiterals:
EnforcedStyle: percent_q EnforcedStyle: percent_q
Style/BlockDelimiters: # consistency helps readability and helps people who don't know Ruby
EnforcedStyle: line_count_based Style/CollectionMethods:
Enabled: true
Style/ClassAndModuleChildren: # our current conditional style is established
EnforcedStyle: nested # TODO: enable this when possible
# our current conditional style is established, clear and
# requiring users to change that now would be confusing.
Style/ConditionalAssignment: Style/ConditionalAssignment:
Enabled: false Enabled: false
@ -121,32 +138,17 @@ Style/ConditionalAssignment:
Style/Documentation: Style/Documentation:
Enabled: false Enabled: false
# we don't need UTF-8 encoding comments
Style/Encoding: Style/Encoding:
Enabled: true Enabled: true
# disabled until we get the Metrics/LineLength down to 80.
Style/IfUnlessModifier:
Enabled: false
# messes with existing plist/caveats style
Style/TrailingBodyOnMethodDefinition:
Enabled: false
# use spaces for indentation; detect tabs
Layout/Tab:
Enabled: true
# We have no use for using `warn` because we are
# calling Ruby with warnings disabled ourselves.
Style/StderrPuts:
Enabled: false
# dashes in filenames are typical
Naming/FileName:
Regex: !ruby/regexp /^[\w\@\-\+\.]+(\.rb)?$/
# falsely flags e.g. curl formatting arguments as format strings # falsely flags e.g. curl formatting arguments as format strings
Style/FormatStringToken: Style/FormatStringToken:
EnforcedStyle: template
# we want to add this slowly and manually
# TODO: add to more files
Style/FrozenStringLiteralComment:
Enabled: false Enabled: false
# so many of these in formulae and can't be autocorrected # so many of these in formulae and can't be autocorrected
@ -162,33 +164,31 @@ Style/HashSyntax:
- '**/lib/**/*' - '**/lib/**/*'
- '**/spec/**/*' - '**/spec/**/*'
# this doesn't make sense for wide lines below maximum line length
# https://github.com/rubocop-hq/rubocop/issues/6149
Style/IfUnlessModifier:
Enabled: false
# only for numbers >= 1_000_000 # only for numbers >= 1_000_000
Style/NumericLiterals: Style/NumericLiterals:
MinDigits: 7 MinDigits: 7
# zero-prefixed octal literals are just too widely used (and mostly understood) # zero-prefixed octal literals are just too widely used (and understood)
Style/NumericLiteralPrefix: Style/NumericLiteralPrefix:
EnforcedOctalStyle: zero_only EnforcedOctalStyle: zero_only
# consistency and readability when faced with string interpolation # rescuing StandardError is an understood default
Style/PercentLiteralDelimiters: Style/RescueStandardError:
PreferredDelimiters: EnforcedStyle: implicit
'%': '()'
'%i': '()'
'%q': '()'
'%Q': '()'
'%r': '{}'
'%s': '()'
'%w': '[]'
'%W': '[]'
'%x': '()'
Style/RaiseArgs: # return nil is unnecessary and a common mistake believing it's required
EnforcedStyle: exploded Style/ReturnNil:
Enabled: true
# paths abound, easy escape # We have no use for using `warn` because we are
Style/RegexpLiteral: # calling Ruby with warnings disabled ourselves (for now).
EnforcedStyle: slashes Style/StderrPuts:
Enabled: false
# ruby style guide favorite # ruby style guide favorite
Style/StringLiterals: Style/StringLiterals:
@ -198,46 +198,30 @@ Style/StringLiterals:
Style/StringLiteralsInInterpolation: Style/StringLiteralsInInterpolation:
EnforcedStyle: double_quotes EnforcedStyle: double_quotes
# consistency helps readability and helps people who don't know Ruby
Style/StringMethods:
Enabled: true
# less confusing to non-Rubyists
Style/SymbolArray: Style/SymbolArray:
EnforcedStyle: brackets EnforcedStyle: brackets
# make things a bit easier to read
Style/TernaryParentheses: Style/TernaryParentheses:
EnforcedStyle: require_parentheses_when_complex EnforcedStyle: require_parentheses_when_complex
# makes diffs nicer # messes with existing plist/caveats style
Style/TrailingBodyOnMethodDefinition:
Enabled: false
# all trailing commas make diffs nicer
Style/TrailingCommaInArguments:
EnforcedStyleForMultiline: comma
Style/TrailingCommaInArrayLiteral: Style/TrailingCommaInArrayLiteral:
EnforcedStyleForMultiline: comma EnforcedStyleForMultiline: comma
Style/TrailingCommaInHashLiteral: Style/TrailingCommaInHashLiteral:
EnforcedStyleForMultiline: comma EnforcedStyleForMultiline: comma
Style/TrailingCommaInArguments: # a bit confusing to non-Rubyists but useful for longer arrays
EnforcedStyleForMultiline: comma
# we have too many variables like sha256 where this harms readability
Naming/VariableNumber:
Enabled: false
# doesn't make sense for Homebrew/brew but does for taps
Naming/UncommunicativeMethodParamName:
Enabled: true
Style/WordArray: Style/WordArray:
MinSize: 4 MinSize: 4
# we want to add this slowly and manually
Style/FrozenStringLiteralComment:
Enabled: false
# generally rescuing StandardError is fine
Style/RescueStandardError:
Enabled: false
# implicitly allow EOS as we use it everywhere
Naming/HeredocDelimiterNaming:
Blacklist:
- END, EOD, EOF
# we output how to use interpolated strings too often
Lint/InterpolationCheck:
Enabled: false

View File

@ -10,14 +10,11 @@ AllCops:
- '**/Casks/**/*' - '**/Casks/**/*'
- '**/vendor/**/*' - '**/vendor/**/*'
# make rspec formatting more flexible
Layout/MultilineMethodCallIndentation: Layout/MultilineMethodCallIndentation:
Exclude: Exclude:
- '**/*_spec.rb' - '**/*_spec.rb'
# Gets false positives with our heredocs nested inside arrays
Layout/ClosingHeredocIndentation:
Enabled: false
# so many of these in formulae but none in here # so many of these in formulae but none in here
Lint/AmbiguousRegexpLiteral: Lint/AmbiguousRegexpLiteral:
Enabled: true Enabled: true
@ -31,70 +28,101 @@ Lint/NestedMethodDefinition:
Lint/ParenthesesAsGroupedExpression: Lint/ParenthesesAsGroupedExpression:
Enabled: true Enabled: true
# unused keyword arguments improve APIs
Lint/UnusedMethodArgument: Lint/UnusedMethodArgument:
AllowUnusedKeywordArguments: true AllowUnusedKeywordArguments: true
# TODO: try to bring down all metrics maximums # TODO: try to bring down all metrics maximums
Metrics/AbcSize: Metrics/AbcSize:
Max: 250 Enabled: true
Max: 275
Metrics/BlockLength: Metrics/BlockLength:
Max: 1250 Enabled: true
Max: 1100
Metrics/BlockNesting: Metrics/BlockNesting:
Enabled: true
Max: 5 Max: 5
Metrics/ClassLength: Metrics/ClassLength:
Max: 1226 Enabled: true
Max: 1400
Metrics/CyclomaticComplexity: Metrics/CyclomaticComplexity:
Enabled: true
Max: 75 Max: 75
Metrics/MethodLength:
Enabled: true
Max: 300
Metrics/ModuleLength:
Enabled: true
Max: 500
Metrics/PerceivedComplexity:
Enabled: true
Max: 100
# GitHub diff UI wraps beyond 118 characters
Metrics/LineLength: Metrics/LineLength:
# 118 is the goal as GitHub diff UI wraps beyond that
Max: 118 Max: 118
# ignore manpage comments # ignore manpage comments
IgnoredPatterns: ['#: '] IgnoredPatterns: ['#: ']
Metrics/MethodLength:
Max: 195
Metrics/ModuleLength:
Max: 222
Metrics/PerceivedComplexity:
Max: 100
# we won't change backward compatible method names
Naming/MethodName:
Exclude:
- 'compat/**/*'
# we won't change backward compatible predicate names # we won't change backward compatible predicate names
# TODO: deprecate whitelisted names and move to compat
Naming/PredicateName: Naming/PredicateName:
Exclude: Exclude:
- 'compat/**/*' - 'compat/**/*'
NameWhitelist: is_32_bit?, is_64_bit? NameWhitelist: is_32_bit?, is_64_bit?
# f meaning formulae is pretty standard # whitelist those that are standard
# TODO: try to remove some of these
Naming/UncommunicativeMethodParamName: Naming/UncommunicativeMethodParamName:
Enabled: false AllowedNames:
- '_'
- 'a'
- 'b'
- 'cc'
- 'c1'
- 'c2'
- 'd'
- 'e'
- 'f'
- 'ff'
- 'fn'
- 'id'
- 'io'
- 'o'
- 'p'
- 'pr'
- 'r'
- 'rb'
- 's'
- 'to'
- 'v'
# Avoid false positives on modifiers used on symbols of methods # Avoid false positives on modifiers used on symbols of methods
# See https://github.com/rubocop-hq/rubocop/issues/5953 # See https://github.com/rubocop-hq/rubocop/issues/5953
Style/AccessModifierDeclarations: Style/AccessModifierDeclarations:
Enabled: false Enabled: false
# make rspec formatting more flexible
Style/BlockDelimiters: Style/BlockDelimiters:
Exclude: Exclude:
- '**/*_spec.rb' - '**/*_spec.rb'
- '**/shared_examples/**/*.rb' - '**/shared_examples/**/*.rb'
# document our public APIs
Style/Documentation:
Enabled: true
Include:
- 'Library/Homebrew/formula.rb'
Style/DocumentationMethod:
Enabled: true
Include:
- 'Library/Homebrew/formula.rb'
# so many of these in formulae but none in here # so many of these in formulae but none in here
Style/GuardClause: Style/GuardClause:
Enabled: true Enabled: true
# hash-rockets preferred for formulae, a: 1 preferred elsewhere # hash-rockets preferred for formulae, a: 1 preferred here
Style/HashSyntax: Style/HashSyntax:
EnforcedStyle: ruby19_no_mixed_keys EnforcedStyle: ruby19_no_mixed_keys

View File

@ -174,7 +174,7 @@ class Build
raise raise
end end
Keg.new(path).optlink Keg.new(path).optlink
rescue StandardError rescue
raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f.full_name}. Sorry :(" raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f.full_name}. Sorry :("
end end
end end

View File

@ -30,7 +30,7 @@ module Hbc
def class_for_dsl_key(dsl_key) def class_for_dsl_key(dsl_key)
namespace = self.class.name.to_s.sub(/::.*::.*$/, "") namespace = self.class.name.to_s.sub(/::.*::.*$/, "")
self.class.const_get("#{namespace}::DSL::#{dsl_key.to_s.split("_").collect(&:capitalize).join}") self.class.const_get("#{namespace}::DSL::#{dsl_key.to_s.split("_").map(&:capitalize).join}")
end end
def abstract_phase(dsl_key) def abstract_phase(dsl_key)

View File

@ -39,7 +39,7 @@ module Hbc
check_latest_with_auto_updates check_latest_with_auto_updates
check_stanza_requires_uninstall check_stanza_requires_uninstall
self self
rescue StandardError => e rescue => e
odebug "#{e.message}\n#{e.backtrace.join("\n")}" odebug "#{e.message}\n#{e.backtrace.join("\n")}"
add_error "exception while auditing #{cask}: #{e.message}" add_error "exception while auditing #{cask}: #{e.message}"
self self

View File

@ -94,7 +94,7 @@ module Hbc
path = PATH.new(tap_cmd_directories, ENV["HOMEBREW_PATH"]) path = PATH.new(tap_cmd_directories, ENV["HOMEBREW_PATH"])
external_ruby_cmd = tap_cmd_directories.map { |d| d/"brewcask-#{command}.rb" } external_ruby_cmd = tap_cmd_directories.map { |d| d/"brewcask-#{command}.rb" }
.detect(&:file?) .find(&:file?)
external_ruby_cmd ||= which("brewcask-#{command}.rb", path) external_ruby_cmd ||= which("brewcask-#{command}.rb", path)
if external_ruby_cmd if external_ruby_cmd
@ -126,7 +126,7 @@ module Hbc
end end
def detect_command_and_arguments(*args) def detect_command_and_arguments(*args)
command = args.detect do |arg| command = args.find do |arg|
if self.class.commands.include?(arg) if self.class.commands.include?(arg)
true true
else else

View File

@ -49,7 +49,7 @@ module Hbc
if locations.empty? if locations.empty?
puts self.class.none_string puts self.class.none_string
else else
locations.collect do |l| locations.map do |l|
add_error "Legacy install at #{l}. Run \"brew uninstall --force brew-cask\"." add_error "Legacy install at #{l}. Run \"brew uninstall --force brew-cask\"."
puts l puts l
end end
@ -163,7 +163,7 @@ module Hbc
def self.cask_count_for_tap(tap) def self.cask_count_for_tap(tap)
Formatter.pluralize(tap.cask_files.count, "cask") Formatter.pluralize(tap.cask_files.count, "cask")
rescue StandardError rescue
add_error "Unable to read from Tap: #{tap.path}" add_error "Unable to read from Tap: #{tap.path}"
"0" "0"
end end

View File

@ -63,7 +63,7 @@ module Hbc
begin begin
value = cask.send(stanza) value = cask.send(stanza)
rescue StandardError rescue
opoo "failure calling '#{stanza}' on Cask '#{cask}'" unless quiet? opoo "failure calling '#{stanza}' on Cask '#{cask}'" unless quiet?
puts "" puts ""
next next

View File

@ -39,7 +39,7 @@ module Hbc
def fetch def fetch
downloader.fetch downloader.fetch
@downloaded_path = downloader.cached_location @downloaded_path = downloader.cached_location
rescue StandardError => e rescue => e
error = CaskError.new("Download failed on Cask '#{cask}' with message: #{e}") error = CaskError.new("Download failed on Cask '#{cask}' with message: #{e}")
error.set_backtrace e.backtrace error.set_backtrace e.backtrace
raise error raise error

View File

@ -102,7 +102,7 @@ module Hbc
instance_variable_set("@#{stanza}", yield) instance_variable_set("@#{stanza}", yield)
rescue CaskInvalidError rescue CaskInvalidError
raise raise
rescue StandardError => e rescue => e
raise CaskInvalidError.new(cask, "'#{stanza}' stanza failed with: #{e}") raise CaskInvalidError.new(cask, "'#{stanza}' stanza failed with: #{e}")
end end
@ -271,7 +271,7 @@ module Hbc
artifacts.add(klass.from_args(cask, *args)) artifacts.add(klass.from_args(cask, *args))
rescue CaskInvalidError rescue CaskInvalidError
raise raise
rescue StandardError => e rescue => e
raise CaskInvalidError.new(cask, "invalid '#{klass.dsl_key}' stanza: #{e}") raise CaskInvalidError.new(cask, "invalid '#{klass.dsl_key}' stanza: #{e}")
end end
end end

View File

@ -48,7 +48,7 @@ module Hbc
else else
raise raise
end end
rescue StandardError rescue
raise "invalid 'depends_on macos' value: #{arg.inspect}" raise "invalid 'depends_on macos' value: #{arg.inspect}"
end end
end end

View File

@ -74,7 +74,7 @@ module Hbc
extract_primary_container extract_primary_container
save_caskfile save_caskfile
rescue StandardError => e rescue => e
purge_versioned_files purge_versioned_files
raise e raise e
end end
@ -209,7 +209,7 @@ module Hbc
artifact.install_phase(command: @command, verbose: verbose?, force: force?) artifact.install_phase(command: @command, verbose: verbose?, force: force?)
already_installed_artifacts.unshift(artifact) already_installed_artifacts.unshift(artifact)
end end
rescue StandardError => e rescue => e
begin begin
already_installed_artifacts.each do |artifact| already_installed_artifacts.each do |artifact|
next unless artifact.respond_to?(:uninstall_phase) next unless artifact.respond_to?(:uninstall_phase)
@ -397,7 +397,7 @@ module Hbc
See System Preferences to enable it manually. See System Preferences to enable it manually.
EOS EOS
end end
rescue StandardError => e rescue => e
purge_versioned_files purge_versioned_files
raise e raise e
end end
@ -503,12 +503,12 @@ module Hbc
end end
def backup_path def backup_path
return nil if @cask.staged_path.nil? return if @cask.staged_path.nil?
Pathname.new "#{@cask.staged_path}.upgrading" Pathname.new "#{@cask.staged_path}.upgrading"
end end
def backup_metadata_path def backup_metadata_path
return nil if @cask.metadata_versioned_path.nil? return if @cask.metadata_versioned_path.nil?
Pathname.new "#{@cask.metadata_versioned_path}.upgrading" Pathname.new "#{@cask.metadata_versioned_path}.upgrading"
end end

View File

@ -47,7 +47,7 @@ module Hbc
parent = metadata_timestamped_path(version: version, timestamp: timestamp, create: create) parent = metadata_timestamped_path(version: version, timestamp: timestamp, create: create)
return nil if parent.nil? return if parent.nil?
subdir = parent.join(leaf) subdir = parent.join(leaf)

View File

@ -13,13 +13,13 @@ module Hbc
def plist_set(key, value) def plist_set(key, value)
plist_exec("Set #{key} #{value}") plist_exec("Set #{key} #{value}")
rescue StandardError => e rescue => e
raise CaskError, "#{@cask.token}: 'plist_set' failed with: #{e}" raise CaskError, "#{@cask.token}: 'plist_set' failed with: #{e}"
end end
def bundle_identifier def bundle_identifier
plist_exec("Print CFBundleIdentifier").stdout.chomp plist_exec("Print CFBundleIdentifier").stdout.chomp
rescue StandardError => e rescue => e
raise CaskError, "#{@cask.token}: 'bundle_identifier' failed with: #{e}" raise CaskError, "#{@cask.token}: 'bundle_identifier' failed with: #{e}"
end end

View File

@ -27,7 +27,7 @@ module Hbc
tried_ownership = false tried_ownership = false
begin begin
yield path yield path
rescue StandardError rescue
# in case of permissions problems # in case of permissions problems
unless tried_permissions unless tried_permissions
# TODO: Better handling for the case where path is a symlink. # TODO: Better handling for the case where path is a symlink.

View File

@ -151,7 +151,7 @@ module Homebrew
end end
def deps_for_formulae(formulae, recursive = false, &block) def deps_for_formulae(formulae, recursive = false, &block)
formulae.map { |f| deps_for_formula(f, recursive) }.inject(&block) formulae.map { |f| deps_for_formula(f, recursive) }.reduce(&block)
end end
def puts_deps(formulae) def puts_deps(formulae)

View File

@ -182,7 +182,7 @@ module Homebrew
end end
def decorate_dependencies(dependencies) def decorate_dependencies(dependencies)
deps_status = dependencies.collect do |dep| deps_status = dependencies.map do |dep|
if dep.satisfied?([]) if dep.satisfied?([])
pretty_installed(dep_display_s(dep)) pretty_installed(dep_display_s(dep))
else else
@ -193,7 +193,7 @@ module Homebrew
end end
def decorate_requirements(requirements) def decorate_requirements(requirements)
req_status = requirements.collect do |req| req_status = requirements.map do |req|
req_s = req.display_s req_s = req.display_s
req.satisfied? ? pretty_installed(req_s) : pretty_uninstalled(req_s) req.satisfied? ? pretty_installed(req_s) : pretty_uninstalled(req_s)
end end

View File

@ -88,7 +88,7 @@ module Homebrew
end end
json << { name: f.full_name, json << { name: f.full_name,
installed_versions: outdated_versions.collect(&:to_s), installed_versions: outdated_versions.map(&:to_s),
current_version: current_version, current_version: current_version,
pinned: f.pinned?, pinned: f.pinned?,
pinned_version: f.pinned_version } pinned_version: f.pinned_version }

View File

@ -56,7 +56,7 @@ module Homebrew
conflicts(*package_manager_switches) conflicts(*package_manager_switches)
end end
if package_manager = PACKAGE_MANAGERS.detect { |name,| args[:"#{name}?"] } if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] }
_, url = package_manager _, url = package_manager
exec_browser url.call(URI.encode_www_form_component(args.remaining.join(" "))) exec_browser url.call(URI.encode_www_form_component(args.remaining.join(" ")))
return return

View File

@ -60,7 +60,7 @@ module Debrew
if i.positive? if i.positive?
choice = menu.entries[i - 1] choice = menu.entries[i - 1]
else else
possible = menu.entries.find_all { |e| e.name.start_with?(input) } possible = menu.entries.select { |e| e.name.start_with?(input) }
case possible.size case possible.size
when 0 then puts "No such option" when 0 then puts "No such option"

View File

@ -257,8 +257,10 @@ module Homebrew
wanted_mode = 0100644 & ~File.umask wanted_mode = 0100644 & ~File.umask
actual_mode = formula.path.stat.mode actual_mode = formula.path.stat.mode
unless actual_mode == wanted_mode unless actual_mode == wanted_mode
problem format("Incorrect file permissions (%03o): chmod %03o %s", problem format("Incorrect file permissions (%03<actual>o): chmod %03<wanted>o %{path}",
actual_mode & 0777, wanted_mode & 0777, formula.path) actual: actual_mode & 0777,
wanted: wanted_mode & 0777,
path: formula.path)
end end
problem "'DATA' was found, but no '__END__'" if text.data? && !text.end? problem "'DATA' was found, but no '__END__'" if text.data? && !text.end?
@ -407,7 +409,7 @@ module Homebrew
dep.options.each do |opt| dep.options.each do |opt|
next if dep_f.option_defined?(opt) next if dep_f.option_defined?(opt)
next if dep_f.requirements.detect do |r| next if dep_f.requirements.find do |r|
if r.recommended? if r.recommended?
opt.name == "with-#{r.name}" opt.name == "with-#{r.name}"
elsif r.optional? elsif r.optional?

View File

@ -29,7 +29,7 @@ module Homebrew
CacheStoreDatabase.use(:linkage) do |db| CacheStoreDatabase.use(:linkage) do |db|
kegs = if ARGV.kegs.empty? kegs = if ARGV.kegs.empty?
Formula.installed.collect(&:opt_or_installed_prefix_keg).reject(&:nil?) Formula.installed.map(&:opt_or_installed_prefix_keg).reject(&:nil?)
else else
ARGV.kegs ARGV.kegs
end end

View File

@ -513,7 +513,7 @@ module Homebrew
def self.lookup(name) def self.lookup(name)
json = Utils.popen_read(HOMEBREW_BREW_FILE, "info", "--json=v1", name) json = Utils.popen_read(HOMEBREW_BREW_FILE, "info", "--json=v1", name)
return nil unless $CHILD_STATUS.success? return unless $CHILD_STATUS.success?
Homebrew.force_utf8!(json) Homebrew.force_utf8!(json)
FormulaInfoFromJson.new(JSON.parse(json)[0]) FormulaInfoFromJson.new(JSON.parse(json)[0])
@ -526,9 +526,9 @@ module Homebrew
def bottle_info(my_bottle_tag = Utils::Bottles.tag) def bottle_info(my_bottle_tag = Utils::Bottles.tag)
tag_s = my_bottle_tag.to_s tag_s = my_bottle_tag.to_s
return nil unless info["bottle"]["stable"] return unless info["bottle"]["stable"]
btl_info = info["bottle"]["stable"]["files"][tag_s] btl_info = info["bottle"]["stable"]["files"][tag_s]
return nil unless btl_info return unless btl_info
BottleInfo.new(btl_info["url"], btl_info["sha256"]) BottleInfo.new(btl_info["url"], btl_info["sha256"])
end end

View File

@ -61,13 +61,13 @@ module Homebrew
# Specify paths relative to a prefix eg. "include/foo.h". # Specify paths relative to a prefix eg. "include/foo.h".
# Sets @found for your convenience. # Sets @found for your convenience.
def find_relative_paths(*relative_paths) def find_relative_paths(*relative_paths)
@found = [HOMEBREW_PREFIX, "/usr/local"].uniq.inject([]) do |found, prefix| @found = [HOMEBREW_PREFIX, "/usr/local"].uniq.reduce([]) do |found, prefix|
found + relative_paths.map { |f| File.join(prefix, f) }.select { |f| File.exist? f } found + relative_paths.map { |f| File.join(prefix, f) }.select { |f| File.exist? f }
end end
end end
def inject_file_list(list, string) def inject_file_list(list, string)
list.inject(string) { |acc, elem| acc << " #{elem}\n" } list.reduce(string) { |acc, elem| acc << " #{elem}\n" }
end end
############# END HELPERS ############# END HELPERS

View File

@ -93,7 +93,7 @@ module HomebrewArgvExtension
def kegs def kegs
require "keg" require "keg"
require "formula" require "formula"
@kegs ||= downcased_unique_named.collect do |name| @kegs ||= downcased_unique_named.map do |name|
raise UsageError if name.empty? raise UsageError if name.empty?
rack = Formulary.to_rack(name.downcase) rack = Formulary.to_rack(name.downcase)

View File

@ -23,11 +23,11 @@ class JavaRequirement < Requirement
end end
def java_home_cmd def java_home_cmd
return nil unless File.executable?("/usr/libexec/java_home") return unless File.executable?("/usr/libexec/java_home")
args = %w[--failfast] args = %w[--failfast]
args << "--version" << @version.to_s if @version args << "--version" << @version.to_s if @version
java_home = Utils.popen_read("/usr/libexec/java_home", *args).chomp java_home = Utils.popen_read("/usr/libexec/java_home", *args).chomp
return nil unless $CHILD_STATUS.success? return unless $CHILD_STATUS.success?
Pathname.new(java_home)/"bin/java" Pathname.new(java_home)/"bin/java"
end end

View File

@ -1120,7 +1120,7 @@ class Formula
begin begin
yield self, staging yield self, staging
rescue StandardError rescue
staging.retain! if ARGV.interactive? || ARGV.debug? staging.retain! if ARGV.interactive? || ARGV.debug?
raise raise
ensure ensure
@ -1373,7 +1373,7 @@ class Formula
files.each do |file| files.each do |file|
begin begin
yield Formulary.factory(file) yield Formulary.factory(file)
rescue StandardError => e rescue => e
# Don't let one broken formula break commands. But do complain. # Don't let one broken formula break commands. But do complain.
onoe "Failed to import: #{file}" onoe "Failed to import: #{file}"
puts e puts e
@ -1812,7 +1812,9 @@ class Formula
@exec_count ||= 0 @exec_count ||= 0
@exec_count += 1 @exec_count += 1
logfn = format("#{logs}/#{active_log_prefix}%02d.%s", @exec_count, File.basename(cmd).split(" ").first) logfn = format("#{logs}/#{active_log_prefix}%02<exec_count>d.%{cmd_base}",
exec_count: @exec_count,
cmd_base: File.basename(cmd).split(" ").first)
logs.mkpath logs.mkpath
File.open(logfn, "w") do |log| File.open(logfn, "w") do |log|
@ -2006,7 +2008,7 @@ class Formula
$stdout.reopen(out) $stdout.reopen(out)
$stderr.reopen(out) $stderr.reopen(out)
out.close out.close
args.collect!(&:to_s) args.map!(&:to_s)
begin begin
exec(cmd, *args) exec(cmd, *args)
rescue rescue

View File

@ -283,7 +283,7 @@ module Formulary
# to install the formula will be set instead. # to install the formula will be set instead.
def self.from_rack(rack, spec = nil, alias_path: nil) def self.from_rack(rack, spec = nil, alias_path: nil)
kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : [] kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : []
keg = kegs.detect(&:linked?) || kegs.detect(&:optlinked?) || kegs.max_by(&:version) keg = kegs.find(&:linked?) || kegs.find(&:optlinked?) || kegs.max_by(&:version)
if keg if keg
from_keg(keg, spec, alias_path: alias_path) from_keg(keg, spec, alias_path: alias_path)
@ -432,7 +432,7 @@ module Formulary
"#{tap}HomebrewFormula/#{name}.rb", "#{tap}HomebrewFormula/#{name}.rb",
"#{tap}#{name}.rb", "#{tap}#{name}.rb",
"#{tap}Aliases/#{name}", "#{tap}Aliases/#{name}",
]).detect(&:file?) ]).find(&:file?)
end.compact end.compact
end end

View File

@ -389,7 +389,7 @@ class Keg
def oldname_opt_record def oldname_opt_record
@oldname_opt_record ||= if (opt_dir = HOMEBREW_PREFIX/"opt").directory? @oldname_opt_record ||= if (opt_dir = HOMEBREW_PREFIX/"opt").directory?
opt_dir.subdirs.detect do |dir| opt_dir.subdirs.find do |dir|
dir.symlink? && dir != opt_record && path.parent == dir.resolved_path.parent dir.symlink? && dir != opt_record && path.parent == dir.resolved_path.parent
end end
end end

View File

@ -69,8 +69,8 @@ class Locale
alias == eql? alias == eql?
def detect(locale_groups) def detect(locale_groups)
locale_groups.detect { |locales| locales.any? { |locale| eql?(locale) } } || locale_groups.find { |locales| locales.any? { |locale| eql?(locale) } } ||
locale_groups.detect { |locales| locales.any? { |locale| include?(locale) } } locale_groups.find { |locales| locales.any? { |locale| include?(locale) } }
end end
def to_s def to_s

View File

@ -174,7 +174,7 @@ class Migrator
keg_dirs += new_cellar.subdirs if new_cellar.exist? keg_dirs += new_cellar.subdirs if new_cellar.exist?
keg_dirs += old_cellar.subdirs keg_dirs += old_cellar.subdirs
kegs = keg_dirs.map { |d| Keg.new(d) } kegs = keg_dirs.map { |d| Keg.new(d) }
kegs.detect(&:linked?) || kegs.detect(&:optlinked?) kegs.find(&:linked?) || kegs.find(&:optlinked?)
end end
def pinned? def pinned?

View File

@ -37,7 +37,7 @@ module ArchitectureListExtension
end end
def as_arch_flags def as_arch_flags
collect { |a| "-arch #{a}" }.join(" ") map { |a| "-arch #{a}" }.join(" ")
end end
def as_cmake_arch_flags def as_cmake_arch_flags

View File

@ -94,7 +94,7 @@ class JavaRequirement < Requirement
end end
def preferred_java def preferred_java
possible_javas.detect do |java| possible_javas.find do |java|
next false unless java&.executable? next false unless java&.executable?
next true unless @version next true unless @version
next true if satisfies_version(java) next true if satisfies_version(java)

View File

@ -335,7 +335,7 @@ class Tap
# path to the directory of all {Formula} files for this {Tap}. # path to the directory of all {Formula} files for this {Tap}.
def formula_dir def formula_dir
@formula_dir ||= potential_formula_dirs.detect(&:directory?) || path/"Formula" @formula_dir ||= potential_formula_dirs.find(&:directory?) || path/"Formula"
end end
def potential_formula_dirs def potential_formula_dirs

View File

@ -47,7 +47,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
inspect_source(source) inspect_source(source)
expected_offense = if patch_url =~ %r{/raw\.github\.com/} expected_offense = if patch_url =~ %r{/raw\.github\.com/}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
GitHub/Gist patches should specify a revision: GitHub/Gist patches should specify a revision:
#{patch_url} #{patch_url}
EOS EOS
@ -56,7 +57,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 12, column: 12,
source: source }] source: source }]
elsif patch_url =~ %r{macports/trunk} elsif patch_url =~ %r{macports/trunk}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
MacPorts patches should specify a revision instead of trunk: MacPorts patches should specify a revision instead of trunk:
#{patch_url} #{patch_url}
EOS EOS
@ -65,7 +67,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 33, column: 33,
source: source }] source: source }]
elsif patch_url =~ %r{^http://trac\.macports\.org} elsif patch_url =~ %r{^http://trac\.macports\.org}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
Patches from MacPorts Trac should be https://, not http: Patches from MacPorts Trac should be https://, not http:
#{patch_url} #{patch_url}
EOS EOS
@ -74,7 +77,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 5, column: 5,
source: source }] source: source }]
elsif patch_url =~ %r{^http://bugs\.debian\.org} elsif patch_url =~ %r{^http://bugs\.debian\.org}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
Patches from Debian should be https://, not http: Patches from Debian should be https://, not http:
#{patch_url} #{patch_url}
EOS EOS
@ -83,7 +87,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 5, column: 5,
source: source }] source: source }]
elsif patch_url =~ %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)} elsif patch_url =~ %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)}
[{ message: <<~EOS, [{ message:
<<~EOS,
use GitHub pull request URLs: use GitHub pull request URLs:
https://github.com/foo/foo-bar/pull/100.patch https://github.com/foo/foo-bar/pull/100.patch
Rather than patch-diff: Rather than patch-diff:
@ -94,7 +99,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 5, column: 5,
source: source }] source: source }]
elsif patch_url =~ %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)} elsif patch_url =~ %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)}
[{ message: <<~EOS, [{ message:
<<~EOS,
GitHub patches should use the full_index parameter: GitHub patches should use the full_index parameter:
#{patch_url}?full_index=1 #{patch_url}?full_index=1
EOS EOS
@ -132,7 +138,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
line: 4, line: 4,
column: 2, column: 2,
source: source }, source: source },
{ message: <<~EOS.chomp, { message:
<<~EOS.chomp,
Patches from MacPorts Trac should be https://, not http: Patches from MacPorts Trac should be https://, not http:
http://trac.macports.org/export/68507/trunk/dports/net/trafshow/files/ http://trac.macports.org/export/68507/trunk/dports/net/trafshow/files/
EOS EOS
@ -175,7 +182,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
inspect_source(source) inspect_source(source)
expected_offense = if patch_url =~ %r{/raw\.github\.com/} expected_offense = if patch_url =~ %r{/raw\.github\.com/}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
GitHub/Gist patches should specify a revision: GitHub/Gist patches should specify a revision:
#{patch_url} #{patch_url}
EOS EOS
@ -184,7 +192,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 16, column: 16,
source: source }] source: source }]
elsif patch_url =~ %r{macports/trunk} elsif patch_url =~ %r{macports/trunk}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
MacPorts patches should specify a revision instead of trunk: MacPorts patches should specify a revision instead of trunk:
#{patch_url} #{patch_url}
EOS EOS
@ -193,7 +202,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 37, column: 37,
source: source }] source: source }]
elsif patch_url =~ %r{^http://trac\.macports\.org} elsif patch_url =~ %r{^http://trac\.macports\.org}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
Patches from MacPorts Trac should be https://, not http: Patches from MacPorts Trac should be https://, not http:
#{patch_url} #{patch_url}
EOS EOS
@ -202,7 +212,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 9, column: 9,
source: source }] source: source }]
elsif patch_url =~ %r{^http://bugs\.debian\.org} elsif patch_url =~ %r{^http://bugs\.debian\.org}
[{ message: <<~EOS.chomp, [{ message:
<<~EOS.chomp,
Patches from Debian should be https://, not http: Patches from Debian should be https://, not http:
#{patch_url} #{patch_url}
EOS EOS
@ -211,7 +222,8 @@ describe RuboCop::Cop::FormulaAudit::Patches do
column: 9, column: 9,
source: source }] source: source }]
elsif patch_url =~ %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)} elsif patch_url =~ %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)}
[{ message: <<~EOS, [{ message:
<<~EOS,
use GitHub pull request URLs: use GitHub pull request URLs:
https://github.com/foo/foo-bar/pull/100.patch https://github.com/foo/foo-bar/pull/100.patch
Rather than patch-diff: Rather than patch-diff:

View File

@ -80,11 +80,11 @@ module UnpackStrategy
def self.from_extension(extension) def self.from_extension(extension)
strategies.sort_by { |s| s.extensions.map(&:length).max(0) } strategies.sort_by { |s| s.extensions.map(&:length).max(0) }
.reverse .reverse
.detect { |s| s.extensions.any? { |ext| extension.end_with?(ext) } } .find { |s| s.extensions.any? { |ext| extension.end_with?(ext) } }
end end
def self.from_magic(path) def self.from_magic(path)
strategies.detect { |s| s.can_extract?(path) } strategies.find { |s| s.can_extract?(path) }
end end
def self.detect(path, extension_only: false, type: nil, ref_type: nil, ref: nil) def self.detect(path, extension_only: false, type: nil, ref_type: nil, ref: nil)
@ -93,7 +93,7 @@ module UnpackStrategy
if extension_only if extension_only
strategy ||= from_extension(path.extname) strategy ||= from_extension(path.extname)
strategy ||= strategies.select { |s| s < Directory || s == Fossil } strategy ||= strategies.select { |s| s < Directory || s == Fossil }
.detect { |s| s.can_extract?(path) } .find { |s| s.can_extract?(path) }
else else
strategy ||= from_magic(path) strategy ||= from_magic(path)
strategy ||= from_extension(path.extname) strategy ||= from_extension(path.extname)

View File

@ -31,8 +31,10 @@ module UnpackStrategy
end end
def bom def bom
# rubocop:disable Style/AsciiComments
# We need to use `find` here instead of Ruby in order to properly handle # We need to use `find` here instead of Ruby in order to properly handle
# file names containing special characters, such as “e” + “´” vs. “é”. # file names containing special characters, such as “e” + “´” vs. “é”.
# rubocop:enable Style/AsciiComments
system_command("find", args: [".", "-print0"], chdir: self, print_stderr: false) system_command("find", args: [".", "-print0"], chdir: self, print_stderr: false)
.stdout .stdout
.split("\0") .split("\0")

View File

@ -182,7 +182,7 @@ module Homebrew
def _system(cmd, *args, **options) def _system(cmd, *args, **options)
pid = fork do pid = fork do
yield if block_given? yield if block_given?
args.collect!(&:to_s) args.map!(&:to_s)
begin begin
exec(cmd, *args, **options) exec(cmd, *args, **options)
rescue rescue
@ -380,7 +380,7 @@ end
# GZips the given paths, and returns the gzipped paths # GZips the given paths, and returns the gzipped paths
def gzip(*paths) def gzip(*paths)
paths.collect do |path| paths.map do |path|
safe_system "gzip", path safe_system "gzip", path
Pathname.new("#{path}.gz") Pathname.new("#{path}.gz")
end end
@ -426,7 +426,7 @@ def nostdout
end end
def paths def paths
@paths ||= PATH.new(ENV["HOMEBREW_PATH"]).collect do |p| @paths ||= PATH.new(ENV["HOMEBREW_PATH"]).map do |p|
begin begin
File.expand_path(p).chomp("/") File.expand_path(p).chomp("/")
rescue ArgumentError rescue ArgumentError

View File

@ -1,7 +1,7 @@
module Utils module Utils
class InreplaceError < RuntimeError class InreplaceError < RuntimeError
def initialize(errors) def initialize(errors)
formatted_errors = errors.inject("inreplace failed\n") do |s, (path, errs)| formatted_errors = errors.reduce("inreplace failed\n") do |s, (path, errs)|
s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join
end end
super formatted_errors super formatted_errors