Skip to content

Commit

Permalink
[Fix rubocop#10936] Fix an error for Lint/NonAtomicFileOperation
Browse files Browse the repository at this point in the history
Fixes rubocop#10936.

This PR fixes an error for `Lint/NonAtomicFileOperation`
when using `FileTest.exist?` as a condition for `elsif`.
Complex cases such as `if`/`elsif`/`else` don't autocorrect
and respect user changes.
  • Loading branch information
koic committed Aug 19, 2022
1 parent 28a4b67 commit 5e8e462
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
@@ -0,0 +1 @@
* [#10936](https://github.com/rubocop/rubocop/issues/10936): Fix an error for `Lint/NonAtomicFileOperation` when using `FileTest.exist?` as a condition for `elsif`. ([@koic][])
12 changes: 6 additions & 6 deletions lib/rubocop/cop/lint/non_atomic_file_operation.rb
Expand Up @@ -99,19 +99,19 @@ def allowable_use_with_if?(if_node)
end

def register_offense(node, exist_node)
unless force_method?(node)
add_offense(node,
message: format(MSG_CHANGE_FORCE_METHOD,
method_name: replacement_method(node)))
end
add_offense(node, message: message_change_force_method(node)) unless force_method?(node)

range = range_between(node.parent.loc.keyword.begin_pos,
exist_node.loc.expression.end_pos)
add_offense(range, message: message_remove_file_exist_check(exist_node)) do |corrector|
autocorrect(corrector, node, range)
autocorrect(corrector, node, range) unless node.parent.elsif?
end
end

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

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)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb
Expand Up @@ -95,6 +95,19 @@
RUBY
end

it 'registers an offense when using `FileTest.exist?` as a condition for `elsif`' do
expect_offense(<<~RUBY)
if condition
do_something
elsif FileTest.exist?(path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`.
FileUtils.rm_f path
end
RUBY

expect_no_corrections
end

it 'does not register an offense when use `FileTest.exist?` before creating file with an option `force: false`' do
expect_no_offenses(<<~RUBY)
unless FileTest.exists?(path)
Expand Down

0 comments on commit 5e8e462

Please sign in to comment.