`FileUtils.cd` and `Dir.chdir` cause the working directory to change for the entire process. We run sidekiq jobs, hijacked requests and deferred jobs in threads, which can make working directory changes have unintended side-effects. - Add a rubocop rule to warn about usage of Dir.chdir and FileUtils.cd - Added rubocop:disable for scripts used outside the app - Refactored code using cd to use alternative methods - Temporarily skipped the rubocop check for lib/backup_restore. This will require more complex refactoring, so I will create a separate PR for review
35 lines
856 B
Ruby
35 lines
856 B
Ruby
# frozen_string_literal: true
|
|
|
|
module RuboCop
|
|
module Cop
|
|
module DiscourseCops
|
|
# Avoid using chdir - it is not thread safe.
|
|
#
|
|
# Instead, you may be able to use:
|
|
# Discourse::Utils.execute_command(chdir: 'test') do |runner|
|
|
# runner.exec('pwd')
|
|
# end
|
|
#
|
|
# @example
|
|
# # bad
|
|
# Dir.chdir('test')
|
|
class NoChdir < Cop
|
|
MSG = 'Chdir is not thread safe.'
|
|
|
|
def_node_matcher :using_dir_chdir?, <<-MATCHER
|
|
(send (const nil? :Dir) :chdir ...)
|
|
MATCHER
|
|
|
|
def_node_matcher :using_fileutils_cd?, <<-MATCHER
|
|
(send (const nil? :FileUtils) :cd ...)
|
|
MATCHER
|
|
|
|
def on_send(node)
|
|
return if !(using_dir_chdir?(node) || using_fileutils_cd?(node))
|
|
add_offense(node, message: MSG)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|