Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #10786] Fix a false positive for Lint/NonAtomicFileOperation #10787

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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