Skip to content

Commit 87e90fe

Browse files
committed
rubocop/no_fileutils_rmrf: Discourage Pathname#rmtree too
- 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.
1 parent 1e2e5ec commit 87e90fe

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

Library/Homebrew/rubocops/no_fileutils_rmrf.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,32 @@
44
module RuboCop
55
module Cop
66
module Homebrew
7-
# This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `FileUtils.rmtree`
8-
# and recommends the non-`f` versions.
7+
# This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `{FileUtils,Pathname}.rmtree`
8+
# and recommends the safer versions.
99
class NoFileutilsRmrf < Base
1010
extend AutoCorrector
1111

12-
MSG = "Use `FileUtils.rm`, `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, or `FileUtils.rmtree`."
12+
MSG = "Use `FileUtils.rm` or `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, " \
13+
"or `{FileUtils,Pathname}.rmtree`."
1314

1415
def_node_matcher :fileutils_rm_r_f?, <<~PATTERN
1516
(send (const {nil? cbase} :FileUtils) {:rm_rf :rm_f :rmtree} ...)
1617
PATTERN
1718

19+
def_node_matcher :pathname_rmtree?, <<~PATTERN
20+
(send (const {nil? cbase} :Pathname) :rmtree ...)
21+
PATTERN
22+
1823
def on_send(node)
19-
return unless fileutils_rm_r_f?(node)
24+
return unless fileutils_rm_r_f?(node) || pathname_rmtree?(node)
2025

2126
add_offense(node) do |corrector|
2227
new_method = if node.method?(:rm_rf) || node.method?(:rmtree)
2328
"rm_r"
2429
else
2530
"rm"
2631
end
32+
2733
corrector.replace(node.loc.expression, "FileUtils.#{new_method}(#{node.arguments.first.source})")
2834
end
2935
end

Library/Homebrew/test/rubocops/no_fileutils_rmrf_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,24 @@
6060
FileUtils.rm_r("path/to/directory")
6161
RUBY
6262
end
63+
64+
describe "Pathname.rmtree" do
65+
it "registers an offense when using Pathname.rmtree" do
66+
expect_offense(<<~RUBY)
67+
Pathname.rmtree("path/to/directory")
68+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Homebrew/NoFileutilsRmrf: #{RuboCop::Cop::Homebrew::NoFileutilsRmrf::MSG}
69+
RUBY
70+
end
71+
72+
it "autocorrects" do
73+
corrected = autocorrect_source(<<~RUBY)
74+
Pathname.rmtree("path/to/directory")
75+
RUBY
76+
77+
expect(corrected).to eq(<<~RUBY)
78+
FileUtils.rm_r("path/to/directory")
79+
RUBY
80+
end
81+
end
6382
end
6483
end

0 commit comments

Comments
 (0)