From 91fc1beed7b9eac6b577a4598aa98226175b8347 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Tue, 9 May 2023 13:47:53 +0900 Subject: [PATCH] [Fix #11862] Fix an incorrect autocorrect for `Style/GuardClause` Fixes #11862. This PR fixes an incorrect autocorrect for `Style/GuardClause` when using `raise` in `else` branch in a one-liner with `then`. --- ...n_incorrect_autocorrect_for_style_guard_clause.md | 1 + lib/rubocop/cop/style/guard_clause.rb | 2 ++ spec/rubocop/cop/style/guard_clause_spec.rb | 12 ++++++++++++ 3 files changed, 15 insertions(+) create mode 100644 changelog/fix_an_incorrect_autocorrect_for_style_guard_clause.md diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_guard_clause.md b/changelog/fix_an_incorrect_autocorrect_for_style_guard_clause.md new file mode 100644 index 00000000000..885708c1e1a --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_guard_clause.md @@ -0,0 +1 @@ +* [#11862](https://github.com/rubocop/rubocop/issues/11862): Fix an incorrect autocorrect for `Style/GuardClause` when using `raise` in `else` branch in a one-liner with `then`. ([@koic][]) diff --git a/lib/rubocop/cop/style/guard_clause.rb b/lib/rubocop/cop/style/guard_clause.rb index c637682a384..ab380992a4f 100644 --- a/lib/rubocop/cop/style/guard_clause.rb +++ b/lib/rubocop/cop/style/guard_clause.rb @@ -187,6 +187,8 @@ def autocorrect(corrector, node, condition, replacement, guard) if_branch = node.if_branch else_branch = node.else_branch + corrector.replace(node.loc.begin, "\n") if node.loc.begin&.is?('then') + if if_branch&.send_type? && heredoc?(if_branch.last_argument) autocorrect_heredoc_argument(corrector, node, if_branch, else_branch, guard) elsif else_branch&.send_type? && heredoc?(else_branch.last_argument) diff --git a/spec/rubocop/cop/style/guard_clause_spec.rb b/spec/rubocop/cop/style/guard_clause_spec.rb index a14ef48f40b..4b317e71a01 100644 --- a/spec/rubocop/cop/style/guard_clause_spec.rb +++ b/spec/rubocop/cop/style/guard_clause_spec.rb @@ -165,6 +165,18 @@ def func expect_no_corrections end + it 'registers an offense when using `raise` in `else` branch in a one-liner with `then`' do + expect_offense(<<~RUBY) + if something then work else raise('message') end + ^^ Use a guard clause (`raise('message') unless something`) instead of wrapping the code inside a conditional expression. + RUBY + + expect_correction(<<~RUBY) + raise('message') unless something#{trailing_whitespace} + work#{trailing_whitespace * 3} + RUBY + end + it 'registers an offense when using `and return` in `then` branch' do expect_offense(<<~RUBY) def func