diff --git a/CHANGELOG.md b/CHANGELOG.md index 919ef0736dc..b57a4cbf043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/rubocop/cop/style/yoda_condition.rb b/lib/rubocop/cop/style/yoda_condition.rb index 2bc4f238e57..00640b05a01 100644 --- a/lib/rubocop/cop/style/yoda_condition.rb +++ b/lib/rubocop/cop/style/yoda_condition.rb @@ -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 @@ -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 diff --git a/spec/rubocop/cop/style/yoda_condition_spec.rb b/spec/rubocop/cop/style/yoda_condition_spec.rb index f4745fe0a61..c2c58cf1bec 100644 --- a/spec/rubocop/cop/style/yoda_condition_spec.rb +++ b/spec/rubocop/cop/style/yoda_condition_spec.rb @@ -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'