diff --git a/changelog/fix_a_false_positive_for_non_atomic_file_operation.md b/changelog/fix_a_false_positive_for_non_atomic_file_operation.md new file mode 100644 index 00000000000..24730dfdcf8 --- /dev/null +++ b/changelog/fix_a_false_positive_for_non_atomic_file_operation.md @@ -0,0 +1 @@ +* [#10760](https://github.com/rubocop/rubocop/issues/10760): Fix a false positive for `Lint/NonAtomicFileOperation` when using `FileTest.exist?` with `if` condition that has `else` branch. ([@koic][]) diff --git a/lib/rubocop/cop/lint/non_atomic_file_operation.rb b/lib/rubocop/cop/lint/non_atomic_file_operation.rb index bae3b2accf7..9aad8addc21 100644 --- a/lib/rubocop/cop/lint/non_atomic_file_operation.rb +++ b/lib/rubocop/cop/lint/non_atomic_file_operation.rb @@ -72,6 +72,7 @@ class NonAtomicFileOperation < Base def on_send(node) return unless node.parent&.if_type? + return if node.parent.else_branch 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 diff --git a/spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb b/spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb index 5fa6a9381af..0d1f09b236e 100644 --- a/spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb +++ b/spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb @@ -173,4 +173,14 @@ end RUBY end + + it 'does not register an offense when using `FileTest.exist?` with `if` condition that has `else` branch' do + expect_no_offenses(<<~RUBY) + if FileTest.exist?(path) + FileUtils.mkdir(path) + else + do_something + end + RUBY + end end