Skip to content

Commit

Permalink
[Fix rubocop#7569] Make Style/YodaCondition accept __FILE__ == $0
Browse files Browse the repository at this point in the history
Fixes rubocop#7569.

This PR makes `Style/YodaCondition` cop accept `__FILE__ == $0`

I think that both operands `__FILE__ == $0` can be assumed to be
read-only, as mentioned in rubocop#7569. If users try to assign `__FILE__`,
an error will occur. Also, it is not usually assigned to `$0` by users.

Therefore, this PR will make `Style/YodaCondition` cop accept both
`__FILE__` and `$0` on the left side.

Also, this PR will change only an idiom `__FILE__ == $0`.
  • Loading branch information
koic committed Dec 25, 2019
1 parent c66efb9 commit 098c722
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@

* [#7193](https://github.com/rubocop-hq/rubocop/issues/7193): Prevent `Style/PercentLiteralDelimiters` from changing `%i` literals that contain escaped delimiters. ([@buehmann][])
* [#7590](https://github.com/rubocop-hq/rubocop/issues/7590): Fix an error for `Layout/SpaceBeforeBlockBraces` when using with `EnforcedStyle: line_count_based` of `Style/BlockDelimiters` cop. ([@koic][])
* [#7569](https://github.com/rubocop-hq/rubocop/issues/7569): Make `Style/YodaCondition` accept `__FILE__ == $0`. ([@koic][])

## 0.78.0 (2019-12-18)

Expand Down
17 changes: 16 additions & 1 deletion lib/rubocop/cop/style/yoda_condition.rb
Expand Up @@ -67,9 +67,16 @@ class YodaCondition < Cop

NONCOMMUTATIVE_OPERATORS = %i[===].freeze

PROGRAM_NAMES = %i[$0 $PROGRAM_NAME].freeze

def_node_matcher :file_constant_equal_program_name?, <<~PATTERN
(send #source_file_path_constant? {:== :!=} (gvar #program_name?))
PATTERN

def on_send(node)
return unless yoda_compatible_condition?(node)
return if equality_only? && non_equality_operator?(node)
return if equality_only? && non_equality_operator?(node) ||
file_constant_equal_program_name?(node)

valid_yoda?(node) || add_offense(node)
end
Expand Down Expand Up @@ -135,6 +142,14 @@ def non_equality_operator?(node)
def noncommutative_operator?(node)
NONCOMMUTATIVE_OPERATORS.include?(node.method_name)
end

def source_file_path_constant?(node)
node.source == '__FILE__'
end

def program_name?(name)
PROGRAM_NAMES.include?(name)
end
end
end
end
Expand Down
4 changes: 4 additions & 0 deletions spec/rubocop/cop/style/yoda_condition_spec.rb
Expand Up @@ -55,6 +55,10 @@
it_behaves_like 'accepts', 'not true'
it_behaves_like 'accepts', '0 <=> val'
it_behaves_like 'accepts', '"foo" === bar'
it_behaves_like 'accepts', '__FILE__ == $0'
it_behaves_like 'accepts', '__FILE__ != $0'
it_behaves_like 'accepts', '__FILE__ == $PROGRAM_NAME'
it_behaves_like 'accepts', '__FILE__ != $PROGRAM_NAME'

it_behaves_like 'offense', '"foo" == bar'
it_behaves_like 'offense', 'nil == bar'
Expand Down

0 comments on commit 098c722

Please sign in to comment.