Skip to content

Commit

Permalink
rubocop/no_fileutils_rmrf: Extend to cover rmtree_f too
Browse files Browse the repository at this point in the history
  • Loading branch information
issyl0 committed Jul 13, 2024
1 parent 1793127 commit ffaa407
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
15 changes: 11 additions & 4 deletions Library/Homebrew/rubocops/no_fileutils_rmrf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,28 @@
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_f`
# 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_f` or `FileUtils.rmtree` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, or `FileUtils.rmtree_f`."

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_f} ...)
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)
"rm_r"
elsif node.method?(:rmtree_f)
"rmtree"
else
"rm"
end
corrector.replace(node.loc.expression, "FileUtils.#{new_method}(#{node.arguments.first.source})")
end
end
Expand Down
13 changes: 13 additions & 0 deletions Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
RUBY
end

it "registers an offense when using FileUtils.rmtree_f" do
expect_offense(<<~RUBY)
FileUtils.rmtree_f("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")
Expand All @@ -40,4 +47,10 @@
FileUtils.rm("path/to/directory")
RUBY
end

it "does not register an offense when using FileUtils.rmtree" do
expect_no_offenses(<<~RUBY)
FileUtils.rmtree("path/to/directory")
RUBY
end
end

0 comments on commit ffaa407

Please sign in to comment.