Skip to content

Commit

Permalink
[Fix #10581] Fix a false positive for Style/FetchEnvVar
Browse files Browse the repository at this point in the history
Fixes #10581.

This PR fixes a false positive for `Style/FetchEnvVar` when comparing with `ENV['TERM']`.
`ENV['DISABLE_DOTENV'] != '1'` could be treated the same as the already allowed in `used_as_flag?`
(that is, used as a flag).
  • Loading branch information
koic committed Apr 26, 2022
1 parent 3679375 commit 0b350b1
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10581](https://github.com/rubocop/rubocop/issues/10581): Fix a false positive for `Style/FetchEnvVar` when comparing with `ENV['TERM']`. ([@koic][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/style/fetch_env_var.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ def allowed_var?(expression)

def used_as_flag?(node)
return false if node.root?
return true if node.parent.if_type?

node.parent.if_type? || (node.parent.send_type? && node.parent.prefix_bang?)
node.parent.send_type? && (node.parent.prefix_bang? || node.parent.comparison_method?)
end

# Check if the node is a receiver and receives a message with dot syntax.
Expand Down
15 changes: 9 additions & 6 deletions spec/rubocop/cop/style/fetch_env_var_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,18 @@
end
end

context 'when it is compared with other object' do
it 'registers an offense' do
expect_offense(<<~RUBY)
context 'when it is compared `==` with other object' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] == 1
^^^^^^^^ Use `ENV.fetch('X')` or `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
end
end

expect_correction(<<~RUBY)
ENV.fetch('X', nil) == 1
context 'when it is compared `!=` with other object' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] != 1
RUBY
end
end
Expand Down

0 comments on commit 0b350b1

Please sign in to comment.