From 6a3fab220f8bccdab509dc7026ace11c9abc913b Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Fri, 4 Sep 2020 11:59:21 -0400 Subject: [PATCH] [Fix #8642] Fix a false negative for `Style/SpaceInsideHashLiteralBraces` when a correct empty hash precedes the incorrect hash. --- CHANGELOG.md | 1 + .../layout/space_inside_hash_literal_braces.rb | 5 ++--- .../space_inside_hash_literal_braces_spec.rb | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4415212083f..81f6bdfd083 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ * [#8671](https://github.com/rubocop-hq/rubocop/issues/8671): Fix an error for `Style/ExplicitBlockArgument` when using safe navigation method call. ([@koic][]) * [#8682](https://github.com/rubocop-hq/rubocop/pull/8682): Fix a positive for `Style/HashTransformKeys` and `Style/HashTransformValues` when the `each_with_object` hash is used in the transformed key or value. ([@eugeneius][]) * [#8688](https://github.com/rubocop-hq/rubocop/issues/8688): Mark `Style/GlobalStdStream` as unsafe autocorrection. ([@marcandre][]) +* [#8642](https://github.com/rubocop-hq/rubocop/issues/8642): Fix a false negative for `Style/SpaceInsideHashLiteralBraces` when a correct empty hash precedes the incorrect hash. ([@dvandersluis][]) ### Changes diff --git a/lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb b/lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb index 93d309037ae..06841857b24 100644 --- a/lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb +++ b/lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb @@ -126,12 +126,11 @@ def expect_space?(token1, token2) def incorrect_style_detected(token1, token2, expect_space, is_empty_braces) + return unless ambiguous_or_unexpected_style_detected(style, token1.text == token2.text) + brace = (token1.text == '{' ? token1 : token2).pos range = expect_space ? brace : space_range(brace) - style = expect_space ? :no_space : :space - return unless ambiguous_or_unexpected_style_detected(style, token1.text == token2.text) - add_offense(range, message: message(brace, is_empty_braces, expect_space)) do |corrector| autocorrect(corrector, range) end diff --git a/spec/rubocop/cop/layout/space_inside_hash_literal_braces_spec.rb b/spec/rubocop/cop/layout/space_inside_hash_literal_braces_spec.rb index 4e62378ad1b..a9380d79d59 100644 --- a/spec/rubocop/cop/layout/space_inside_hash_literal_braces_spec.rb +++ b/spec/rubocop/cop/layout/space_inside_hash_literal_braces_spec.rb @@ -216,4 +216,21 @@ expect_no_offenses('{ key: "{" }') end end + + context 'offending hash following empty hash' do + # regression test; see GH issue 8642 + it 'registers an offense on both sides' do + expect_offense(<<~RUBY) + {} + {key: 1} + ^ Space inside { missing. + ^ Space inside } missing. + RUBY + + expect_correction(<<~RUBY) + {} + { key: 1 } + RUBY + end + end end