Skip to content

Commit

Permalink
Fix a false positive for Style/FetchEnvVar in the body with assignm…
Browse files Browse the repository at this point in the history
…ent method
  • Loading branch information
ydah authored and bbatsov committed May 29, 2022
1 parent 14ae24b commit 9476274
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_fetch_env_var.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10670](https://github.com/rubocop/rubocop/pull/10670): Fix a false positive for `Style/FetchEnvVar` in the body with assignment method. ([@ydah][])
11 changes: 9 additions & 2 deletions lib/rubocop/cop/style/fetch_env_var.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,20 @@ def used_if_condition_in_body(node)
end

def used_in_condition?(node, condition)
if condition.send_type? && (!condition.comparison_method? && !condition.predicate_method?)
return false
if condition.send_type?
return true if condition.assignment_method? && partial_matched?(node, condition)
return false if !condition.comparison_method? && !condition.predicate_method?
end

condition.child_nodes.any?(node)
end

# Avoid offending in the following cases:
# `ENV['key'] if ENV['key'] = x`
def partial_matched?(node, condition)
node.child_nodes == node.child_nodes & condition.child_nodes
end

def offensive?(node)
!(allowed_var?(node) || allowable_use?(node))
end
Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/style/fetch_env_var_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,29 @@
end
RUBY
end

it 'registers no offenses when using the same `ENV` var as `if` condition in the body with assignment method' do
expect_no_offenses(<<~RUBY)
if ENV['X'] = x
puts ENV['X']
end
RUBY
end

it 'registers an offense with using an `ENV` var as `if` condition in the body with assignment method' do
expect_offense(<<~RUBY)
if ENV['X'] = x
puts ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y')` or `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
end
RUBY

expect_correction(<<~RUBY)
if ENV['X'] = x
puts ENV.fetch('Y', nil)
end
RUBY
end
end

it 'registers an offense when using `ENV && x` that is different from `if` condition in the body' do
Expand Down

0 comments on commit 9476274

Please sign in to comment.