From 0b350b196ffc46fc511cc9a3c160e0689e30dbff Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Tue, 26 Apr 2022 11:50:41 +0900 Subject: [PATCH] [Fix #10581] Fix a false positive for `Style/FetchEnvVar` 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). --- ..._false_positive_for_style_fetch_env_var_cop.md | 1 + lib/rubocop/cop/style/fetch_env_var.rb | 3 ++- spec/rubocop/cop/style/fetch_env_var_spec.rb | 15 +++++++++------ 3 files changed, 12 insertions(+), 7 deletions(-) create mode 100644 changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md diff --git a/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md b/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md new file mode 100644 index 00000000000..632bd0b8c08 --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_fetch_env_var_cop.md @@ -0,0 +1 @@ +* [#10581](https://github.com/rubocop/rubocop/issues/10581): Fix a false positive for `Style/FetchEnvVar` when comparing with `ENV['TERM']`. ([@koic][]) diff --git a/lib/rubocop/cop/style/fetch_env_var.rb b/lib/rubocop/cop/style/fetch_env_var.rb index 9ed2886883f..258ccb1c114 100644 --- a/lib/rubocop/cop/style/fetch_env_var.rb +++ b/lib/rubocop/cop/style/fetch_env_var.rb @@ -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. diff --git a/spec/rubocop/cop/style/fetch_env_var_spec.rb b/spec/rubocop/cop/style/fetch_env_var_spec.rb index be82c930898..8f98e7ae43e 100644 --- a/spec/rubocop/cop/style/fetch_env_var_spec.rb +++ b/spec/rubocop/cop/style/fetch_env_var_spec.rb @@ -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