diff --git a/Library/Homebrew/rubocops/caveats.rb b/Library/Homebrew/rubocops/caveats.rb index 8d228e10fa..73922a2d31 100644 --- a/Library/Homebrew/rubocops/caveats.rb +++ b/Library/Homebrew/rubocops/caveats.rb @@ -6,13 +6,25 @@ require "rubocops/extend/formula_cop" 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 @@ -35,6 +47,18 @@ module RuboCop 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 diff --git a/Library/Homebrew/test/rubocops/caveats_spec.rb b/Library/Homebrew/test/rubocops/caveats_spec.rb index 6b262fd278..7524d7df54 100644 --- a/Library/Homebrew/test/rubocops/caveats_spec.rb +++ b/Library/Homebrew/test/rubocops/caveats_spec.rb @@ -42,5 +42,35 @@ RSpec.describe RuboCop::Cop::FormulaAudit::Caveats do 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