diff --git a/Library/Homebrew/rubocops/all.rb b/Library/Homebrew/rubocops/all.rb index 284d135bd5..bfcf79a8b9 100644 --- a/Library/Homebrew/rubocops/all.rb +++ b/Library/Homebrew/rubocops/all.rb @@ -8,6 +8,7 @@ require_relative "compact_blank" require_relative "io_read" require_relative "move_to_extend_os" require_relative "negate_include" +require_relative "no_fileutils_rmrf" require_relative "presence" require_relative "present" require_relative "safe_navigation_with_blank" diff --git a/Library/Homebrew/rubocops/no_fileutils_rmrf.rb b/Library/Homebrew/rubocops/no_fileutils_rmrf.rb new file mode 100644 index 0000000000..c6de46f8b3 --- /dev/null +++ b/Library/Homebrew/rubocops/no_fileutils_rmrf.rb @@ -0,0 +1,27 @@ +# typed: true +# frozen_string_literal: true + +module RuboCop + module Cop + module Homebrew + # This cop checks for the use of `FileUtils.rm_rf` and recommends `FileUtils.rm_r`. + class NoFileutilsRmrf < Base + extend AutoCorrector + + MSG = "Use `FileUtils.rm_r` instead of `FileUtils.rm_rf`." + + def_node_matcher :fileutils_rm_rf?, <<~PATTERN + (send (const {nil? cbase} :FileUtils) :rm_rf ...) + PATTERN + + def on_send(node) + return unless fileutils_rm_rf?(node) + + add_offense(node) do |corrector| + corrector.replace(node.loc.expression, "FileUtils.rm_r(#{node.arguments.first.source})") + end + end + end + end + end +end diff --git a/Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb b/Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb new file mode 100644 index 0000000000..1b590fa12b --- /dev/null +++ b/Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require "rubocops/no_fileutils_rmrf" + +RSpec.describe RuboCop::Cop::Homebrew::NoFileutilsRmrf do + subject(:cop) { described_class.new } + + it "registers an offense when using FileUtils.rm_rf" do + expect_offense(<<~RUBY) + FileUtils.rm_rf("path/to/directory") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Homebrew/NoFileutilsRmrf: Use `FileUtils.rm_r` instead of `FileUtils.rm_rf`. + RUBY + end + + it "autocorrects" do + corrected = autocorrect_source(<<~RUBY) + FileUtils.rm_rf("path/to/directory") + RUBY + + expect(corrected).to eq(<<~RUBY) + FileUtils.rm_r("path/to/directory") + RUBY + end + + it "does not register an offense when using FileUtils.rm_r" do + expect_no_offenses(<<~RUBY) + FileUtils.rm_r("path/to/directory") + RUBY + end +end