Skip to content

Commit

Permalink
Add FileUtils methods detection to Dir::Chdir cop
Browse files Browse the repository at this point in the history
  • Loading branch information
viralpraxis committed Sep 19, 2024
1 parent 489ebd2 commit b400726
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/rubocop/cop/thread_safety/dir_chdir.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,28 @@ module ThreadSafety
# @example
# # bad
# Dir.chdir("/var/run")
#
# # bad
# FileUtils.chdir("/var/run")
class DirChdir < Base
MSG = 'Avoid using `Dir.chdir` due to its process-wide effect.'
RESTRICT_ON_SEND = %i[chdir].freeze
MESSAGE = 'Avoid using `%<module>s.%<method>s` due to its process-wide effect.'
RESTRICT_ON_SEND = %i[chdir cd].freeze

# @!method dir_chdir?(node)
def_node_matcher :dir_chdir?, <<~MATCHER
(send (const {nil? cbase} :Dir) :chdir ...)
# @!method chdir?(node)
def_node_matcher :chdir?, <<~MATCHER
{
(send (const {nil? cbase} {:Dir :FileUtils}) :chdir ...)
(send (const {nil? cbase} :FileUtils) :cd ...)
}
MATCHER

def on_send(node)
dir_chdir?(node) { add_offense(node) }
chdir?(node) do
add_offense(
node,
message: format(MESSAGE, module: node.receiver.short_name, method: node.method_name)
)
end
end
end
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/thread_safety/dir_chdir_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@
end
end

context 'with `FileUtils.chdir` method' do
let(:msg) { 'Avoid using `FileUtils.chdir` due to its process-wide effect.' }

it 'registers an offense' do
expect_offense(<<~RUBY)
FileUtils.chdir("/var/run")
^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end
end

context 'with `FileUtils.cd` method' do
let(:msg) { 'Avoid using `FileUtils.cd` due to its process-wide effect.' }

it 'registers an offense' do
expect_offense(<<~RUBY)
FileUtils.cd("/var/run")
^^^^^^^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end
end

context 'with another `Dir` class method' do
it 'does not register an offense' do
expect_no_offenses 'Dir.pwd'
Expand Down

0 comments on commit b400726

Please sign in to comment.