2024-07-13 15:35:06 -04:00
|
|
|
# typed: true
|
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
|
|
|
module Homebrew
|
2024-07-13 22:13:03 -04:00
|
|
|
# This cop checks for the use of `FileUtils.rm_f`, `FileUtils.rm_rf`, or `{FileUtils,Pathname}.rmtree`
|
|
|
|
# and recommends the safer versions.
|
2024-07-13 15:35:06 -04:00
|
|
|
class NoFileutilsRmrf < Base
|
|
|
|
extend AutoCorrector
|
|
|
|
|
2024-07-13 22:13:03 -04:00
|
|
|
MSG = "Use `FileUtils.rm` or `FileUtils.rm_r` instead of `FileUtils.rm_rf`, `FileUtils.rm_f`, " \
|
|
|
|
"or `{FileUtils,Pathname}.rmtree`."
|
2024-07-13 15:35:06 -04:00
|
|
|
|
2024-07-13 16:01:25 -04:00
|
|
|
def_node_matcher :fileutils_rm_r_f?, <<~PATTERN
|
2024-07-13 16:12:30 -04:00
|
|
|
(send (const {nil? cbase} :FileUtils) {:rm_rf :rm_f :rmtree} ...)
|
2024-07-13 15:35:06 -04:00
|
|
|
PATTERN
|
|
|
|
|
2024-07-13 22:13:03 -04:00
|
|
|
def_node_matcher :pathname_rmtree?, <<~PATTERN
|
|
|
|
(send (const {nil? cbase} :Pathname) :rmtree ...)
|
|
|
|
PATTERN
|
|
|
|
|
2024-07-13 15:35:06 -04:00
|
|
|
def on_send(node)
|
2024-07-13 22:13:03 -04:00
|
|
|
return if neither_rm_rf_nor_rmtree?(node)
|
2024-07-13 15:35:06 -04:00
|
|
|
|
|
|
|
add_offense(node) do |corrector|
|
2024-07-13 16:12:30 -04:00
|
|
|
new_method = if node.method?(:rm_rf) || node.method?(:rmtree)
|
|
|
|
"rm_r"
|
|
|
|
else
|
|
|
|
"rm"
|
|
|
|
end
|
2024-07-13 22:13:03 -04:00
|
|
|
|
2024-07-13 16:01:25 -04:00
|
|
|
corrector.replace(node.loc.expression, "FileUtils.#{new_method}(#{node.arguments.first.source})")
|
2024-07-13 15:35:06 -04:00
|
|
|
end
|
|
|
|
end
|
2024-07-13 22:13:03 -04:00
|
|
|
|
|
|
|
def neither_rm_rf_nor_rmtree?(node)
|
|
|
|
!fileutils_rm_r_f?(node) && !pathname_rmtree?(node)
|
|
|
|
end
|
2024-07-13 15:35:06 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|