Skip to content

rubocops/caveats: check for dynamic caveats. #20135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion Library/Homebrew/rubocops/caveats.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,25 @@
module RuboCop
module Cop
module FormulaAudit
# This cop ensures that caveats don't recommend unsupported or unsafe operations.
# This cop ensures that caveats don't have problematic text or logic.
#
# ### Example
#
# ```ruby
# # bad
# def caveats
# if File.exist?("/etc/issue")
# "This caveat only when file exists that won't work with JSON API."
# end
# end
#
# # good
# def caveats
# "This caveat always works regardless of the JSON API."
# end
#
# # bad
# def caveats
# <<~EOS
# Use `setuid` to allow running the executable by non-root users.
# EOS
Expand All @@ -35,6 +47,18 @@ def audit_formula(_formula_nodes)

problem "Don't use ANSI escape codes in the caveats." if regex_match_group(n, /\e/)
end

# Forbid dynamic logic in caveats (only if/else/unless)
caveats_method = find_method_def(@body, :caveats)
return unless caveats_method

dynamic_nodes = caveats_method.each_descendant.select do |descendant|
descendant.type == :if
end
dynamic_nodes.each do |node|
@offensive_node = node
problem "Don't use dynamic logic (if/else/unless) in caveats."
end
end
end
end
Expand Down
30 changes: 30 additions & 0 deletions Library/Homebrew/test/rubocops/caveats_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,35 @@ def caveats
end
RUBY
end

it "reports an offense if dynamic logic (if/else/unless) is used in caveats" do
expect_offense(<<~RUBY, "/homebrew-core/Formula/foo.rb")
class Foo < Formula
homepage "https://brew.sh/foo"
url "https://brew.sh/foo-1.0.tgz"
def caveats
if true
^^^^^^^ FormulaAudit/Caveats: Don't use dynamic logic (if/else/unless) in caveats.
"foo"
else
"bar"
end
end
end
RUBY

expect_offense(<<~RUBY, "/homebrew-core/Formula/foo.rb")
class Foo < Formula
homepage "https://brew.sh/foo"
url "https://brew.sh/foo-1.0.tgz"
def caveats
unless false
^^^^^^^^^^^^ FormulaAudit/Caveats: Don't use dynamic logic (if/else/unless) in caveats.
"foo"
end
end
end
RUBY
end
end
end