Skip to content

Commit

Permalink
[Fix rubocop#10786] Fix a false positive for `Lint/NonAtomicFileOpera…
Browse files Browse the repository at this point in the history
…tion`

Fixes rubocop#10786.

This PR fixes a false positive for `Lint/NonAtomicFileOperation`
when using complex conditional.
  • Loading branch information
koic committed Jul 5, 2022
1 parent 9577173 commit da7ff7d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
@@ -0,0 +1 @@
* [#10786](https://github.com/rubocop/rubocop/issues/10786): Fix a false positive for `Lint/NonAtomicFileOperation` when using complex conditional. ([@koic][])
14 changes: 9 additions & 5 deletions lib/rubocop/cop/lint/non_atomic_file_operation.rb
Expand Up @@ -71,18 +71,22 @@ class NonAtomicFileOperation < Base
PATTERN

def on_send(node)
return unless node.parent&.if_type?
return if node.parent.else_branch
return unless (parent = node.parent) && parent.if_type?
return if allowable_use_with_if?(parent)
return if explicit_not_force?(node)
return unless (exist_node = send_exist_node(node.parent).first)
return unless (exist_node = send_exist_node(parent).first)
return unless exist_node.first_argument == node.first_argument

offense(node, exist_node)
register_offense(node, exist_node)
end

private

def offense(node, exist_node)
def allowable_use_with_if?(if_node)
if_node.condition.and_type? || if_node.condition.or_type? || if_node.else_branch
end

def register_offense(node, exist_node)
range = range_between(node.parent.loc.keyword.begin_pos,
exist_node.loc.expression.end_pos)

Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb
Expand Up @@ -183,4 +183,20 @@
end
RUBY
end

it 'does not register an offense when using complex conditional with `&&`' do
expect_no_offenses(<<~RUBY)
if FileTest.exist?(path) && File.stat(path).socket?
FileUtils.mkdir(path)
end
RUBY
end

it 'does not register an offense when using complex conditional with `||`' do
expect_no_offenses(<<~RUBY)
if FileTest.exist?(path) || condition
FileUtils.mkdir(path)
end
RUBY
end
end

0 comments on commit da7ff7d

Please sign in to comment.