Skip to content

Commit

Permalink
rubocop/no_fileutils_rmrf: Discourage Pathname#rmtree too
Browse files Browse the repository at this point in the history
- This [seems to be](https://ruby-doc.org/3.3.4/exts/pathname/Pathname.html#method-i-rmtree)
  equivalent to `FileUtils#rm_r`, so replace it with that.
  • Loading branch information
issyl0 committed Jul 14, 2024
1 parent 1e2e5ec commit 87e90fe
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
14 changes: 10 additions & 4 deletions Library/Homebrew/rubocops/no_fileutils_rmrf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,32 @@
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 unless fileutils_rm_r_f?(node) || pathname_rmtree?(node)

add_offense(node) do |corrector|
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
Expand Down
19 changes: 19 additions & 0 deletions Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,24 @@
FileUtils.rm_r("path/to/directory")
RUBY
end

describe "Pathname.rmtree" do
it "registers an offense when using Pathname.rmtree" 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
end

0 comments on commit 87e90fe

Please sign in to comment.