From b37720da8b437f3de62eab9ee3ad415cc7aee217 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 1 Apr 2021 01:47:09 +0900 Subject: [PATCH] Fix a false negative for `Layout/IndentationWidth` This PR fixes a false negative for `Layout/IndentationWidth` when using `ensure` in `do` ... `end` block --- ...e_negative_for_layout_indentation_width.md | 1 + lib/rubocop/cop/layout/indentation_width.rb | 7 +++++-- .../cop/layout/indentation_width_spec.rb | 21 +++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_false_negative_for_layout_indentation_width.md diff --git a/changelog/fix_false_negative_for_layout_indentation_width.md b/changelog/fix_false_negative_for_layout_indentation_width.md new file mode 100644 index 00000000000..20b2c13f5ea --- /dev/null +++ b/changelog/fix_false_negative_for_layout_indentation_width.md @@ -0,0 +1 @@ +* [#9791](https://github.com/rubocop/rubocop/pull/9791): Fix a false negative for `Layout/IndentationWidth` when using `ensure` in `do` ... `end` block. ([@koic][]) diff --git a/lib/rubocop/cop/layout/indentation_width.rb b/lib/rubocop/cop/layout/indentation_width.rb index 3571ed3b752..5eb5596dc6a 100644 --- a/lib/rubocop/cop/layout/indentation_width.rb +++ b/lib/rubocop/cop/layout/indentation_width.rb @@ -313,9 +313,12 @@ def indentation_to_check?(base_loc, body_node) check_rescue?(body_node) elsif body_node.ensure_type? block_body, = *body_node - return unless block_body - check_rescue?(block_body) if block_body.rescue_type? + if block_body&.rescue_type? + check_rescue?(block_body) + else + !block_body.nil? + end else true end diff --git a/spec/rubocop/cop/layout/indentation_width_spec.rb b/spec/rubocop/cop/layout/indentation_width_spec.rb index e80d8cc21ed..0639a882e6c 100644 --- a/spec/rubocop/cop/layout/indentation_width_spec.rb +++ b/spec/rubocop/cop/layout/indentation_width_spec.rb @@ -1437,6 +1437,27 @@ def bar RUBY end + it 'does not register an offense for good indentation of `do` ... `ensure` ... `end` block' do + expect_no_offenses(<<~RUBY) + do_something do + foo + ensure + handle_error + end + RUBY + end + + it 'registers an offense for bad indentation of `do` ... `ensure` ... `end` block' do + expect_offense(<<~RUBY) + do_something do + foo + ^^^^ Use 2 (not 4) spaces for indentation. + ensure + handle_error + end + RUBY + end + context 'when using safe navigation operator' do it 'registers an offense for bad indentation of a {} body' do expect_offense(<<~RUBY)