Class: RuboCop::Cop::ThreadSafety::DirChdir

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/thread_safety/dir_chdir.rb

Overview

Avoid using ‘Dir.chdir` due to its process-wide effect. If `AllowCallWithBlock` (disabled by default) option is enabled, calling `Dir.chdir` with block will be allowed.

Examples:

# bad
Dir.chdir("/var/run")

# bad
FileUtils.chdir("/var/run")

AllowCallWithBlock: false (default)

# good
Dir.chdir("/var/run") do
  puts Dir.pwd
end

AllowCallWithBlock: true

# bad
Dir.chdir("/var/run") do
  puts Dir.pwd
end

Constant Summary collapse

MESSAGE =
'Avoid using `%<module>s%<dot>s%<method>s` due to its process-wide effect.'
RESTRICT_ON_SEND =
%i[chdir cd].freeze

Instance Method Summary collapse

Instance Method Details

#chdir?(node) ⇒ Object



34
35
36
37
38
39
# File 'lib/rubocop/cop/thread_safety/dir_chdir.rb', line 34

def_node_matcher :chdir?, <<~MATCHER
  {
    (call (const {nil? cbase} {:Dir :FileUtils}) :chdir ...)
    (call (const {nil? cbase} :FileUtils) :cd ...)
  }
MATCHER

#on_send(node) ⇒ Object Also known as: on_csend



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubocop/cop/thread_safety/dir_chdir.rb', line 41

def on_send(node)
  return unless chdir?(node)
  return if allow_call_with_block? && (node.block_argument? || node.parent&.block_type?)

  add_offense(
    node,
    message: format(
      MESSAGE,
      module: node.receiver.short_name,
      method: node.method_name,
      dot: node.loc.dot.source
    )
  )
end