From b0eb6d76b0e4a935c4896f3aadbb90066f7b16bb Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 12 May 2022 00:16:13 +0900 Subject: [PATCH] [Fix #10622] Fix a false positive for `Style/RaiseArgs` Fixes #10622. This PR fixes a false positive for `Style/RaiseArgs` when error type class constructor with keyword arguments and message argument. The signature of `raise` is below. ```ruby raise raise(string, cause: $!) raise(exception [, string [, array]], cause: $!) ``` https://ruby-doc.org/core-3.1.0/Kernel.html#method-i-raise So #10622 would be a false positive because `raise MyError.new(data: 'mydata'), 'message'` and `raise MyError.new('message', data: 'mydata')` are incompatible. --- changelog/fix_a_false_positive_for_style_raise_args.md | 1 + lib/rubocop/cop/style/raise_args.rb | 3 +++ spec/rubocop/cop/style/raise_args_spec.rb | 4 ++++ 3 files changed, 8 insertions(+) create mode 100644 changelog/fix_a_false_positive_for_style_raise_args.md diff --git a/changelog/fix_a_false_positive_for_style_raise_args.md b/changelog/fix_a_false_positive_for_style_raise_args.md new file mode 100644 index 00000000000..a37dfa58417 --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_raise_args.md @@ -0,0 +1 @@ +* [#10622](https://github.com/rubocop/rubocop/issues/10622): Fix a false positive for `Style/RaiseArgs` when error type class constructor with keyword arguments and message argument. ([@koic][]) diff --git a/lib/rubocop/cop/style/raise_args.rb b/lib/rubocop/cop/style/raise_args.rb index 872eb8a8075..40a54876473 100644 --- a/lib/rubocop/cop/style/raise_args.rb +++ b/lib/rubocop/cop/style/raise_args.rb @@ -91,6 +91,9 @@ def correction_exploded_to_compact(node) def check_compact(node) if node.arguments.size > 1 + exception = node.first_argument + return if exception.send_type? && exception.first_argument&.hash_type? + add_offense(node, message: format(COMPACT_MSG, method: node.method_name)) do |corrector| replacement = correction_exploded_to_compact(node) diff --git a/spec/rubocop/cop/style/raise_args_spec.rb b/spec/rubocop/cop/style/raise_args_spec.rb index d199905d4bb..669b3f0c79f 100644 --- a/spec/rubocop/cop/style/raise_args_spec.rb +++ b/spec/rubocop/cop/style/raise_args_spec.rb @@ -145,6 +145,10 @@ it 'accepts a raise with an exception argument' do expect_no_offenses('raise Ex.new(msg)') end + + it 'accepts exception constructor with keyword arguments and message argument' do + expect_no_offenses('raise MyKwArgError.new(a: 1, b: 2), message') + end end context 'when enforced style is exploded' do