diff --git a/Library/Homebrew/rubocops/no_fileutils_rmrf.rb b/Library/Homebrew/rubocops/no_fileutils_rmrf.rb index 914d2a79d89f0..a99c9c5452e29 100644 --- a/Library/Homebrew/rubocops/no_fileutils_rmrf.rb +++ b/Library/Homebrew/rubocops/no_fileutils_rmrf.rb @@ -4,19 +4,24 @@ module RuboCop module Cop module Homebrew - # This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `FileUtils.rmtree` - # and recommends the non-`f` versions. + # This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `{FileUtils,Pathname}.rmtree` + # and recommends the safer versions. class NoFileutilsRmrf < Base extend AutoCorrector - MSG = "Use `FileUtils.rm`, `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, or `FileUtils.rmtree`." + MSG = "Use `FileUtils.rm` or `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, " \ + "or `{FileUtils,Pathname}.rmtree`." def_node_matcher :fileutils_rm_r_f?, <<~PATTERN (send (const {nil? cbase} :FileUtils) {:rm_rf :rm_f :rmtree} ...) PATTERN + def_node_matcher :pathname_rmtree?, <<~PATTERN + (send (const {nil? cbase} :Pathname) :rmtree ...) + PATTERN + def on_send(node) - return unless fileutils_rm_r_f?(node) + return if neither_rm_rf_nor_rmtree?(node) add_offense(node) do |corrector| new_method = if node.method?(:rm_rf) || node.method?(:rmtree) @@ -24,9 +29,14 @@ def on_send(node) else "rm" end + corrector.replace(node.loc.expression, "FileUtils.#{new_method}(#{node.arguments.first.source})") end end + + def neither_rm_rf_nor_rmtree?(node) + !fileutils_rm_r_f?(node) && !pathname_rmtree?(node) + 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 index 9ea3634ae2d2b..4581fb2dbba70 100644 --- a/Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb +++ b/Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb @@ -61,4 +61,23 @@ RUBY end end + + describe "Pathname.rmtree" do + it "registers an offense" do + expect_offense(<<~RUBY) + Pathname.rmtree("path/to/directory") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Homebrew/NoFileutilsRmrf: #{RuboCop::Cop::Homebrew::NoFileutilsRmrf::MSG} + RUBY + end + + it "autocorrects" do + corrected = autocorrect_source(<<~RUBY) + Pathname.rmtree("path/to/directory") + RUBY + + expect(corrected).to eq(<<~RUBY) + FileUtils.rm_r("path/to/directory") + RUBY + end + end end