From b2dcb10a218b0f4c1bfaeef46314f4c2b889b5d3 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 11 Jun 2021 02:51:00 +0900 Subject: [PATCH] Fix an incorrect auto-correct for `Layout/DotPosition` This PR fixes the following incorrect auto-correct for `Layout/DotPosition` when using only dot line. ```console % cat example.rb foo .bar . baz % rubocop --only Layout/DotPosition -a (snip) Inspecting 1 file C Offenses: example.rb:3:3: C: [Corrected] Layout/DotPosition: Place the . on the next line, together with the method name. . ^ 1 file inspected, 1 offense detected, 1 offense corrected ``` ## Before ```consle % cat example.rb foo .bar .baz % ruby -c example.rb example.rb:4: syntax error, unexpected '.', expecting end-of-input .baz ``` ## After ```console % cat example.rb foo .bar .baz % ruby -c example.rb Syntax OK ``` --- ...orrect_autocorrect_for_layout_dot_position.md | 1 + lib/rubocop/cop/layout/dot_position.rb | 8 +++++++- spec/rubocop/cop/layout/dot_position_spec.rb | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_incorrect_autocorrect_for_layout_dot_position.md diff --git a/changelog/fix_incorrect_autocorrect_for_layout_dot_position.md b/changelog/fix_incorrect_autocorrect_for_layout_dot_position.md new file mode 100644 index 00000000000..d2bece3e7ce --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_layout_dot_position.md @@ -0,0 +1 @@ +* [#9867](https://github.com/rubocop/rubocop/pull/9867): Fix an incorrect auto-correct for `Layout/DotPosition` when using only dot line. ([@koic][]) diff --git a/lib/rubocop/cop/layout/dot_position.rb b/lib/rubocop/cop/layout/dot_position.rb index adbb7344b20..61ebc38914e 100644 --- a/lib/rubocop/cop/layout/dot_position.rb +++ b/lib/rubocop/cop/layout/dot_position.rb @@ -24,6 +24,7 @@ module Layout # method class DotPosition < Base include ConfigurableEnforcedStyle + include RangeHelp extend AutoCorrector def on_send(node) @@ -42,7 +43,12 @@ def on_send(node) private def autocorrect(corrector, dot, node) - corrector.remove(dot) + dot_range = if processed_source[dot.line - 1].strip == '.' + range_by_whole_lines(dot, include_final_newline: true) + else + dot + end + corrector.remove(dot_range) case style when :leading corrector.insert_before(selector_range(node), dot.source) diff --git a/spec/rubocop/cop/layout/dot_position_spec.rb b/spec/rubocop/cop/layout/dot_position_spec.rb index b137b270cc6..e6c012f09ee 100644 --- a/spec/rubocop/cop/layout/dot_position_spec.rb +++ b/spec/rubocop/cop/layout/dot_position_spec.rb @@ -34,6 +34,22 @@ RUBY end + it 'registers an offense for only dot line' do + expect_offense(<<~RUBY) + foo + .bar + . + ^ Place the . on the next line, together with the method name. + baz + RUBY + + expect_correction(<<~RUBY) + foo + .bar + .baz + RUBY + end + it 'accepts leading do in multi-line method call' do expect_no_offenses(<<~RUBY) something