rubocop/no_fileutils_rmrf: Extend to cover FileUtils#rmtree too

This commit is contained in:
Issy Long 2024-07-13 16:12:30 -04:00 committed by Issy Long
parent f4e4808553
commit ebd9d183dc
No known key found for this signature in database
2 changed files with 16 additions and 4 deletions

View File

@ -4,21 +4,26 @@
module RuboCop
module Cop
module Homebrew
# This cop checks for the use of `FileUtils.rm_f` or `FileUtils.rm_rf` and recommends the non-`f` versions.
# This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `FileUtils.rmtree`
# and recommends the non-`f` versions.
class NoFileutilsRmrf < Base
extend AutoCorrector
MSG = "Use `FileUtils.rm` or `FileUtils.rm_f` instead of `FileUtils.rm_rf` or `FileUtils.rm_f`."
MSG = "Use `FileUtils.rm`, `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, or `FileUtils.rmtree`."
def_node_matcher :fileutils_rm_r_f?, <<~PATTERN
(send (const {nil? cbase} :FileUtils) {:rm_rf :rm_f} ...)
(send (const {nil? cbase} :FileUtils) {:rm_rf :rm_f :rmtree} ...)
PATTERN
def on_send(node)
return unless fileutils_rm_r_f?(node)
add_offense(node) do |corrector|
new_method = node.method?(:rm_rf) ? "rm_r" : "rm"
new_method = if node.method?(:rm_rf) || node.method?(:rmtree)
"rm_r"
else
"rm"
end
corrector.replace(node.loc.expression, "FileUtils.#{new_method}(#{node.arguments.first.source})")
end
end

View File

@ -19,6 +19,13 @@ RSpec.describe RuboCop::Cop::Homebrew::NoFileutilsRmrf do
RUBY
end
it "registers an offense when using FileUtils.rmtree" do
expect_offense(<<~RUBY)
FileUtils.rmtree("path/to/directory")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Homebrew/NoFileutilsRmrf: #{RuboCop::Cop::Homebrew::NoFileutilsRmrf::MSG}
RUBY
end
it "autocorrects" do
corrected = autocorrect_source(<<~RUBY)
FileUtils.rm_rf("path/to/directory")