rubocops/text: Include dashed binaries in bin/ interpolation check

- Previously this only included the formula name.
- But, for example in tests, we have "#{bin}/ansible-test",
  not just "#{bin}/ansible". So handle that too.
- I decided to make the error message better by extracting the
  binary name from the interpolation, but I'm not sure it was worth it.

```
$ brew audit --strict ansible
ansible
  * line 580, col 29: Use `bin/"ansible-test"` instead of `"#{bin}/ansible-test"`
Error: 1 problem in 1 formula detected.
```
This commit is contained in:
Issy Long 2024-07-24 21:57:45 +01:00
parent 96400e01e1
commit 3713939e0d
No known key found for this signature in database
2 changed files with 12 additions and 7 deletions

View File

@ -137,9 +137,10 @@ module RuboCop
problem "Use `\#{pkgshare}` instead of `\#{share}/#{@formula_name}`"
end
interpolated_bin_path_starts_with(body_node, "/#{@formula_name}") do |bin_node|
interpolated_bin_path_starts_with(body_node, "/#{@formula_name}", true) do |bin_node|
offending_node(bin_node)
problem "Use `bin/\"#{@formula_name}\"` instead of `\"\#{bin}/#{@formula_name}\"`"
cmd = bin_node.source.match(%r{\#{bin}/(\S+)})[1]&.delete_suffix('"') || @formula_name
problem "Use `bin/\"#{cmd}\"` instead of `\"\#{bin}/#{cmd}\"`"
end
return if formula_tap != "homebrew-core"
@ -150,8 +151,10 @@ module RuboCop
end
# Check whether value starts with the formula name and then a "/", " " or EOS.
def path_starts_with?(path, starts_with)
path.match?(%r{^#{Regexp.escape(starts_with)}(/| |$)})
# If we're checking for "#{bin}", we also check for "-" since similar binaries also don't need interpolation.
def path_starts_with?(path, starts_with, bin = false)
ending = bin ? "/| |-|$" : "/| |$"
path.match?(/^#{Regexp.escape(starts_with)}(#{ending})/)
end
# Find "#{share}/foo"
@ -159,9 +162,9 @@ module RuboCop
$(dstr (begin (send nil? :share)) (str #path_starts_with?(%1)))
EOS
# Find "#{bin}/foo"
# Find "#{bin}/foo" and "#{bin}/foo-bar"
def_node_search :interpolated_bin_path_starts_with, <<~EOS
$(dstr (begin (send nil? :bin)) (str #path_starts_with?(%1)))
$(dstr (begin (send nil? :bin)) (str #path_starts_with?(%1, %2)))
EOS
# Find share/"foo"

View File

@ -132,12 +132,14 @@ RSpec.describe RuboCop::Cop::FormulaAuditStrict::Text do
RUBY
end
it 'reports an offense if "\#{bin}/<formula name>" is present' do
it 'reports an offense if "\#{bin}/<formula_name>" or other dashed binaries too are present' do
expect_offense(<<~RUBY, "/homebrew-core/Formula/foo.rb")
class Foo < Formula
test do
ohai "\#{bin}/foo", "-v"
^^^^^^^^^^^^ FormulaAuditStrict/Text: Use `bin/"foo"` instead of `"\#{bin}/foo"`
ohai "\#{bin}/foo-bar", "-v"
^^^^^^^^^^^^^^^^ FormulaAuditStrict/Text: Use `bin/"foo-bar"` instead of `"\#{bin}/foo-bar"`
end
end
RUBY