Add cop to police os checks

The methods `OS.linux?` and `OS.mac?` should only be used
in `extend/os` and this cop makes sure of that.
This commit is contained in:
apainintheneck 2022-11-19 21:46:58 -08:00
parent 759ab2d0bd
commit c7d53a2d9c
4 changed files with 53 additions and 0 deletions

View File

@ -55,6 +55,11 @@ FormulaAudit:
FormulaAuditStrict: FormulaAuditStrict:
Enabled: true Enabled: true
Homebrew/MoveToExtendOS:
Exclude:
- "Homebrew/{extend,test}/**/*"
- "Taps/**/*"
# enable all Homebrew custom cops # enable all Homebrew custom cops
Homebrew: Homebrew:
Enabled: true Enabled: true

View File

@ -14,6 +14,7 @@ end
require_relative "io_read" require_relative "io_read"
require_relative "shell_commands" require_relative "shell_commands"
require_relative "platform"
require_relative "formula_desc" require_relative "formula_desc"
require_relative "components_order" require_relative "components_order"

View File

@ -0,0 +1,25 @@
# typed: false
# frozen_string_literal: true
module RuboCop
module Cop
module Homebrew
# This cop ensures that platform specific code ends up in `extend/os`.
#
# @api private
class MoveToExtendOS < Base
MSG = "Move calls to `OS.linux?` and `OS.mac?` to `extend/os`."
def_node_matcher :os_check?, <<~PATTERN
(send (const nil? :OS) {:mac? | :linux?})
PATTERN
def on_send(node)
return unless os_check?(node)
add_offense(node)
end
end
end
end
end

View File

@ -0,0 +1,22 @@
# typed: false
# frozen_string_literal: true
require "rubocops/platform"
describe RuboCop::Cop::Homebrew::MoveToExtendOS do
subject(:cop) { described_class.new }
it "registers an offense when using `OS.linux?`" do
expect_offense(<<~RUBY)
OS.linux?
^^^^^^^^^ Move calls to `OS.linux?` and `OS.mac?` to `extend/os`.
RUBY
end
it "registers an offense when using `OS.mac?`" do
expect_offense(<<~RUBY)
OS.mac?
^^^^^^^ Move calls to `OS.linux?` and `OS.mac?` to `extend/os`.
RUBY
end
end