123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::NonAtomicFileOperation

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/lint/non_atomic_file_operation.rb

Overview

Checks for non-atomic file operation. And then replace it with a nearly equivalent and atomic method.

These can cause problems that are difficult to reproduce, especially in cases of frequent file operations in parallel, such as test runs with parallel_rspec.

For examples: creating a directory if there is none, has the following problems

An exception occurs when the directory didn’t exist at the time of exist?, but someone else created it before mkdir was executed.

Subsequent processes are executed without the directory that should be there when the directory existed at the time of exist?, but someone else deleted it shortly afterwards.

Examples:

# bad - race condition with another process may result in an error in {mkdir}
unless Dir.exist?(path)
  FileUtils.mkdir(path)
end

# good - atomic and idempotent creation
FileUtils.mkdir_p(path)

# bad - race condition with another process may result in an error in {remove}
if File.exist?(path)
  FileUtils.remove(path)
end

# good - atomic and idempotent removal
FileUtils.rm_f(path)

Cop Safety Information:

  • This cop is unsafe, because autocorrection change to atomic processing. The atomic processing of the replacement destination is not guaranteed to be strictly equivalent to that before the replacement.

Constant Summary

::RuboCop::Cop::Base - Inherited

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

::RuboCop::Cop::Base - Inherited

::RuboCop::Cop::AutocorrectLogic - Included

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?,
#skipped_unsafe_correction_with_disable_uncorrectable?

Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while --disable-uncorrectable asks for a todo comment on everything this run cannot correct.

#contextual_autocorrect_held_back?

When LSP is enabled or the --editor-mode option is on, it is considered as editing source code, and autocorrection with AutoCorrect: contextual will not be performed.

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos

rubocop:disable-next Metrics/ParameterLists.

#move_pos, #move_pos_str, #range_between, #range_by_whole_lines,
#range_for_statement_removal

Returns the range to remove a statement: its whole lines, including a trailing comment and the final newline, when no other code shares them, and otherwise the range itself with the spaces after it.

#range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed

 — grouped under the Commissioner heading above.

#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#file_independent_relevance

Whether relevant_file? has the same answer for every file: true or false when it does, and nil when the answer depends on the file.

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing The source is parsed the way the file under investigation was.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked).

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 81

def self.autocorrect_incompatible_with
  [Style::MethodCallWithArgsParentheses]
end

Instance Method Details

#allowable_use_with_if?(if_node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 103

def allowable_use_with_if?(if_node)
  if_node.condition.operator_keyword? || if_node.else_branch
end

#autocorrect(corrector, node, range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 156

def autocorrect(corrector, node, range)
  if_node = node.parent

  corrector.remove(condition_range(if_node, range))
  autocorrect_replace_method(corrector, node)

  if if_node.modifier_form?
    corrector.remove(node.source_range.end.join(if_node.loc.keyword.begin))
  else
    corrector.remove(end_keyword_range(node))
  end
end

#autocorrect_replace_method(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 182

def autocorrect_replace_method(corrector, node)
  return if force_method?(node)

  corrector.replace(node.child_nodes.first.loc.name, 'FileUtils')
  corrector.replace(node.loc.selector, replacement_method(node))
  corrector.insert_before(node.last_argument, 'mode: ') if require_mode_keyword?(node)
end

#autocorrectable?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 128

def autocorrectable?(node)
  parent = node.parent
  return false if parent.elsif?
  return true if parent.modifier_form?
  return true unless code_after_end?(parent)
  return false if !node.parenthesized? || last_heredoc_end_pos(node)

  !processed_source.contains_comment?(body_to_end_range(node))
end

#body_to_end_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 144

def body_to_end_range(node)
  begin_pos = [node.source_range.end_pos, last_heredoc_end_pos(node)].compact.max

  range_between(begin_pos, node.parent.loc.end.end_pos)
end

#code_after_end?(if_node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 138

def code_after_end?(if_node)
  end_keyword = if_node.loc.end

  !end_keyword.source_line[end_keyword.last_column..].match?(/\A\s*(?:#|\z)/)
end

#condition_range(if_node, range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 169

def condition_range(if_node, range)
  return range unless (separator = if_node.loc.begin)

  range.join(separator)
end

#end_keyword_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 175

def end_keyword_range(node)
  range = body_to_end_range(node)
  return node.parent.loc.end if processed_source.contains_comment?(range)

  range
end

#explicit_not_force?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 77

def_node_search :explicit_not_force?, <<~PATTERN
  (pair (sym :force) (:false))
PATTERN

#force?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 72

def_node_search :force?, <<~PATTERN
  (pair (sym :force) (:true))
PATTERN

#force_method?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 202

def force_method?(node)
  force_method_name?(node) || force_option?(node)
end

#force_method_name?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 216

def force_method_name?(node)
  (MAKE_FORCE_METHODS + REMOVE_FORCE_METHODS).include?(node.method_name)
end

#force_option?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 212

def force_option?(node)
  node.arguments.any? { |arg| force?(arg) }
end

#if_node_child?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 97

def if_node_child?(node)
  return false unless (parent = node.parent)

  parent.if_type? && !allowable_use_with_if?(parent)
end

#last_heredoc_end_pos(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 150

def last_heredoc_end_pos(node)
  node.each_descendant(:any_str).select(&:heredoc?).map do |heredoc|
    heredoc.loc.heredoc_end.end_pos
  end.max
end

#message_change_force_method(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 118

def message_change_force_method(node)
  format(MSG_CHANGE_FORCE_METHOD, method_name: replacement_method(node))
end

#message_remove_file_exist_check(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 122

def message_remove_file_exist_check(node)
  receiver, method_name = receiver_and_method_name(node)

  format(MSG_REMOVE_FILE_EXIST_CHECK, receiver: receiver, method_name: method_name)
end

#on_send(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 85

def on_send(node)
  return unless node.receiver&.const_type?
  return unless if_node_child?(node)
  return if explicit_not_force?(node)
  return unless (exist_node = send_exist_node(node.parent).first)
  return unless exist_node.first_argument == node.first_argument

  register_offense(node, exist_node)
end

#receiver_and_method_name(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 67

def_node_matcher :receiver_and_method_name, <<~PATTERN
  (send (const {cbase nil?} $_) $_ ...)
PATTERN

#register_offense(node, exist_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 107

def register_offense(node, exist_node)
  add_offense(node, message: message_change_force_method(node)) unless force_method?(node)

  parent = node.parent
  range = parent.loc.keyword.begin.join(parent.condition.source_range.end)

  add_offense(range, message: message_remove_file_exist_check(exist_node)) do |corrector|
    autocorrect(corrector, node, range) if autocorrectable?(node)
  end
end

#replacement_method(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 190

def replacement_method(node)
  if MAKE_METHODS.include?(node.method_name)
    'mkdir_p'
  elsif REMOVE_METHODS.include?(node.method_name)
    'rm_f'
  elsif RECURSIVE_REMOVE_METHODS.include?(node.method_name)
    'rm_rf'
  else
    node.method_name
  end
end

#require_mode_keyword?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 206

def require_mode_keyword?(node)
  return false unless node.receiver.const_name == 'Dir'

  replacement_method(node) == 'mkdir_p' && node.arguments.length == 2
end

#send_exist_node(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/non_atomic_file_operation.rb', line 62

def_node_search :send_exist_node, <<~PATTERN
  $(send (const {cbase nil?} {:FileTest :File :Dir :Shell}) {:exist? :exists?} ...)
PATTERN