From a368ed57ec32ba406b70846d898cbbb48a465acb Mon Sep 17 00:00:00 2001 From: Subramanya-Murugesan Date: Fri, 23 Feb 2024 16:42:42 +0530 Subject: [PATCH] Squashed commit of the following: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commit 2a864701d66808b93d57095a5d2fe503b1b21e4c Author: Koichi ITO Date: Fri Feb 23 19:53:28 2024 +0900 [Docs] Tweak the doc for `Style/ConditionalAssignmentHelper` This PR tweaks the doc for `Style/ConditionalAssignmentHelper`. In #2480, the cop has been updated to also support comparison of variables. commit 1d4303567c58161335bf6729e5e0c3aa4f1e1a6c Author: Koichi ITO Date: Thu Feb 22 19:55:36 2024 +0900 Tweak offense range for `Lint/RedundantSafeNavigation` commit 1666278a8587bb9982fcdb198c1395fd9af93f50 Author: Koichi ITO Date: Wed Feb 21 21:06:30 2024 +0900 Support autocorrect for `InternalAffairs/MethodNameEndWith` commit 876a49d6fb3e0060c734eb40cd6660adf63cf77e Author: Koichi ITO Date: Tue Feb 20 17:33:15 2024 +0900 [Docs] Add `--display-time` to the Basic Usage doc commit 2b013e123485102a790e44fc0b934aae1c625f6a Author: Koichi ITO Date: Sat Feb 17 23:23:41 2024 +0900 Support searching for `rubocop/config.yml` in compliance with dot-config Follow https://github.com/rubocop/rubocop/pull/12700#issuecomment-1949764386 This PR supports searching for `rubocop/config.yml` in compliance with dot-config. This PR adds `project_root/.config/rubocop/config.yml` to the list of paths to search, matching XDG path format of the already targeted `~/.config/rubocop/config.yml`. However, support for `~/.config/rubocop.yml` is not included in this PR, as the outcome of inquiry https://github.com/dot-config/dot-config.github.io/issues/17 regarding it is still pending. commit 4478266e98f326ea36e173977d4e1eb6643371cc Author: Koichi ITO Date: Mon Feb 19 15:55:39 2024 +0900 Fix false positives for `InternalAffairs/MethodNameEndWith` This PR fixes false positives for `InternalAffairs/MethodNameEndWith` when using `method_name` without receiver and resolves the following `rubocop:todo`. ```console $ bundle exec rubocop -a (snip) Offenses: lib/rubocop/cop/naming/predicate_name.rb:102:43: W: [Corrected] Lint/RedundantCopDisableDirective: Unnecessary disabling of InternalAffairs/MethodNameEndWith. method_name.end_with?('=') || # rubocop:todo InternalAffairs/MethodNameEndWith ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/naming/predicate_name.rb:112:61: W: [Corrected] Lint/RedundantCopDisableDirective: Unnecessary disabling of InternalAffairs/MethodNameEndWith. new_name << '?' unless method_name.end_with?('?') # rubocop:todo InternalAffairs/MethodNameEndWith ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` `method_name` without receiver or variable is a string object rather than a node object. commit b5cccc7130920151e120b3a5d9b68ca825a5a8b4 Merge: 974672714 dc74ac8d7 Author: Koichi ITO Date: Sun Feb 18 00:24:58 2024 +0900 Merge pull request #12697 from koic/fix_an_error_for_style_case_like_if [Fix #12690] Fix an error for `Style/CaseLikeIf` commit 97467271431cf6db6a134b4398fe8f09db8bbb31 Author: Koichi ITO Date: Sat Feb 17 03:25:43 2024 +0900 [Fix #12699] Support searching for `.rubocop.yml` in compliance with dot-config Resolves #12699 This PR supports searching for `.rubocop.yml` in compliance with dot-config. [dot-config](https://dot-config.github.io/) prioritizes project-specific configurations over user-specific configurations, with a search order that first looks for the `.rubocop.yml` within the project's directories, in accordance with dot-config standards, before considering user-specific configurations. commit 948a6ed6fcd431d9d02c68e3199d77468e0dbcc5 Merge: e8df84bd8 f89412f1e Author: Koichi ITO Date: Sat Feb 17 01:35:54 2024 +0900 Merge pull request #12696 from koic/fix_an_incorrect_for_style_object_then [Fix #12693] Fix an incorrect autocorrect for `Style/ObjectThen` commit e8df84bd8a3eff5e6ed29bcabd58525befb30e1d Merge: 7b8726132 efa4eb839 Author: Koichi ITO Date: Fri Feb 16 23:31:00 2024 +0900 Merge pull request #12698 from koic/fix_error_for_style_multiline_ternary_operator [Fix #12691] Fix an error for `Style/MultilineTernaryOperator` commit efa4eb8398c6a512813987150b2260b32cf1c987 Author: Koichi ITO Date: Fri Feb 16 21:32:18 2024 +0900 [Fix #12691] Fix an error for `Style/MultilineTernaryOperator` Fixes #12691. This PR fixes an error for `Style/MultilineTernaryOperator` when nesting multiline ternary operators. commit dc74ac8d773ea1526aacc0975755b3067ae60aae Author: Koichi ITO Date: Fri Feb 16 11:32:33 2024 +0900 [Fix #12690] Fix an error for `Style/CaseLikeIf` Fixes #12690. This PR fixes an error for `Style/CaseLikeIf` when using `==` with literal and using ternary operator. commit f89412f1e0b29d052a4ad219e286565d14ea77bd Author: Koichi ITO Date: Fri Feb 16 11:04:23 2024 +0900 [Fix #12693] Fix an incorrect autocorrect for `Style/ObjectThen` Fixes #12693. This PR fixes an incorrect autocorrect for `Style/ObjectThen` when using `yield_self` without receiver. commit 7b8726132be1148d625a2005f283aa4c761fab92 Author: Koichi ITO Date: Thu Jan 25 02:34:27 2024 +0900 [Fix #12649] Fix false positives for `Style/InverseMethods` Fixes #12649. This PR fixes false positives for `Style/InverseMethods` when using relational comparison operator with safe navigation. commit d4afee6fb41a619836b8bb201ba5594710a7900f Author: Koichi ITO Date: Thu Feb 15 12:06:59 2024 +0900 [Fix #12687] Fix a false positive for `Lint/Void` Fixes #12687. This PR fixes a false positive for `Lint/Void` when `each` block with conditional expressions that has multiple statements. commit d8d8474edf63e4b60ec4b72cd78941520f977d44 Author: Koichi ITO Date: Tue Feb 13 23:16:42 2024 +0900 Add new `InternalAffairs/RedundantExpectOffenseArguments` cop This PR adds new `InternalAffairs/RedundantExpectOffenseArguments` cop, which checks for redundant arguments of `RuboCop::RSpec::ExpectOffense`'s methods. ```ruby # bad expect_no_offenses('code', keyword: keyword) # good expect_no_offenses('code') ``` commit 1acdaefb146c472ed92919444bccdb88cdade099 Merge: 1dac6a4e2 29c47f82c Author: Koichi ITO Date: Wed Feb 14 00:02:54 2024 +0900 Merge pull request #12684 from koic/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block [Fix #12683] Fix an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` commit 29c47f82cb1c8d4939a7ea20ac2dab10b6153551 Author: Koichi ITO Date: Tue Feb 13 09:55:43 2024 +0900 [Fix #12683] Fix an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` Fixes #12683 This PR fixes an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` when using guard clause with `next` implicitly nil. It also fixes the incorrect test code. commit 1dac6a4e20ab8b66bf0c0269b085a4191c0fce98 Author: Koichi ITO Date: Mon Feb 12 01:01:22 2024 +0900 Add `--editor-mode` CLI option Follow up https://github.com/rubocop/rubocop/pull/12657#issuecomment-1937084864. This PR adds `--editor-mode` CLI option, which optimize real-time feedback in editors, adjusting behaviors for editing experience. Editors that run RuboCop directly (e.g., by shelling out) encounter the same issues as with `--lsp`. This option is designed for such editors. commit 772054e2d3dc3f9a55e0de9bb0d1262be71019f8 Author: Koichi ITO Date: Sun Jan 28 17:16:01 2024 +0900 Support `AutoCorrect: contextual` option for LSP ## Summary This PR introduces `AutoCorrect: contextual` option that prevents autocorrection during typing in LSP. This option extends the existing `AutoCorrect` parameter. - Before: `AutoCorrect: true` or `AutoCorrect: false` - After: `AutoCorrect: always`, `AutoCorrect: disabled`, or `AutoCorrect: contextual` Note, `AutoCorrect: always` maintains compatibility with `AutoCorrect: true`, and `AutoCorrect: disabled` maintains compatibility with `AutoCorrect: false`. ## Details For example, `Style/EmptyMethod` should not autocorrect to one-liner while in the process of writing the body of the method. This isn't an issue with autocorrection itself, but rather due to differing requirements in contexts such as editing (LSP) and command line (e.g., CI). So, `AutoCorrect: contextual` is set for some cops like this. There may be other cases, but for the obvious following cops. The classification is as follows: ### Cops that might remove code being edited - `Layout/EmptyComment` cop - `Lint/EmptyConditionalBody` cop - `Lint/EmptyEnsure` cop - `Lint/EmptyInterpolation` cop - `Lint/TrailingCommaInAttributeDeclaration` cop - `Lint/UselessAccessModifier` cop - `Lint/UselessAssignment` cop - `Lint/UselessMethodDefinition` cop - `Lint/UselessTimes` cop - `Lint/Void` cop - `Style/EmptyElse` cop - `Style/RedundantInitialize` cop ### Cops that might adjust code being edited - `Lint/UnusedBlockArgument` cop - `Lint/UnusedMethodArgument` cop - `Style/EmptyHeredoc` cop - `Style/EmptyMethod` cop As a result, it allows for a distinction in the use of autocorrection between the LSP and command-line contexts. ## Other Information Here is why the parameter name was chosen as `contextual`. In this PR, autocorrection from LSP is always not applied in the case of `contextual`. However, even when `contextual` is set, I was considering a possibility for autocorrection to be forcibly applied from LSP under certain conditions. Therefore, the initial thought was to name it `contextual`, but it might have been too abstract in context, so it was changed to `contextual`. commit 8b3656d6e5e5685dc28dc8c57efa19ee2e9092f0 Author: Koichi ITO Date: Sun Feb 11 02:09:05 2024 +0900 Avoid redundant `parse` for `Style/RedundantArgument` This PR avoids redundant repetitive `parse` for `Style/RedundantArgument`. Similar to #12677 and #12678, there is no need to parse code that has already been parsed once. commit f9a6d2d973d9bb9b78fe4e9c11538bece53f043f Merge: 81ccef985 9e3bf052c Author: Koichi ITO Date: Sat Feb 10 03:12:25 2024 +0900 Merge pull request #12680 from koic/pending_a_options_spec_when_ruby34 Make an options_spec as pending when using Ruby 3.4.0dev commit 9e3bf052cef32eeb770db15ceb8f3cf2334cc5c7 Author: Koichi ITO Date: Sat Feb 10 02:25:15 2024 +0900 Make an options_spec as pending when using Ruby 3.4.0dev This PR makes the following options_spec as pending when using Ruby 3.4.0dev. ```console $ ruby -v ruby 3.4.0dev (2024-02-09T12:28:26Z master 08b77dd682) [x86_64-darwin23] $ bundle exec rspec './spec/rubocop/options_spec.rb[1:1:1:2]' (snip) 1 example, 1 failure Failed examples: rspec ./spec/rubocop/options_spec.rb:29 # RuboCop::Options option -h/--help shows help text ``` https://github.com/rubocop/rubocop/actions/runs/7845618444/job/21410458812?pr=12657 The pending spec should be update to behavior in accordance with the inquiry results of https://bugs.ruby-lang.org/issues/20252. commit 81ccef985a914f647e36bc956ea8c14755858d82 Author: Koichi ITO Date: Wed Feb 7 00:34:41 2024 +0900 Fix an error for `Style/RedundantLineContinuation` when using `Prism::Translation::Parser` This PR fixes the following error `Style/RedundantLineContinuation` when using `Prism::Translation::Parser` as a parser: ```console $ bundle exec ruby -rprism/translation/parser/rubocop $(bundle exec which rubocop) (snip) An error occurred while Style/RedundantLineContinuation cop was inspecting /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb. undefined method `complete?' for an instance of AST::Node /Users/koic/src/github.com/rubocop/rubocop-ast/lib/rubocop/ast/node.rb:104:in `block in initialize' ``` This is a similar error to #12677. commit 775852c35e14db23f4a65ab9a1c6cd2b0692832f Author: Koichi ITO Date: Fri Feb 2 00:44:00 2024 +0900 [Fix #12273] Make `OffenseCountFormatter` display autocorrection info Fixes #12273. This PR makes `OffenseCountFormatter` display autocorrection information. This solves the use case of checking and selectively applying cops that support autocorrection when there are some unresolved offenses. Although it may be possible to provide an option, finding use cases for making them optional seems unlikely. Therefore, the new autocorrection information will always be displayed. commit 6b516d01e7c0958441ef03abb903fab454d757ac Author: Koichi ITO Date: Mon Feb 5 12:55:28 2024 +0900 Fix false negatives for `Lint/RedundantSafeNavigation` This is similar to detection #12246. This PR fixes false negatives for `Lint/RedundantSafeNavigation` when using safe navigation operator for literal receiver. commit 3f9a75aebcc28f11d8e3a93ae3e14c3f64a75136 Author: Koichi ITO Date: Fri Feb 9 01:29:29 2024 +0900 Publish `RuboCop::LSP.enable` to enable LSP mode `RuboCop::Cop::Base.enable_lsp_mode` will be renamed to `RuboCop::LSP.enable`. Before: ```ruby RuboCop::Cop::Base.enable_lsp_mode ``` After: ```ruby RuboCop::LSP.enable ``` This is because whether or not it is LSP should not be set per cop but should be a state controlled for the entire RuboCop process. Since `RuboCop::Cop::Base.enable_lsp_mode` was an experimental private API, it will be renamed without a deprecation warning. Along with this, the module name has been changed from `RuboCop::Lsp` to `RuboCop::LSP`. This change is made to align with Ruby's standard API, like `RubyVM::YJIT.enable`, making it `RuboCop::LSP.enable` instead. `RuboCop::Lsp.enable` does not look as pretty name. With the renaming to `RuboCop::LSP.enable`, the usage of this API will be documented. This allows libraries like Ruby LSP and Solargraph, which use internal modules other than RuboCop's built-in `RuboCop::LSP::Server#start`, to easily utilize the features in #12586 and #12657. commit dc50e8034183646f05e7009e917a452ec1f7ba7e Author: Koichi ITO Date: Thu Feb 8 11:05:04 2024 +0900 Remove `base64` development dependency from Gemfile WebMock 3.20.0 has been released: https://github.com/bblimke/webmock/blob/master/CHANGELOG.md#3200 So, reverts https://github.com/rubocop/rubocop/pull/12317. commit 9b87c88c02c0b0f7c1c39f21c5f1000d286d245f Merge: 1488e1ff7 42e46805b Author: Koichi ITO Date: Wed Feb 7 16:01:09 2024 +0900 Merge pull request #12674 from koic/fix_false_negative_for_style_redundant_return Fix false negatives for `Style/RedundantReturn` commit 1488e1ff7b499664596040ce8a6d15e41aa97e53 Author: Koichi ITO Date: Tue Feb 6 21:56:55 2024 +0900 Fix an error for `Style/HashSyntax` when using `Prism::Translation::Parser` This PR fixes the following error `Style/HashSyntax` when using `Prism::Translation::Parser` as a parser: ```console $ bundle exec ruby -rprism/translation/parser/rubocop $(bundle exec which rubocop) \ --only Style/HashSyntax -d lib/rubocop/cop/style/not.rb (snip) An error occurred while Style/HashSyntax cop was inspecting /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/not.rb:23:27. undefined method `loc' for an instance of AST::Node /Users/koic/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/parser-3.3.0.5/lib/parser/builders/default.rb:1875: in `join_exprs' ``` Other ways to resolve this might exist, but using `RuboCop::Cop::Base#parser` is not necessary. Currently, no repro tests have been added as it is sufficient to verify that it is not broken with the Parser gem. And, this is for refactoring aimed at integration with `Prism`, no changelog entry will be added. cf. https://github.com/ruby/prism/blob/v0.21.0/docs/parser_translation.md#rubocop commit 42e46805b1f303c5ab65f5961b4b3f4fb2b09027 Author: Koichi ITO Date: Tue Feb 6 01:02:32 2024 +0900 Fix false negatives for `Style/RedundantReturn` This PR fixes false negatives for `Style/RedundantReturn` when using pattern matching. commit 3a03c799f2a69b81885ad8a982b1481d5ef1dc44 Author: Koichi ITO Date: Mon Feb 5 21:37:56 2024 +0900 Use `Range#join` instead of generic `Parser::Source::Range.new` This commit replaces the generic and verbose `Parser::Source::Range.new` with the dedicated API. commit c3ea782e490a7c7f1eb955459f010216194bf750 Author: Koichi ITO Date: Sun Feb 4 17:26:01 2024 +0900 Fix a typo commit 81b5d3eae698ff6296235e9c4917136257ab1baa Merge: 3f24b822a 5307cec0f Author: Koichi ITO Date: Sat Feb 3 00:17:38 2024 +0900 Merge pull request #12670 from koic/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body [Fix #12668] Fix an incorrect autocorrect for `Lint/EmptyConditionalBody` commit 5307cec0f4a8db592b6308da4ed0e913638563d3 Author: Koichi ITO Date: Fri Feb 2 09:57:06 2024 +0900 [Fix #12668] Fix an incorrect autocorrect for `Lint/EmptyConditionalBody` Fixes #12668. This PR fixes an incorrect autocorrect for `Lint/EmptyConditionalBody` when missing `if` body with conditional `else` body. commit 3f24b822a37f08e54a3e076e3a091f808adc6fa9 Author: Koichi ITO Date: Thu Feb 1 01:13:28 2024 +0900 [Docs] Update the doc for `Layout/EndAlignment` commit 36a6b885448c3f5c1652345d9afdc3cce5edd79b Author: Koichi ITO Date: Wed Jan 31 13:07:04 2024 +0900 Use `ProcessedSource#file_path` commit c27c74ef47b955fab6ccb844f19e4db44ca7217a Merge: 573b23bda 841b18d9f Author: Koichi ITO Date: Tue Jan 30 11:26:20 2024 +0900 Merge pull request #12659 from kiskoza/remove-bigdecimal-fixme Resolve Fixme in Gemfile, remove bigdecimal commit 841b18d9f738a6fb0ab44f23623f03ac81e37d0d Author: Koza Date: Mon Jan 29 20:05:14 2024 +0100 Resolve Fixme in Gemfile, remove bigdecimal This is a follow up on https://github.com/rubocop/rubocop/pull/12153 . The mentioned PR was merged in to `crack` and released as v0.4.6 commit 573b23bdaec2e0cc4787764117ae1fc38bfeaff5 Author: Maruth Goyal Date: Mon Jan 22 11:28:39 2024 -0800 Update error message on incorrect badge commit b6ee1c20a553e13c404b0b48137a17120a64e176 Author: Koichi ITO Date: Mon Jan 29 00:17:05 2024 +0900 Tweak an error message of `ConfigValidator` This PR tweaks an error message of `ConfigValidator` when the config is invalid: ## Before ```console $ bundle exec rake update_cops_documentation (snip) rake aborted! RuboCop::ValidationError: Property AutoCorrect of cop Layout/EmptyComment is supposed to be a boolean and on_command is not. (RuboCop::ValidationError) ``` ## After ```console $ bundle exec rake update_cops_documentation (snip) rake aborted! RuboCop::ValidationError: Property AutoCorrect of Layout/EmptyComment cop is supposed to be a boolean and on_command is not. (RuboCop::ValidationError) ``` commit bededcc93132938aeb10b885d7056bea87c4f3eb Merge: d1746bedd a3a30d454 Author: Koichi ITO Date: Sun Jan 28 09:45:05 2024 +0900 Merge pull request #12656 from koic/fix_error_for_layout_redundant_line_break Fix an error for `Layout/RedundantLineBreak` commit a3a30d4545a079a525e0ba23ce45b10326177f41 Author: Koichi ITO Date: Sat Jan 27 17:32:07 2024 +0900 Fix an error for `Layout/RedundantLineBreak` This PR fixes the following error for `Layout/RedundantLineBreak` when using index access call chained on multiline hash literal: ```console $ cat example.rb { key: value }[key] $ bundle exec rubocop --only Layout/RedundantLineBreak -a -d (snip) An error occurred while Layout/RedundantLineBreak cop was inspecting /tmp/example.rb:1:0. undefined method `method?' for an instance of RuboCop::AST::HashNode /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/layout/redundant_line_break.rb:92:in `index_access_call_chained?' ``` commit d1746bedda902662d2d2fc5225982dca936990e0 Merge: 3e31e45c3 02b2c3a46 Author: Koichi ITO Date: Sat Jan 27 01:51:49 2024 +0900 Merge pull request #12645 from jenshenny/change-source-order Check gemspec `required_ruby_version` before `.ruby-version` and other sources commit 3e31e45c3eb7395be601e0b27ead885b4074046a Author: Koichi ITO Date: Fri Jan 26 10:07:35 2024 +0900 Revert "Add default tags to issue templates" Reverts #12644. It's been a few days since the introduction, but there are false reports of the "bug" label being applied to items that are not confirmed as bugs or are not bugs. The default "bug" label is confusing for unconfirmed feedback. Despite considering user likelihood to change labels, submissions are often made with the default. For feature request, sometimes labels other than "enhancement", like "feature" or others, are more appropriate. Labeling can suit mechanical operations (e.g., bot), but may not fit uncertain feedback needing review, as seen in this repository. To avoid misleading labels on unresolved issues, the default labels will be removed from the issue template for maintenance reasons. commit 02b2c3a461f197134cb1d7e1bf693c4e3902e8de Author: Jenny Shen Date: Tue Jan 23 15:16:58 2024 -0500 Check gemspec source after rubocop config commit 02e1ab0212733142b69cb3148c4f92f83bd96fdb Author: Koichi ITO Date: Fri Jan 26 01:50:30 2024 +0900 Add `AutoCorrect` param to non display keys of generated doc Currently, `AutoCorrect` parameter is not configured, therefore there's no problem. But, this parameter should probably be ignored, similar to `SafeAutoCorrect`. commit 91bc38c7306adb07c62129db1614f67b941685b9 Merge: b4080d8ef 5d818a96d Author: Koichi ITO Date: Thu Jan 25 11:54:20 2024 +0900 Merge pull request #12648 from gsamokovarov/omit-parens-1-60-issues Fix numblock regressions in `omit_parentheses` Style/MethodCallWithArgsParentheses` commit 5d818a96d69c5062e7beb20314b9f28957d67f5f Author: Genadi Samokovarov Date: Wed Jan 24 17:50:00 2024 +0200 Fix numblock regressions in `omit_parentheses` Style/MethodCallWithArgsParentheses My last change was trying to fix an edge case where RuboCop wanted us to remove parentheses in the following example, but removing the parens was resulting in a `SyntaxError`: ```ruby AnyCable.middleware.use( Class.new(AnyCable::Middleware) do ^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for method calls with arguments. pass end ) ``` As it often happens, though, I broke a few other cases where we now want to remove parens, while the removal can result in ambiguous code: **Case 1** ```ruby Foo::Bar.find(pending.things.map { _1['code'] }) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for method calls with arguments. ``` While we can remove the parentheses in *Case 1*, the author has to be well aware of the difference between the do/end and braced blocks method bounding semantics. Allowing the author to put the parens can remove this ambiguity and we used to allow it. **Case 2** ```ruby [a, b].map { _1.call 'something' }.uniq.join(' - ') ^^^^^^^ Omit parentheses for method calls with arguments. ``` If we set `AllowParenthesesInChaining: true`, we should allow parentheses in chained calls. However, this is broken in current RuboCop. Both of the issues were caused by a 'refactoring' that forgot to check argument calls or chaining with `numblocks` specifically. commit b4080d8efc42466f31c63a443157363b11a467f7 Author: Koichi ITO Date: Wed Jan 24 16:57:31 2024 +0900 LSP mode configurable from external source The original LSP mode determination relied on the `--lsp` command-line argument, making it hard to set the mode from 3rd party LSP(-like) tools. This PR refines the API to resolve this issue. Additionally, as a side effect, it improves the mocking part of spec. However, the APIs are still experimental and not yet mature. commit 8a000a304090740fd599a86e63dc8b0d81f176bf Author: Bozhidar Batsov Date: Wed Jan 24 14:07:28 2024 +0200 Add back :windows as a platform for bigdecimal It was breaking bundler locally for me with the following error: [!] There was an error parsing `Gemfile`: `windows` is not a valid platform. The available options are: [:ruby, :ruby_18, :ruby_19, :ruby_20, :ruby_21, :ruby_22, :ruby_23, :ruby_24, :ruby_25, :ruby_26, :mri, :mri_18, :mri_19, :mri_20, :mri_21, :mri_22, :mri_23, :mri_24, :mri_25, :mri_26, :rbx, :truffleruby, :jruby, :jruby_18, :jruby_19, :mswin, :mswin_18, :mswin_19, :mswin_20, :mswin_21, :mswin_22, :mswin_23, :mswin_24, :mswin_25, :mswin_26, :mswin64, :mswin64_19, :mswin64_20, :mswin64_21, :mswin64_22, :mswin64_23, :mswin64_24, :mswin64_25, :mswin64_26, :mingw, :mingw_18, :mingw_19, :mingw_20, :mingw_21, :mingw_22, :mingw_23, :mingw_24, :mingw_25, :mingw_26, :x64_mingw, :x64_mingw_20, :x64_mingw_21, :x64_mingw_22, :x64_mingw_23, :x64_mingw_24, :x64_mingw_25, :x64_mingw_26]. Bundler cannot continue. # from /home/bozhidar/projects/rubocop/Gemfile:30 # ------------------------------------------- # # is merged and released. It's a workaround until then. > gem 'bigdecimal', platform: %i[mri windows] # gem 'webmock', require: false # ------------------------------------------- Seems this works on MigGW, though. commit 1f277665d506b65f1c3819e0229ebe70554d3ea6 Author: Bozhidar Batsov Date: Wed Jan 24 13:42:55 2024 +0200 Reset the docs version commit fbf41c6b2f2a3b80f0c5bb91c65080888d1e6c1e Author: r7kamura Date: Fri Jan 19 04:46:31 2024 +0900 Mark `Style/RaiseArgs` as unsafe commit edb56c927d4d1112a9c02990da31767e68d2121c Author: Bozhidar Batsov Date: Wed Jan 24 13:32:45 2024 +0200 Cut 1.60.2 commit f00679b93e118a81d53cf97d6459e6498336b710 Author: Bozhidar Batsov Date: Wed Jan 24 13:31:52 2024 +0200 Update Changelog commit 05730f51eb83c2eb681a2a7d578c7d1a79814072 Author: Koichi ITO Date: Tue Jan 23 15:11:32 2024 +0900 Fix false positives for `Style/HashEachMethods` Fixes https://github.com/rubocop/rubocop/issues/12534#issuecomment-1871676010. This PR fixes false positives for `Style/HashEachMethods` when using array converter method. Hash object converted to an Array cannot process `Hash#each_key` and `Hash#each_value`. Therefore, if methods that convert to an Array are used before `each`, they should be ignored. commit c5a705279e2fccd339d6edb3e528464e5f401e78 Author: OKURA Masafumi Date: Wed Jan 24 01:46:48 2024 +0900 Add default tags to issue templates commit 996c6be4b19a0b6819474df8639a95bf771b5d7b Author: Koichi ITO Date: Wed Jan 17 01:30:07 2024 +0900 Update the Compatibility Policy This PR proposes to update the Compatibility Policy. There are major version incompatibilities between Ruby 2.7 and Ruby 3.0. And the latest stable version of Ruby on Rails, 7.1, still supports Ruby 2.7. So, dropping support for Ruby 2.7 from RuboCop might be premature for the market at this stage. At least for the duration that Rails 7.1 is classified as being in the "Bug Fix" phase under the [Maintenance Policy for Ruby on Rails] (https://guides.rubyonrails.org/maintenance_policy.html), RuboCop will continue to support Ruby 2.7. In reality, RuboCop is mostly used for code analysis with the same version of the Ruby runtime. I think that ensuring such users can smoothly upgrade their RuboCop version justifies maintaining support for older Ruby version 2.7 for an extended period. commit a6cf5a76dbad273a4695e40ca08533404840c6e5 Author: Koichi ITO Date: Thu Jan 18 17:46:55 2024 +0900 [Fix #12632] Fix an infinite loop error for `Style/ArgumentsForwarding` Fixes #12632. This PR fixes an infinite loop error when `EnforcedStyle: explicit` of `Naming/BlockForwarding` with `Style/ArgumentsForwarding`. commit 60a9350687ea1120647bbc6b82c80407abb54644 Author: Koichi ITO Date: Mon Jan 22 00:25:17 2024 +0900 [Fix #12638] Fix an `Errno::ENOENT` error when using server mode Fixes #12638. There is a possibility of a race condition occurring with the status file when using server mode. The status file is updated to a new status by `Cache.write_status_file` (`Pathname#write`), so there is no need to clear it by deleting the file. Due to the difficulty in reproducing this race conditions, test code for this have not been added. commit 96542aa6ff0446487e78bdb8b303bbb04f1eb06f Author: Koichi ITO Date: Mon Jan 22 17:01:10 2024 +0900 [Docs] Tweak the "Template support" doc This commit prevents unintended hyphens from being displayed instead of highlights: https://docs.rubocop.org/rubocop/1.60/extensions.html#template-support commit c3921c0988d23c994a705eae08fc2c8983455106 Merge: 54c3f61a2 17f5fcff7 Author: Koichi ITO Date: Sun Jan 21 14:06:46 2024 +0900 Merge pull request #12636 from Earlopain/fix-error-for-style-hash-each-methods Fix an error for `Style/HashEachMethods` when a block with both parameters has no body commit 17f5fcff76e4e3784d8e42f0c0cc82908f777042 Author: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Sat Jan 20 17:54:11 2024 +0100 Fix an error for `Style/HashEachMethods` when a block with both parameters has no body commit 54c3f61a2e3db697394652d11d52f6620b481f1e Merge: d4229d35b 210c4d361 Author: Koichi ITO Date: Sun Jan 21 01:31:23 2024 +0900 Merge pull request #12635 from Earlopain/false-positive-for-style-hash-each-methods Fix a false positive for `Style/HashEachMethods` when both arguments are unused commit d4229d35bdf615d8222327c126860cdc916800a0 Author: Koichi ITO Date: Sun Jan 21 01:13:17 2024 +0900 Fix false negatives for `InternalAffairs/ExampleDescription` Follow up https://github.com/rubocop/rubocop/pull/12624#discussion_r1454736589 This PR fixes false negatives for `InternalAffairs/ExampleDescription` when given an improper description with option. commit 4ad4b95c538a42c5d4eff48b34c83d8e8de02416 Merge: 20353dc2c 4b6ad5cbe Author: Koichi ITO Date: Sat Jan 20 02:48:34 2024 +0900 Merge pull request #12628 from koic/fix_false_positive_for_style_arguments_forwarding Fix a false positive for `Style/ArgumentsForwarding` commit 20353dc2ced595d9faa7c31ff202e9bde8128cc5 Merge: 2b27ed86b 3cf1bce84 Author: Koichi ITO Date: Fri Jan 19 02:25:08 2024 +0900 Merge pull request #12631 from koic/fix_a_false_positive_for_layout_redundant_line_break_cop [Fix #12627] Fix a false positive for `Layout/RedundantLineBreak` commit 210c4d361a749ea77766381983f605917e1109b6 Author: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Thu Jan 18 18:19:57 2024 +0100 Fix a false positive for `Style/HashEachMethods` when both arguments are unused. `Lint/UnusedBlockArgument` should instead say something about this: commit 3cf1bce84aba870f05b1c815e03b6491ab7a4772 Author: Koichi ITO Date: Thu Jan 18 16:01:42 2024 +0900 [Fix #12627] Fix a false positive for `Layout/RedundantLineBreak` Fix #12627. This PR fixes a false positive for `Layout/RedundantLineBreak` when using index access call chained on multiple lines with backslash. commit 2b27ed86b5270715a70fa3899a586af9b5797388 Merge: 14119589b f8ccef6e0 Author: Koichi ITO Date: Thu Jan 18 18:46:11 2024 +0900 Merge pull request #12634 from koic/fix_build_error_on_windows Fix a build error on windows mingw matrix commit f8ccef6e0f4a6d00a7621cc17391c95fe6aa9010 Author: Koichi ITO Date: Thu Jan 18 18:17:15 2024 +0900 Fix a build error on windows mingw matrix This PR fixes the following build error on windows mingw matrix: ```console D:/a/rubocop/rubocop/vendor/bundle/ruby/3.4.0+0/gems/crack-0.4.5/lib/crack/xml.rb:9: warning: bigdecimal was loaded from the standard library, but is not part of the default gems since Ruby 3.4.0. Add bigdecimal to your Gemfile or gemspec. An error occurred while loading spec_helper. - Did you mean? rspec ./spec/spec_helper.rb Failure/Error: require 'webmock/rspec' LoadError: cannot load such file -- bigdecimal # ./vendor/bundle/ruby/3.4.0+0/gems/crack-0.4.5/lib/crack/xml.rb:9:in `' ``` https://github.com/rubocop/rubocop/actions/runs/7567518866/job/20606843322?pr=12633 This occurred due to BigDecimal has been extracted as a bundled gem: ruby/ruby#9573 commit 4b6ad5cbe3a0a58d2090afd6f69b841ac16a0d75 Author: Koichi ITO Date: Thu Jan 18 10:42:07 2024 +0900 Fix a false positive for `Style/ArgumentsForwarding` Resolves https://github.com/rubocop/rubocop/issues/12618#issuecomment-1896303457. This PR fixes a false positive for `Style/ArgumentsForwarding` when using block arg forwarding with positional arguments forwarding to within block. commit 14119589b2e3a7be13f2542ad9ae0d3515fdda76 Author: Koichi ITO Date: Thu Jan 18 02:25:41 2024 +0900 Fix a false positive for `Style/ArgumentsForwarding` Fixes https://github.com/rubocop/rubocop/issues/12618#issuecomment-1896227199. This PR fixes a false positive for `Style/ArgumentsForwarding` when naming a block argument `&`. commit f0e89c976cd56330b4f95c82dc4f9aacacfeff25 Author: Bozhidar Batsov Date: Wed Jan 17 18:00:24 2024 +0200 Reset docs version commit 1f507c9a4fbde88058e504480b7ca2864b7aacd3 Author: Bozhidar Batsov Date: Wed Jan 17 17:59:30 2024 +0200 Cut 1.60.1 commit 356b6cb91cc9b06d334ab225e9132df0307277dd Author: Bozhidar Batsov Date: Wed Jan 17 17:58:55 2024 +0200 Update Changelog commit 936895d67bf119abf4c08610005661c32d31422f Author: Koichi ITO Date: Wed Jan 17 13:30:01 2024 +0900 [Fix #12618] Fix false positives for `Style/ArgumentsForwarding` Fixes #12618, #12619, #12620, and #12621. This PR fixes false positives for `Style/ArgumentsForwarding` when using block argument forwarding with other arguments. And this PR makes `Style/ArgumentsForwarding` aware only block argument forwarding when using Ruby 3.1+. commit 927a220b72700093b42f9df09d0148969fd5a9ba Merge: ef7f54ecd d0dccdd71 Author: Koichi ITO Date: Wed Jan 17 20:55:10 2024 +0900 Merge pull request #12625 from Strzesia/handle-errno-erofs-exception Add Errno::EROFS exception handling for read-only file systems commit d0dccdd71f759573335658e706937c96be2b308a Author: Strzesia Date: Wed Jan 17 10:47:13 2024 +0100 Add Errno::EROFS exception handling for read-only file systems commit ef7f54ecd48b72e10c93bc509bceae2276ae035b Author: Koichi ITO Date: Tue Jan 16 17:44:40 2024 +0900 [Fix #12617] Make `Style/CollectionCompact` aware of `grep_v` with nil Resolves #12617. This PR makes `Style/CollectionCompact` aware of `grep_v` with nil. commit f4cc2921bf5691b62507f81fbffcbb427d7a68be Author: Koichi ITO Date: Tue Jan 16 00:06:42 2024 +0900 [Fix #12614] Fix false positiveis for `Style/RedundantParentheses` Fixes #12614. This PR fixes false positiveis for `Style/RedundantParentheses` when parentheses in control flow keyword with multiline style argument. commit ce906c679e225b5f434950e2991a64a0534aea13 Author: Koichi ITO Date: Tue Jan 16 00:37:35 2024 +0900 Switch back the docs version commit 56e88bb824fa4699b0e7d6af22afd8943daf8d84 Author: Bozhidar Batsov Date: Mon Jan 15 09:53:35 2024 +0200 Cut 1.60 commit 84ee480111ac430c91535d49b01f24ba115d07a9 Author: Bozhidar Batsov Date: Mon Jan 15 09:53:11 2024 +0200 Update Changelog commit 6a83571276cd95a1ff4d4065cb5381789559c23f Author: Koichi ITO Date: Mon Jan 15 12:58:18 2024 +0900 Remove useless `require fileutils` commit d58940bb6ab5c88dd8b3aa73217cbd0588cfa01d Author: Koichi ITO Date: Sun Jan 14 01:14:22 2024 +0900 Rename `git_hub` to `github` GitHub is a single word, as represented by github.com. commit 6d829af807d29bee5ad51406ead53ce543a5a3bb Author: Koichi ITO Date: Sat Jan 13 16:44:38 2024 +0900 Add style guide link for `Style/SlicingWithRange` Follow up https://github.com/rubocop/ruby-style-guide/pull/939 commit 172937ed1e353de5269deb1669f8896c845c3e15 Author: Koichi ITO Date: Sat Jan 13 01:14:32 2024 +0900 Add style guide link for `Style/OptionHash` Closes https://github.com/rubocop/rubocop/issues/12401. commit c51dfeca84f68d72130a5b60ed85fc017cc38106 Author: Kobus Post Date: Thu Nov 30 11:52:52 2023 +0100 Add start of string to regexps in DisabledConfigFormatter commit 4e392b289b88c2aafba9900af1c883cbe4c6d692 Author: Kobus Post Date: Tue Nov 14 10:56:27 2023 +0100 Include expanded EnforcedStyle options when --no-auto-gen-enforced-style is given commit b36fe4adff4c15354c1a64c57ad9e97a01fcbf48 Author: Koichi ITO Date: Thu Jan 11 18:09:40 2024 +0900 [Fix #12601] Make `Style/EachForSimpleLoop` accept block with no parameters Fixes #12601. This PR makes `Style/EachForSimpleLoop` accept block with no parameters. This is the behavior according to the documentation: > This check only applies if the block takes no parameters. https://docs.rubocop.org/rubocop/1.59/cops_style.html#styleeachforsimpleloop commit 075d4d5d7597c2b179a90f76a2a9fc886465ecb9 Author: marocchino Date: Fri Dec 15 11:43:31 2023 +0900 [Fix #12542] Fix false positive for `Lint/MixedRegexpCaptureTypes` commit b9d793a7609c481feb19943b9ddcb4b7e4da277a Merge: 91f7d9acf 64fb437e3 Author: Koichi ITO Date: Fri Jan 12 11:22:29 2024 +0900 Merge pull request #12610 from gsamokovarov/dont-omit-parentheses-in-argument-blocks Accept parentheses in argument calls with blocks commit 64fb437e3e1f6a38a2c6216a797921417c7394b9 Author: Genadi Samokovarov Date: Thu Jan 11 12:00:17 2024 +0200 Accept parentheses in argument calls with blocks In `Style/MethodCallWithArgsParentheses` with `omit_parentheses` enforced style we need to allow parentheses in method calls with blocks, when their value is used as an arguments in method dispatch calls. We have syntax errors when we enforce their omissions: ```ruby foo( Class.new(Base) do # valid Ruby end ) ``` Should be allowed as the example below is invalid Ruby: ```ruby foo( Class.new Base do # invalid Ruby end ) ``` commit 91f7d9acf80ce78c9cbd2e6a9fab3c8db08e9e8d Author: Koichi ITO Date: Thu Dec 28 18:28:45 2023 +0900 [Fix #12571] Fix false posives for `Naming/BlockForwarding` Fixes #12571. This PR fixes false positives for `Naming/BlockForwarding` when using explicit block forwarding in block method. commit 730c4a9f22e76e2c2a4aa6f509406b5fc56e2880 Author: Koichi ITO Date: Fri Dec 29 00:07:58 2023 +0900 Fix false positives for `Style/ArgumentsForwarding` Fixes https://github.com/rubocop/rubocop/issues/12571#issuecomment-1870575888. This PR fixes false positives for `Style/ArgumentsForwarding` when rest arguments forwarding to a method in block. commit 86822c3a74cd7ed5fdc21f9200366613b3267265 Author: Koichi ITO Date: Sun Dec 31 16:01:17 2023 +0900 [Fix #11033] Change warning message for `Lint/Syntax` when using LSP Fixes #11033. ## Summary This PR changes warning message for `Lint/Syntax` between LSP and the command line. The redundancy of the offense message probably depends on the context. The context in which the issue has been reported is LSP. In LSP, source code being typed may still be evaluated as invalid syntax. On the other hand, when executed via the `rubocop` command line, the input is usually complete and evaluated as valid syntax in most cases. This means that suggesting a possible misconfiguration in .rubocop.yml would be sufficient only when using the command line. So, this is because the difference in evaluation timing of source code. Therefore, it is implemented as a distinction based on the execution context, rather than as a configuration option. ## Additional Information To resolve this, it seems reasonable to switch the context of the message between LSP and the `rubocop` command line. As for implementation, while the issue in Solargraph won't be directly resolved, considering a switch to RuboCop's built-in LSP could be an option. This PR adds the `RuboCop::Base#lsp_mode?` method, which is intended to be used for the LSP mode expansion I'm currently considering. The LSP still can be carved, and I think there is potential to make RuboCop's LSP more user-friendly and improve it. commit 39484b81005040aed438983ec0e5384ef907ef33 Author: Koichi ITO Date: Sat Jan 6 01:48:32 2024 +0900 [Fix #12233] Make `Style/SlicingWithRange` aware of beginless range Fixes #12233. This PR makes `Style/SlicingWithRange` aware of redundant and beginless range. Ruby 2.7 introduced beginless ranges. But, unlike the somewhat obscure `-1` in `ary[1..-1]`, the `0` in `ary[0..42]` is clear as a starting point. In fact, changing it to `ary[..42]` could potentially make it less readable. Therefore, `ary[0..42]` should respect the original programmer's intent. On the other hand, `ary[nil..42]` could be replaced with `ary[..42]`. Similarly, `ary[1..nil]` could be replaced with `ary[1..]`. Moreover, `[0..-1]` in `ary[0..-1]` is redundant and simply synonymous with `ary`. This PR has also made adjustments to detect this case. While this is a byproduct of supporting beginless and endless ranges, I think including this change in `Style/SlicingWithRange` cop may be suitable and not feel out of place. commit 975ba2a6cbb88d86cf13127592a7e28974b48a85 Author: Koichi ITO Date: Sun Jan 7 01:58:02 2024 +0900 [Fix #12437] Fix an infinite loop error for `Style/MethodCallWithArgsParentheses` Fixes #12437. This PR fixes an infinite loop error for `EnforcedStyle: omit_parentheses` of `Style/MethodCallWithArgsParentheses` with `Style/SuperWithArgsParentheses`. In #12390, `super` has become a separate `Style/SuperWithArgsParentheses` cop. This PR prevents the infinite loop error by ensuring that `Style/MethodCallWithArgsParentheses` no longer detects `super`, following the separation of `super` into `Style/SuperWithArgsParentheses` cop. This approach aligns with the perspective that methods and `super` have different considerations regarding parentheses usage, as mentioned in #12390. commit 61f92452f1c529a8810bce336f9f23c9bbc5b19e Author: Koichi ITO Date: Wed Jan 10 18:17:12 2024 +0900 Fix a false positive for `Style/RedundantParentheses` This PR fixes a false positive for `Style/RedundantParentheses` when regexp literal attempts to match against a parenthesized condition. The presence or absence of parentheses here changes the meaning of the syntax, so the parentheses are not redundant: ```console $ ruby-parse -e '/regexp/ =~ (foo || bar)' (match-with-lvasgn (regexp (str "regexp") (regopt)) (begin (or (send nil :foo) (send nil :bar)))) $ ruby-parse -e '/regexp/ =~ foo || bar' (or (match-with-lvasgn (regexp (str "regexp") (regopt)) (send nil :foo)) (send nil :bar)) ``` commit 5f3112c186246039fafdebbc025cd89da27f6e04 Merge: 5cd23f889 55e9e70bb Author: Koichi ITO Date: Thu Jan 11 10:26:27 2024 +0900 Merge pull request #12593 from koic/ruby_33 Require Parser 3.3.0.2 or higher commit 5cd23f889d24c4b99305db980dbaddf0134554bb Merge: 753a82c8a 4d058aa8c Author: Koichi ITO Date: Wed Jan 10 12:16:37 2024 +0900 Merge pull request #12604 from koic/fix_a_false_positive_for_style_multiline_ternary_operator [Fix #12603] Fix an infinite loop error for `Style/MultilineTernaryOperator` commit 4d058aa8c2651bf2d59f554281a8fe9545b39c0d Author: Koichi ITO Date: Tue Jan 9 19:27:09 2024 +0900 [Fix #12603] Fix an infinite loop error for `Style/MultilineTernaryOperator` Fixes #12603. This PR fixes an infinite loop error for `Style/MultilineTernaryOperator` when using a method call as a ternary operator condition with a line break between receiver and method. commit 753a82c8abee64afb557add55ce3a21f3a3b366a Author: Koichi ITO Date: Tue Jan 9 12:43:20 2024 +0900 Remove useless FIXME comment There is no context provided in the introduction of #9240. commit 3ce4fbfa8865740d963772d6ecd926cf9c5b0893 Merge: 0f2697d17 8844cefbf Author: Koichi ITO Date: Mon Jan 8 00:20:13 2024 +0900 Merge pull request #12598 from jonas054/12179_auto_gen_config_with_max [Fix #12179] Generate Exclude when Max is overridden commit 55e9e70bbeea7f1949e01aaf6e858364f70bb94d Author: Koichi ITO Date: Fri Jan 5 23:43:33 2024 +0900 Require Parser 3.3.0.2 or higher Ruby 3.3 and Parser 3.3.0.2 have been released. - https://www.ruby-lang.org/en/news/2023/12/25/ruby-3-3-0-released - https://rubygems.org/gems/parser/versions/3.3.0.2 This PR requires Parser 3.3.0.2 or higher and removes "experimental" label from support matrix. The Parser gem specifies version 3.3.0.2+, not 3.3.0.0, as it applies the following patch: https://github.com/whitequark/parser/pull/987 commit 0f2697d176d1d8f666aa08b02e9f1631edccaa53 Author: Koichi ITO Date: Mon Jan 8 00:03:33 2024 +0900 Revert "Workaround for an error when parsing heredoc with non-word delimiters" Parser gem 3.3.0.2 has been released. So, this reverts commit 5b08ee481cc54f293b9815115511288f7199d80d. commit cdc7f02e1e06c6d7a6af9edc768a2a319af35114 Merge: 7adcf786f 5b08ee481 Author: Koichi ITO Date: Sun Jan 7 23:36:09 2024 +0900 Merge pull request #12599 from koic/pending_two_specs_for_heredoc_with_non_word_delimiters Workaround for an error when parsing heredoc with non-word delimiters commit 5b08ee481cc54f293b9815115511288f7199d80d Author: Koichi ITO Date: Sun Jan 7 22:18:07 2024 +0900 Workaround for an error when parsing heredoc with non-word delimiters Pending two specs until the following error in Parser 3.3.0.1 is resolved. https://github.com/whitequark/parser/pull/987 commit 8844cefbf28bcd70e79de24d9460133ac59f5227 Author: Jonas Arvidsson Date: Sat Jan 6 16:27:29 2024 +0100 [Fix #12179] Generate `Exclude` when `Max` is overridden For a cop that has a Max setting, if that setting is overridden in user configuration, creating a Max property in .rubocop_todo.yml will be useless. User configuration will take precedence and after running `rubocop --auto-gen-config` there can still be offenses that get reported in the next `rubocop` run. With this modification, we avoid the problem by generating `Exclude` instead of `Max` in those situations. commit 7adcf786fb105ebdd390e3640273a5252cddc876 Author: Koichi ITO Date: Sat Jan 6 16:15:23 2024 +0900 Remove useless code from options_spec The inner `options.parse` causes an exception, so the outer `options.parse` is never called, making it a useless piece of code. commit 88df571fd32c5317c0fdb0caeeacfedf09525978 Author: Akhil G Krishnan Date: Sun Dec 31 07:55:44 2023 +0530 Bump license years to 2024 commit d3f04df0e1f8395502de11230a318a14fe1bb569 Author: Koichi ITO Date: Fri Jan 5 01:45:18 2024 +0900 Tweak offense message for `Style/SlicingWithRange` This commit tweaks `Style/SlicingWithRange`'s offense message to reflect actual range value, rather than using a fixed message. commit 910e5774bc65cc572bbf4cefa03c6d40469cdd67 Author: Koichi ITO Date: Thu Jan 4 22:54:40 2024 +0900 Use RuboCop RSpec 2.26 This PR uses RuboCop RSpec 2.26 and autocorrects the following new `RSpec/ExampleWording` offenses: ```console $ bundle exec rubocop Offenses: spec/project_spec.rb:308:11: C: [Corrected] RSpec/ExampleWording: Do not use the future tense when describing your tests. it 'will not have a directory' do ^^^^^^^^^^^^^^^^^^^^^^^^^ (snip) ``` https://github.com/rubocop/rubocop-rspec/releases/tag/v2.26.0 commit 9dd56ef7981d8d8a1a466217bd2d65787f0374c7 Author: Koichi ITO Date: Thu Jan 4 02:08:57 2024 +0900 Raise an exception if automation task `system` fails Same as https://github.com/rubocop/rubocop-minitest/commit/8f8f978. commit 623fef0eeab3f774023c22f0ecc6e39c4685307f Author: Koichi ITO Date: Mon Jan 1 02:05:52 2024 +0900 Tweak the changelog URL on RubyGems.org This PR tweaks changelog URL on RubyGems.org. https://rubygems.org/gems/rubocop The CHANGELOG.md is extensive, so the link of the changelog on RubyGems.org will be updated to point to the GitHub release page, focusing on the release version. e.g., https://github.com/rubocop/rubocop/releases/tag/v1.59.0 The idea is the same as in https://github.com/rubocop/rubocop/pull/8775. commit 5d7f57ee15cd9e4a1513a4834a172242c3a3b606 Author: Koichi ITO Date: Wed Jan 3 13:06:03 2024 +0900 CircleCI against Ruby 3.3 Ruby 3.3.0 has been released and this Ruby version is available on `cimg/ruby:3.3` image. - https://www.ruby-lang.org/en/news/2023/12/25/ruby-3-3-0-released/ - https://circleci.com/developer/en/images/image/cimg/ruby commit a6f97574aa391a8e6594598ae34414fb04020a95 Merge: b7de9f008 3325d42a8 Author: Koichi ITO Date: Tue Jan 2 01:24:30 2024 +0900 Merge pull request #12589 from jonas054/12574_auto_gen_bad_style [Fix #12574] Handle unrecognized style better in --auto-gen-config commit 3325d42a82e6501797f214cd5dea171d3c595729 Author: Jonas Arvidsson Date: Mon Jan 1 15:17:15 2024 +0100 [Fix #12574] Handle unrecognized style better in --auto-gen-config When there are supported styles in the cop configuration, auto-generated configuration should get an EnforcedStyle entry if the inspected code base conforms, not to the currently select style, but to one of the other styles, and follows that style in all places. If the code base contains code the conforms to different styles, we should get an Exclude entry instead. The same goes for code that doesn't conform to any of the cop's supported styles. This last case is where we had a bug. We didn't mark the style as unrecognized, which is why we got an EnforcedStyle instead of an Exclude. commit b7de9f008cc0779649d04cc57b70624a169e263c Author: Koichi ITO Date: Mon Jan 1 17:16:17 2024 +0900 Use the latest Ruby 3.3 parser for docs commit 01928d51c25d5a8fb191e1e28a2be44ed4568c17 Author: Koichi ITO Date: Sat Dec 30 19:56:37 2023 +0900 [Fix #12236] Fix an error for `Lint/ShadowedArgument` Fixes #12236. This PR fixes an error for `Lint/ShadowedArgument` when self assigning to a block argument in `for`. commit 5457ca8ab65008a59d67dcfab5c9b6c3852d5f8c Merge: 1cadf985f 81f513838 Author: Koichi ITO Date: Sun Dec 31 01:29:16 2023 +0900 Merge pull request #12580 from koic/fix_an_error_for_layout_end_alignment Fix an infinite loop error for `Layout/EndAlignment` commit 1cadf985f8941da328b66cb8ef92c5f922ae4d5f Merge: f848986a3 be6b3e954 Author: Koichi ITO Date: Sat Dec 30 00:58:41 2023 +0900 Merge pull request #12581 from eugeneius/trailing_line_continuation Handle trailing line continuation in Layout/LineContinuationLeadingSpace commit be6b3e954d544ef806d7b6c41c5701200c7d49d6 Author: Eugene Kenny Date: Fri Dec 29 13:54:16 2023 +0000 Handle trailing line continuation in Layout/LineContinuationLeadingSpace Previously this would crash with: NoMethodError: undefined method `length' for nil:NilClass commit 81f5138384979c1b61522d4426afeb26f2ad5f76 Author: Koichi ITO Date: Fri Dec 29 14:39:35 2023 +0900 Fix an infinite loop error for `Layout/EndAlignment` Fixes https://github.com/standardrb/standard/issues/598. This PR fixes an infinite loop error for `Layout/EndAlignment` when misaligned in singleton class assignments with `EnforcedStyleAlignWith: variable`. commit f848986a37f0c033a7a4c736cf04025f97fe6645 Merge: 229f20565 0187af3e2 Author: Koichi ITO Date: Fri Dec 29 15:15:01 2023 +0900 Merge pull request #12572 from koic/change_emulate_ruby33_warning_for_security_open Follow a Ruby 3.3 warning for `Security/Open ` commit 0187af3e2b66f957810079f662c4afebcb5473b1 Author: Koichi ITO Date: Tue Dec 26 10:25:29 2023 +0900 Follow a Ruby 3.3 warning for `Security/Open ` This PR follows the following Ruby 3.3 warning for `Security/Open` when `open` with a literal string starting with a pipe: ```console $ ruby -we "open('| ls')" ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [x86_64-darwin22] -e:1: warning: Calling Kernel#open with a leading '|' is deprecated and will be removed in Ruby 4.0; use IO.popen instead ``` commit 229f20565a9001b9edc79b09c30bd423d05c11ad Merge: 1718e8d13 cbaf216ce Author: Koichi ITO Date: Thu Dec 28 01:03:04 2023 +0900 Merge pull request #12575 from koic/ci_against_ruby_3_3_on_windows CI against Ruby 3.3 on Windows commit cbaf216ceeabb33cb69207f3333294fffff5b8fe Author: Koichi ITO Date: Wed Dec 27 22:47:06 2023 +0900 CI against Ruby 3.3 on Windows https://github.com/ruby/setup-ruby/pull/555 has been merged. commit 1718e8d13c30ad9b39aba29f8aee89957111ce1b Author: Koichi ITO Date: Wed Dec 27 10:20:59 2023 +0900 Remove unused vars in spec of `Layout/SpaceAroundMethodCallOperator` commit 94d14fe67f429ffe89dcce2e39e0a3e03d9d5fbf Merge: 9fb1e252f 9cd81365e Author: Koichi ITO Date: Tue Dec 26 21:37:07 2023 +0900 Merge pull request #12570 from koic/fix_an_error_for_style_identical_conditional_branches [Fix #12569] Fix an error for `Style/IdenticalConditionalBranches` commit 9cd81365e4ad15eea5b92b19154c64d1b5042d4c Author: Koichi ITO Date: Mon Dec 25 21:30:28 2023 +0900 [Fix #12569] Fix an error for `Style/IdenticalConditionalBranches` Fixes #12569. This PR fixes an error for `Style/IdenticalConditionalBranches` when using `if`...`else` with identical leading lines that assign to `self.foo`. NOTE: It would be better to update `RuboCop::AST::OpAsgnNode` to handle `self.foo ||= value` to solve the issue in future. commit 9fb1e252f8b0a9e6038fae86dd4e345ef35986d3 Author: Koichi ITO Date: Mon Dec 25 09:43:56 2023 +0900 Remove redundant blank line from documentation generator commit 34f93a01773b46115ef1e3a46d19b4f1380381a2 Author: Koichi ITO Date: Mon Dec 25 09:27:32 2023 +0900 Remove unused code in `Style/EvalWithLocation` Follow up https://github.com/rubocop/rubocop/pull/9411. commit e195110c2ab2ba8c3baa58da499a5ff12f8e9238 Author: Sam Bostock Date: Tue Dec 19 14:36:39 2023 -0600 Document `Style/SymbolProc` protected method incompatibility This documents the false positive for `Style/SymbolProc` when used with a `protected` method. `public` and `private` method behaviour matches, but `protected` methods which work in the normal block style break when using `Symbol#to_proc`. commit 6ed8c7174938983c61d5e0f0ce028bc0110d721c Author: Koichi ITO Date: Sun Dec 24 01:10:28 2023 +0900 [Fix #12548] Fix an infinite loop error for `Layout/FirstArgumentIndentation` Fixes #12548. This PR fixes an infinite loop error for `Layout/FirstArgumentIndentation` when specifying `EnforcedStyle: with_fixed_indentation` of `Layout/ArrayAlignment`. commit 38bcf13324dde68fce326885864771054329183f Merge: 14e26fdae 81ef82ddc Author: Koichi ITO Date: Sun Dec 24 08:47:10 2023 +0900 Merge pull request #12566 from koic/make_style_redundant_each_aware_of_safe_navigation_operator [Fix #12453] Make `Style/RedundantEach` aware of safe navigation operator commit 14e26fdae1b0d2959fabd67c525467b9217fc405 Author: Koichi ITO Date: Sat Dec 23 13:54:59 2023 +0900 Remove useless `require pathname` commit 81ef82ddcdca995b839e6a94bd873576e43686e0 Author: Koichi ITO Date: Sat Dec 23 00:35:24 2023 +0900 [Fix #12453] Make `Style/RedundantEach` aware of safe navigation operator Fixes #12453. This PR makes `Style/RedundantEach` aware of safe navigation operator. And offense range has been tweaked to clarify whether the target for removal, associated with the detection of safe navigation, is `.` or `&.`. commit ff458bf531a558489ef91e094877d7543674258a Author: Arman Singh Grewal <66531687+ArmanGrewal007@users.noreply.github.com> Date: Fri Dec 22 21:04:05 2023 +0530 Add RuboCop icons with white bg (#12554) Useful in dark themes. commit 12fc3222993c204d7dca492ef26a0aabdba3c041 Author: Sam Bostock Date: Wed Dec 20 08:20:31 2023 -0600 Improve `Style/InvertibleUnlessCondition` message The existing message is ambiguous about how to invert the condition, leading many to assume the cop is suggesting replacing code like unless number.odd? ^^^^^^^^^^^^^^^^^^ Favor `if` with inverted condition over `unless`. with if !number.odd? which would conflict with `Style/NegatedIf`. This updates the message to clearly describe the change being recommended: unless number.odd? ^^^^^^^^^^^^^^^^^^ Prefer `if number.even?` over `unless number.odd?`. commit 685a7f81f3fcfebd77fd4806b4473144c1926da1 Author: Evan Goldenberg Date: Tue Dec 12 14:42:43 2023 -0800 Allow autocorrect with display-only-fail-level-offenses The `--display-only-fail-level-offenses` option uses `considered_failure?` to determine what to print. The same method is used to determine the exit code of `rubocop`, so the two options should be entirely safe to use together. This change is useful when using rubocop as part of a pre-commit hook. When the hook fails becuase rubocop exited with a non-zero status, we can use `--display-only-fail-level-offenses` to avoid having the output cluttered up with non-blocking offenses. commit 74abd36bb04f30a4c6bce199f4ea53e805cfc101 Merge: 7de40e04e ac5eecb14 Author: Koichi ITO Date: Fri Dec 22 11:14:39 2023 +0900 Merge pull request #12564 from koic/fix_incorrect_autocorrect_for_style_map_to_hash Fix an incorrect autocorrect for `Style/MapToHash` commit ac5eecb14055926e920db11ec9fae61718031247 Author: Koichi ITO Date: Thu Dec 21 19:09:28 2023 +0900 Fix an incorrect autocorrect for `Style/MapToHash` Follow https://github.com/rubocop/rubocop/pull/12560#discussion_r1432423841 This PR fixes an incorrect autocorrect for `Style/MapToHash` using safe navigation operator. NOTE: This is a partial unreleased regression of #12560. So, it has not been added to the changelog. commit 7de40e04e0a244efa1dfa3e9d7d904b902601bb6 Merge: 2a72b6c0c 24fae5e65 Author: Koichi ITO Date: Thu Dec 21 22:09:49 2023 +0900 Merge pull request #12563 from koic/fix_false_positives_for_style_redundant_parentheses [Fix #12556] Fix false positives for `Style/RedundantParentheses` commit 24fae5e6518f8e2883a64cc308b4238dbb75ad43 Author: Koichi ITO Date: Thu Dec 21 00:40:02 2023 +0900 [Fix #12556] Fix false positives for `Style/RedundantParentheses` Fixes #12556. This PR fixes false positives for `Style/RedundantParentheses` when parentheses are used around a semantic operator in expressions within assignments. commit 2a72b6c0c40e1e538c8c2d7e5dc8fecf19973da2 Author: Koichi ITO Date: Wed Dec 20 12:57:10 2023 +0900 [Fix #12558] Fix an incorrect autocorrect for `Style/MapToHash` Fixes #12558. This PR fixes an incorrect autocorrect for `Style/MapToHash` when using `map.to_h` without receiver. commit 1b3c31b93f9945dbdfd0ef0ab8bec21eaa52f080 Author: Daniel Vandersluis Date: Thu Dec 14 14:43:44 2023 -0500 Fix new `Style/ArgumentsForwarding` offenses. commit 626894b26ce1bd8008ac80fe81958869e644ed43 Author: Daniel Vandersluis Date: Thu Dec 14 14:42:53 2023 -0500 Fix false negative in `Style/ArgumentsForwarding` when a block is forwarded but other args aren't. commit 5af4bad2b420a2c7d4bd2d5385191cadda2f5586 Merge: faf48f15e bb49018c2 Author: Koichi ITO Date: Tue Dec 19 02:47:10 2023 +0900 Merge pull request #12538 from koic/make_style_each_for_simple_loop_aware_of_safe_navigation_operator [Fix #12478] Make `Style/EachForSimpleLoop` cops aware of safe navigation operator commit faf48f15e1c990c1767fe6d08cd269115d73db5b Merge: 4843acda5 fa660e155 Author: Koichi ITO Date: Mon Dec 18 08:17:38 2023 +0800 Merge pull request #12550 from koic/fix_a_false_positive_for_style_redundant_line_continuation [Fix #12549] Fix a false positive for `Style/RedundantLineContinuation` commit 4843acda5e1fad8a6b64da1c9f6a3d6dab6e591c Author: Koichi ITO Date: Sun Dec 17 17:13:43 2023 +0800 Add contribution note to cops documentation generator Occasionally I reviewed direct edit to cops documentation. This is similar in intent to the following: https://github.com/rubocop/rubocop/pull/11563 For source code comments, refer to the AsciiDoc documentation: https://docs.asciidoctor.org/asciidoc/latest/comments/#comment-blocks commit fa660e155e5d550a7b42abe06dbbfb00983aa9e8 Author: Koichi ITO Date: Sat Dec 16 16:33:52 2023 +0800 [Fix #12549] Fix a false positive for `Style/RedundantLineContinuation` Fixes #12549. This PR fixes a false positive for `Style/RedundantLineContinuation` when line continuations for multiline leading dot method chain with a blank line. commit 6239e917db0e083a942ad29dd2a328f04d5abeb0 Merge: 079dffada b9e2c65a4 Author: Koichi ITO Date: Sun Dec 17 02:47:47 2023 +0800 Merge pull request #12544 from koic/fix_false_positives_for_redundant_parentheses [Fix #12537] Fix false positives for `Style/RedundantParentheses` commit 079dffada557294790deeb55524ad7af33f55958 Author: Koichi ITO Date: Sat Dec 16 09:27:36 2023 +0800 Use RuboCop Performance to 1.20 ```console $ bundle exec rubocop (snip) lib/rubocop/cop/exclude_limit.rb:11:21: C: [Correctable] Performance/StringIdentifierArgument: Use :"#{method_name}=" instead of "#{method_name}=". define_method("#{method_name}=") do |value| ^^^^^^^^^^^^^^^^^ lib/rubocop/cop/style/conditional_assignment.rb:236:25: C: [Correctable] Performance/StringIdentifierArgument: Use :"on_#{type}" instead of "on_#{type}". define_method "on_#{type}" do |node| ^^^^^^^^^^^^ lib/rubocop/cop/style/numeric_literal_prefix.rb:65:32: C: [Correctable] Performance/StringIdentifierArgument: Use :"#{literal_type(node).upcase}_MSG" instead of "#{literal_type(node).upcase}_MSG". self.class.const_get("#{literal_type(node).upcase}_MSG") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/lsp/routes.rb:20:23: C: [Correctable] Performance/StringIdentifierArgument: Use :"handle_#{name}" instead of "handle_#{name}". define_method("handle_#{name}", &block) ^^^^^^^^^^^^^^^^ 1527 files inspected, 4 offenses detected, 4 offenses autocorrectable ``` commit 58223eb09058f3b6c186ee44d187e853471009a6 Merge: baa4a9765 431b3195f Author: Koichi ITO Date: Fri Dec 15 17:44:32 2023 +0800 Merge pull request #12543 from koic/fix_false_positives_for_style_hash_each_methods [Fix #12540] Fix false positives for `Style/HashEachMethods` commit b9e2c65a470e7d07860bd18b041aefd5eda2dcff Author: Koichi ITO Date: Fri Dec 15 14:04:17 2023 +0800 [Fix #12537] Fix false positives for `Style/RedundantParentheses` Fixes #12537. This PR fixes false positives for `Style/RedundantParentheses` when `AllowInMultilineConditions: true` of `Style/ParenthesesAroundCondition`. commit 431b3195f9fe5845a5c39bfca1158f3a0ae986fa Author: Koichi ITO Date: Fri Dec 15 10:18:34 2023 +0800 [Fix #12540] Fix false positives for `Style/HashEachMethods` Fixes #12540. This PR fixes false positives for `Style/HashEachMethods` when rest block argument of `Enumerable#each` method is used. commit baa4a97656b452f02937efe261b55afa5cbc5bf6 Merge: 7c80c7920 a8fdeb096 Author: Koichi ITO Date: Thu Dec 14 23:30:52 2023 +0800 Merge pull request #12539 from koic/fix_false_positives_for_lint_literal_assignment_in_condition Fix false positives for `Lint/LiteralAssignmentInCondition` commit a8fdeb09679f5ee85f949ef19d1229d903e27956 Author: Koichi ITO Date: Thu Dec 14 00:48:49 2023 +0900 Fix false positives for `Lint/LiteralAssignmentInCondition` This PR fixes the following false positive for `Lint/LiteralAssignmentInCondition` when a collection lireal contains non-literal elements: ```console $ echo 'x = 1; if test = [42, x]; end' | be rubocop --stdin test.rb --only Lint/LiteralAssignmentInCondition Inspecting 1 file W Offenses: test.rb:1:16: W: Lint/LiteralAssignmentInCondition: Don't use literal assignment = [42, x] in conditional, should be == or non-literal operand. x = 1; if test = [42, x]; end ^^^^^^^^^ 1 file inspected, 1 offense detected ``` In cases where non-literal elements are included in the collection, no warning will be displayed. ```console $ ruby -we 'x = 1; if test = [42, x]; end' ``` commit bb49018c2c9cf9706bff3675122ae62c6ffd8762 Author: Koichi ITO Date: Thu Dec 14 17:25:25 2023 +0800 [Fix #12478] Make `Style/EachForSimpleLoop` cops aware of safe navigation operator Fixes #12478. This PR makes `Style/EachForSimpleLoop` cops aware of safe navigation operator. commit 7c80c79209087163a9242df502a387be69382e0b Author: Paweł Gościcki Date: Wed Dec 13 15:19:49 2023 +0100 Fix BufPreWrite pattern in nvim-lspconfig rubocop formatting example The pattern for `Buf*` commands in neovim looks to be a file names pattern, not file types. When set to `ruby`, automatic formatting doesn't work. It starts working only when I set it to `*.rb`. Reference: https://neovim.io/doc/user/api.html#:~:text=%22BufWinEnter%22%7D%2C%20%7B-,pattern%20%3D%20%7B%22*.c%22%2C%20%22*.h%22%7D,-%2C%0A%20%20callback%20%3D%20function commit 47597354fae54fb762ab10069f3ccb71c6185606 Merge: 25f2bb69b 0475db252 Author: Koichi ITO Date: Wed Dec 13 01:11:08 2023 +0900 Merge pull request #12532 from koic/fix_false_positives_for_style_parentheses_around_condition [Fix #12529] Fix false positives for `Style/ParenthesesAroundCondition` commit 0475db252630cc1581704de8a72a0f9c7d26d7a0 Author: Koichi ITO Date: Tue Dec 12 01:16:52 2023 +0900 [Fix #12529] Fix false positives for `Style/ParenthesesAroundCondition` Fixes #12529. This PR fixes false positives for `Style/ParenthesesAroundCondition` when using a method call with `do`...`end` block as a condition in a loop. commit 25f2bb69b732ade8a941ec156dce4fb539126001 Author: Koichi ITO Date: Tue Dec 12 00:07:45 2023 +0900 Switch back the docs version commit aee14b2886ff7361aacb4aef8c4ad6d251155476 Merge: e5a164a26 69cfcfbab Author: Koichi ITO Date: Mon Dec 11 20:56:39 2023 +0900 Merge pull request #12531 from brkn/patch-1 Fix pr reference to the new `Lint/ItWithoutArgumentsInBlock` cop in CHANGELOG commit 69cfcfbabc634e9449ba2f17f943935ba58575ed Author: Berkan Ünal <32255826+brkn@users.noreply.github.com> Date: Mon Dec 11 13:59:46 2023 +0300 Fix reference to the new Lint/ItWithoutArgumentsInBlock cop in CHANGELOG.md commit e5a164a26f8ecba81d44e974e8e3569c550968cd Author: Bozhidar Batsov Date: Mon Dec 11 11:24:03 2023 +0100 Cut 1.59 commit 2912b6e9e90831717b004b4e016fd2723fac5e44 Author: Bozhidar Batsov Date: Mon Dec 11 11:23:40 2023 +0100 Update Changelog commit 3bcc171fe5d9ee0251b1c22ffec463aaec495bf7 Author: Koichi ITO Date: Sun Dec 10 12:57:39 2023 +0900 [Fix #12524] Fix a false positive for `Style/MethodCallWithArgsParentheses` Fixes #12524. This PR fixes a false positive for `Style/MethodCallWithArgsParentheses` when `EnforcedStyle: omit_parentheses` and parens in `when` clause is used to pass an argument. commit 0daa4aa05977f67b575d126caff716959e60f00f Author: Koichi ITO Date: Sat Dec 9 02:26:32 2023 +0900 Make `Style/MethodCallWithoutArgsParentheses` allow parenthesized `it` This PR makes `Style/MethodCallWithoutArgsParentheses` allow the parenthesized `it` method in a block. It respects following Ruby 3.3's warning: ```console $ ruby -e '0.times { begin; it; end }' -e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it ``` Related PR ... https://github.com/rubocop/rubocop/pull/12518 commit b240a093c0539c1f89c60df6b599d2afd4db4f22 Author: Koichi ITO Date: Sat Dec 9 17:56:36 2023 +0900 Make `Style/RedundantSelf` allow `self.it` This PR makes `Style/RedundantSelf` allow the `self.it` method in a block. It respects following Ruby 3.3's warning: ```console $ ruby -e '0.times { begin; it; end }' -e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it ``` Related PR ... https://github.com/rubocop/rubocop/pull/12518 commit a0e1042a34d4d0ff855447d6f9059c98b610258f Author: Koichi ITO Date: Mon Dec 11 08:05:17 2023 +0900 [Fix #12526] Fix incorrect rendering typos commit b1bcb3134d49a60061d08ef168ae996d70d8ce5c Author: Koichi ITO Date: Tue Dec 5 00:08:03 2023 +0900 [Fix #12444] Fix false positive for `Style/HashEachMethods` Fixes #12444. This PR fixes false positive for `Style/HashEachMethods` when receiver literal is not a hash literal. commit 3b0360bb9fcd9c49e09882c2b1780ba7cbbf64a8 Author: Koichi ITO Date: Fri Dec 8 01:24:21 2023 +0900 Add new `Lint/ItWithoutArgumentsInBlock` cop Follow up https://bugs.ruby-lang.org/issues/18980 and https://github.com/ruby/ruby/pull/9152. Emulates the following Ruby warnings in Ruby 3.3. ```ruby $ ruby -e '0.times { it }' -e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it ``` `it` calls without arguments will refer to the first block param in Ruby 3.4. So use `it()` or `self.it` to ensure compatibility. ```ruby # bad do_something { it } # good do_something { it() } do_something { self.it } ``` commit 4e9cfcc6ea39b69474eab3e13b551be32d3217ff Merge: 037c860c1 73bf28412 Author: Koichi ITO Date: Sun Dec 10 01:35:42 2023 +0900 Merge pull request #12521 from koic/make_style_select_by_regexp_aware_of_safe_navigation_operator [Fix #12458] Make `Style/SelectByRegexp` cops aware of safe navigation operator commit 037c860c1fe2f8a0512dbe15ff329fee2f7c10f6 Merge: 63c72e573 fbe176178 Author: Koichi ITO Date: Sat Dec 9 10:27:15 2023 +0900 Merge pull request #12438 from koic/fix_a_false_positive_for_lint_literal_assignment_in_condition [Fix #12434] Fix a false positive for `Lint/LiteralAssignmentInCondition` commit 73bf284123ca6a2e016d5a8ef433efe6dbca93c9 Author: Koichi ITO Date: Sat Dec 9 00:40:43 2023 +0900 [Fix #12458] Make `Style/SelectByRegexp` cops aware of safe navigation operator Fixes #12458. This PR makes `Style/SelectByRegexp` cops aware of safe navigation operator. commit 63c72e573945cbe78247c2aa3fd2a34ce3093119 Author: Koichi ITO Date: Fri Dec 8 15:42:03 2023 +0900 Revert "Make `Style/SingleArgumentDig` aware of safe navigation operator" Follow up https://github.com/rubocop/rubocop/pull/12463#pullrequestreview-1771198386 This PR reverts #12463. As for the scope of this cop's role, it is reasonable to ignore cases where safe navigation is used. This PR will update the documentation and tests to indicate that this behavior is expected. commit 42a5d507dfe5bf7c830aa1b9cf008b97638fcb7f Merge: 86acefc1d 5a726dea4 Author: Koichi ITO Date: Fri Dec 8 10:19:38 2023 +0900 Merge pull request #12513 from koic/fix_false_positives_for_style_redundant_parentheses [Fix #12436] Fix false positives for `Style/RedundantParentheses` commit 86acefc1d292133a794eee0487e27eec625748a6 Merge: 3745a3c67 b59eece6e Author: Koichi ITO Date: Thu Dec 7 01:29:33 2023 +0900 Merge pull request #12515 from koic/fix_an_incorrect_autocorrect_for_style_combinable_loops [Fix #12442] Fix an incorrect autocorrect for `Style/CombinableLoops` commit 3745a3c6727de5bee328c0ea1c3ae8e014effb4a Merge: 3b318913d c7ff1a4a5 Author: Koichi ITO Date: Wed Dec 6 01:24:50 2023 +0900 Merge pull request #12439 from koic/fix_a_false_positive_for_lint_self_assignment [Fix #12435] Fix a false positive for `Lint/SelfAssignment` commit b59eece6ed634973f5773a8fe37b34c6890e1e36 Author: Koichi ITO Date: Wed Dec 6 00:34:11 2023 +0900 [Fix #12442] Fix an incorrect autocorrect for `Style/CombinableLoops` Fixes #12442. This PR fixes an incorrect autocorrect for `Style/CombinableLoops` when looping over the same data as previous loop in `do`...`end` and `{`...`}` blocks. commit 5a726dea42ce37e29ef4b5e7b40767305e8d4e41 Author: Koichi ITO Date: Tue Dec 5 00:28:14 2023 +0900 [Fix #12436] Fix false positives for `Style/RedundantParentheses` Fixes #12436. This PR fixes false positives for `Style/RedundantParentheses` when a part of range is a parenthesized condition. commit 3b318913d64feb1d480c8f290afd18b2aae79d92 Author: Koichi ITO Date: Mon Dec 4 11:12:52 2023 +0900 [Fix #12489] Make `Lint/NextWithoutAccumulator` aware of safe navigation operator Fixes #12489. This PR makes `Lint/NextWithoutAccumulator` aware of safe navigation operator. commit 04ef51be5be55d6cb3391ceba7b2cd702eb003a0 Author: Koichi ITO Date: Mon Dec 4 11:03:43 2023 +0900 [Fix #12489] Make `Lint/HashCompareByIdentity` aware of safe navigation operator Fixes #12489. This PR makes `Lint/HashCompareByIdentity` aware of safe navigation operator. commit 6eec65ca96f8fe2fe0e8972d3b81e7713b764b1a Author: Koichi ITO Date: Mon Dec 4 10:42:17 2023 +0900 [Fix #12494] Make `Layout/SingleLineBlockChain` aware of safe navigation operator Fixes #12494. This PR makes `Layout/SingleLineBlockChain` aware of safe navigation operator. commit 9b504dc06b384098d8c1bb3afa3dbad5576a8322 Author: Koichi ITO Date: Mon Dec 4 10:33:56 2023 +0900 [Fix #12495] Make `Layout/RedundantLineBreak` aware of safe navigation operator Fixes #12495. This PR makes `Layout/RedundantLineBreak` aware of safe navigation operator. commit 1578ed786507b5fc5f9a73cbbf630a378ba73dcc Author: Koichi ITO Date: Mon Dec 4 02:47:15 2023 +0900 [Fix #12486] Make `Style/RedundantArgument` aware of safe navigation operator Fixes #12486. This PR makes `Style/RedundantArgument` aware of safe navigation operator. commit bf670679654c45518a2e3289ceded2dd706ad71f Author: Koichi ITO Date: Mon Dec 4 02:33:27 2023 +0900 [Fix #12484] Make `Style/Next` aware of safe navigation operator Fixes #12484. This PR makes `Style/Next` aware of safe navigation operator. commit c37001c9f3f440504f6fd3106649b7960c7d8c29 Author: Koichi ITO Date: Mon Dec 4 02:22:07 2023 +0900 [Fix #12479] Make `Style/EachWithObject` aware of safe navigation operator Fixes #12479. This PR makes `Style/EachWithObject` aware of safe navigation operator. commit 7cc15926a9015ed2fcc3f0280bc843fc18783407 Author: Koichi ITO Date: Mon Dec 4 02:16:19 2023 +0900 [Fix #12480] Make `Style/ExactRegexpMatch` aware of safe navigation operator Fixes #12480. This PR makes `Style/ExactRegexpMatch` aware of safe navigation operator. commit cec618ddb967bda39988dcf3f62d9e9eed7715eb Author: Koichi ITO Date: Mon Dec 4 02:10:59 2023 +0900 [Fix #12476] Make `Style/ConcatArrayLiterals` aware of safe navigation operator Fixes #12476. This PR make `Style/ConcatArrayLiterals` aware of safe navigation operator and tweaks this cop's offense message. commit 1379d6d63a6be9977dab2deda45a146f1fad4cc4 Author: Koichi ITO Date: Mon Dec 4 02:03:17 2023 +0900 [Fix #12474] Make `Style/ConcatArrayLiterals` aware of safe navigation operator Fixes #12474. This PR makes `Style/ConcatArrayLiterals` aware of safe navigation operator. commit aabddb61fb91c3278f0f2c8cbb68fcf6add1b761 Author: Koichi ITO Date: Mon Dec 4 01:59:10 2023 +0900 [Fix #12473] Make `Style/ClassCheck` aware of safe navigation operator Fixes #12473. This PR makes `Style/ClassCheck` aware of safe navigation operator. commit 9379ef630d063c960b15138e0f484713fd9827e2 Author: Koichi ITO Date: Mon Dec 4 01:19:44 2023 +0900 [Fix #12469] Make `Style/UnpackFirst` aware of safe navigation operator Fixes #12469. This PR makes `Style/UnpackFirst` aware of safe navigation operator and tweaks offense message. commit 9524694ab1f7978ab46f18e7c87bf3c686f262bb Merge: 9879858b5 4cea704d6 Author: Koichi ITO Date: Tue Dec 5 01:37:44 2023 +0900 Merge pull request #12505 from koic/fix_a_false_positive_for_style_redundant_parentheses Fix a false positive for `Style/RedundantParentheses` commit 4cea704d6fc1226dc46584bc0523ee90e6e17112 Author: Koichi ITO Date: Mon Dec 4 17:19:53 2023 +0900 Fix a false positive for `Style/RedundantParentheses` Follow up https://github.com/rubocop/rubocop/pull/12381#issuecomment-1837926968. This PR fixes a false positive for `Style/RedundantParentheses` when using parenthesized `lambda` or `proc` with `do`...`end` block. `do`...`end` and `{`...`}` have different precedence, so with `do`...`end`, parentheses are needed to correct the order of association. However, with `->`, there is no need to worry about precedence, so the parentheses can be removed. commit 9879858b5f92ce59f0421705daeb91a1b5fef2aa Author: Koichi ITO Date: Mon Dec 4 00:27:57 2023 +0900 [Fix #12454] Make `Style/RedundantFetchBlock` aware of safe navigation operator Fixes #12454. This PR makes `Style/RedundantFetchBlock` aware of safe navigation operator. commit a67ea27701bb3ee5293743a0f1cf5cff03173d34 Author: Koichi ITO Date: Mon Dec 4 00:23:30 2023 +0900 [Fix #12455] Make `Style/RedundantSort` aware of safe navigation operator Fixes #12455. This PR makes `Style/RedundantSort` aware of safe navigation operator. commit 42f27c8c0622be3b2427892cb04cf6b7ceda2d1a Author: Koichi ITO Date: Mon Dec 4 00:03:01 2023 +0900 [Fix #12456] Make `Style/RedundantSortBy` aware of safe navigation operator Fixes #12456. This PR makes `Style/RedundantSortBy` aware of safe navigation operator. commit b38283abfeea91d43b7941d81c875e3cfa8e0e10 Author: Koichi ITO Date: Sun Dec 3 23:57:57 2023 +0900 [Fix #12457] Make `Style/Sample` aware of safe navigation operator Fixes #12457. This PR makes `Style/Sample` aware of safe navigation operator. commit 933aa0da2a33d53603ce79611732dfba36ee0981 Author: Koichi ITO Date: Sun Dec 3 23:48:18 2023 +0900 [Fix #12460] Make `Style/SingleArgumentDig` aware of safe navigation operator Fixes #12460. This PR makes `Style/SingleArgumentDig` aware of safe navigation operator. commit 2fdf5d41875db17bdc8c51bf7b1bf92c1311c502 Author: Koichi ITO Date: Mon Dec 4 01:04:04 2023 +0900 [Fix #12468] Make `Style/Strip` aware of safe navigation operator Fixes #12468. This PR makes `Style/Strip` aware of safe navigation operator. commit a41cc466b627854780639ad7b72901fd669224a5 Author: Koichi ITO Date: Sun Dec 3 23:43:51 2023 +0900 [Fix #12461] Make `Style/StringChars` aware of safe navigation operator Fixes #12461. This PR makes `Style/StringChars` aware of safe navigation operator. commit 720d05dd508956811658098df63d2682fa0f27ca Author: Koichi ITO Date: Mon Dec 4 11:31:14 2023 +0900 [Fix #12490] Make `Lint/NumberConversion` aware of safe navigation operator Fixes #12490. This PR makes `Lint/NumberConversion` aware of safe navigation operator. commit 6117bbb97b723cfa19c74c3285597c18cb1b328a Author: Koichi ITO Date: Mon Dec 4 11:36:05 2023 +0900 [Fix #12491] Make `Lint/RedundantWithIndex` aware of safe navigation operator Fixes #12491. This PR makes `Lint/RedundantWithIndex` aware of safe navigation operator. commit 5a344ed93e60e184968dd7ba22c83e095ebea177 Author: Koichi ITO Date: Mon Dec 4 11:39:26 2023 +0900 [Fix #12492] Make `Lint/RedundantWithObject` aware of safe navigation operator Fixes #12492. This PR makes `Lint/RedundantWithObject` aware of safe navigation operator. commit 7e1c64ca7436876eff2c263963e843894e822761 Author: Koichi ITO Date: Mon Dec 4 12:09:05 2023 +0900 [Fix #12493] Make `Lint/UnmodifiedReduceAccumulator` aware of safe navigation operator Fixes #12493. This PR makes `Lint/UnmodifiedReduceAccumulator` aware of safe navigation operator. commit a90b80de045551867911d3f63f46b0edd76d419d Merge: fcc5c430f a92c3f81f Author: Koichi ITO Date: Mon Dec 4 00:31:06 2023 +0900 Merge pull request #12452 from koic/make_style_map_compact_with_conditional_block_aware_of_safe_navigation_operator [Fix #12447] Make `Style/MapCompactWithConditionalBlock` aware of safe navigation operator commit fcc5c430f8c0c76ebf4ab0b33cec1b80ad32e68a Merge: 7b5cf70cd fbf047e1e Author: Koichi ITO Date: Mon Dec 4 00:30:43 2023 +0900 Merge pull request #12451 from koic/make_style_hash_except_aware_of_safe_navigation_operator [Fix #12446] Make `Style/HashExcept` aware of safe navigation operator commit 7b5cf70cd1246bf056d317b7ff1002ce6d9dba26 Merge: 09a4d90c4 18b9792a0 Author: Koichi ITO Date: Mon Dec 4 00:30:17 2023 +0900 Merge pull request #12450 from koic/make_style_collection_compact_aware_of_safe_navigation_operator [Fix #12445] Make `Style/CollectionCompact` aware of safe navigation operator commit a92c3f81f13adab7140f0d659f90e29a86b3c48d Author: Koichi ITO Date: Sun Dec 3 15:39:25 2023 +0900 [Fix #12447] Make `Style/MapCompactWithConditionalBlock` aware of safe navigation operator Fixes #12447. This PR makes `Style/MapCompactWithConditionalBlock` aware of safe navigation operator. commit fbf047e1e07f5d00446aaa83e4e0ce97075adcc9 Author: Koichi ITO Date: Sun Dec 3 15:33:48 2023 +0900 [Fix #12446] Make `Style/HashExcept` aware of safe navigation operator Fixes #12446. This PR makes `Style/HashExcept` aware of safe navigation operator. commit 18b9792a01015cd899963e01e956e7a47b9c02c2 Author: Koichi ITO Date: Sun Dec 3 15:26:12 2023 +0900 [Fix #12445] Make `Style/CollectionCompact` aware of safe navigation operator Fixes #12445. This PR makes `Style/CollectionCompact` aware of safe navigation operator. commit 09a4d90c48f306df99c2c62cea351057443b52ce Merge: 0a40cda2e f92d4ea04 Author: Koichi ITO Date: Sun Dec 3 13:27:39 2023 +0900 Merge pull request #12449 from masato-bkn/fix-layout-heredocindentation Fix inline code for `Layout/HeredocIndentation` document commit 0a40cda2ec5de6f3bdce95783ff412bb3dd0433b Merge: 7815c01e0 c9aea2a59 Author: Koichi ITO Date: Sun Dec 3 09:50:23 2023 +0900 Merge pull request #12443 from koic/fix_false_positives_for_style_hash_each_methods [Fix #12441] Fix false positives for `Style/HashEachMethods` commit 7815c01e0b81b3699877d2a713205b26bac3dda9 Merge: 893435979 851365cae Author: Koichi ITO Date: Sun Dec 3 01:22:27 2023 +0900 Merge pull request #12431 from koic/tweak_autocorrect_for_style_map_to_hash [Fix #12429] Fix incorrect autocorrect for `Style/MapToHash` commit c9aea2a59f9c9c7469a159d0476584d68fea0c5d Author: Koichi ITO Date: Sun Dec 3 00:08:11 2023 +0900 [Fix #12441] Fix false positives for `Style/HashEachMethods` Fixes #12441. This PR fixes false positives for `Style/HashEachMethods` when using destructed block arguments. commit 8934359793f5f948b6a35e759d5f8ec9caab6fe2 Merge: 2e4ca822c 8d094d48b Author: Koichi ITO Date: Sat Dec 2 20:38:02 2023 +0900 Merge pull request #12440 from ishigo974/master Correction: Style/ArrayFirstLast documentation typo commit 8d094d48bfd2dfc07c78f4c0b00b30b2fc1fdd49 Author: Maxime Menigoz Date: Sat Dec 2 11:51:48 2023 +0100 Correction: Style/ArrayFirstLast documentation typo commit fbe1761788e12c5ba36d274e9c875361a1ce691d Author: Koichi ITO Date: Sat Dec 2 15:10:36 2023 +0900 [Fix #12434] Fix a false positive for `Lint/LiteralAssignmentInCondition` Fixes #12434. This PR fixes a false positive for `Lint/LiteralAssignmentInCondition` when using interpolated string or xstring literals. commit c7ff1a4a5ce8ea1eb887a2caca38913081ebf9e6 Author: Koichi ITO Date: Sat Dec 2 15:45:31 2023 +0900 [Fix #12435] Fix a false positive for `Lint/SelfAssignment` Fixes #12435. This PR fixes a false positive for `Lint/SelfAssignment` when using attribute assignment with method call with arguments. commit 851365caea08c98b4b7796ad847654005c913400 Author: Koichi ITO Date: Sat Dec 2 00:03:00 2023 +0900 [Fix #12429] Fix incorrect autocorrect for `Style/MapToHash` Fixes #12429. This PR fixes incorrect autocorrect for `Style/MapToHash` when using dot method calls for `to_h`. commit 2e4ca822cd5512368b34607571b53455ea7ace1e Merge: d4a23fc46 1dc0b7811 Author: Koichi ITO Date: Sat Dec 2 15:07:43 2023 +0900 Merge pull request #12432 from koic/fix_false_positive_for_lint_literal_assignment_in_condition Fix false positive for `Lint/LiteralAssignmentInCondition` commit 1dc0b781143ba3b366433874497c133b1032a2ff Author: Koichi ITO Date: Sat Dec 2 03:02:09 2023 +0900 Fix false positive for `Lint/LiteralAssignmentInCondition` This PR fixes the following false positive for `Lint/LiteralAssignmentInCondition` when using parallel assignment with splat operator in block of guard condition: ```ruby return if do_something do |z| x, y = *z end ``` ```console $ bundle exec rubocop example.rb --only Lint/LiteralAssignmentInCondition Inspecting 1 file W Offenses: example.rb:2:8: W: Lint/LiteralAssignmentInCondition: Don't use literal assignment = *z in conditional, should be == or non-literal operand. x, y = *z ^^^^ 1 file inspected, 1 offense detected ``` This is a false positive because `ruby -w` doesn't warn. commit d4a23fc4629f8c0d482ccf221cec4635ab0d8205 Author: Bozhidar Batsov Date: Fri Dec 1 14:55:00 2023 +0200 Switch back the docs version commit f27164b11c055414a3707e98ffb87d610c32b0ce Author: Bozhidar Batsov Date: Fri Dec 1 14:49:24 2023 +0200 Cut 1.58 commit 73b08761336813b47dff308e0bb9384df312c2cf Author: Bozhidar Batsov Date: Fri Dec 1 14:48:32 2023 +0200 Update Changelog commit 19daa1c2e7a1998d391484aafd8ed7cf59b7c16e Author: Koichi ITO Date: Wed Nov 29 00:14:40 2023 +0900 Add new `Lint/LiteralAssignmentInCondition` cop ## Summary This PR adds a new `Lint/LiteralAssignmentInCondition` cop, which checks for literal assignments in the conditions of `if`, `while`, and `until`. It emulates the following Ruby warning: ```console $ ruby -we 'if x = true; end' -e:1: warning: found `= literal' in conditional, should be == ``` As a lint cop, it cannot be determined if `==` is appropriate as intended, therefore this cop does not provide autocorrection. ```ruby # bad if x = 42 do_something end # good if x == 42 do_something end # good if x = y do_something end ``` Literal assignment used within a condition always triggers a Ruby warning, regardless of parentheses. This PR prevents the Ruby warning from being overlooked due to the `ruby -w` option. ## Additional Information Here, the differences between similar cops, `Lint/LiteralAssignmentInCondition` cop and `Lint/LiteralAsCondition` cop are discussed. ### `Lint/LiteralAssignmentInCondition` cop A similar `Lint/LiteralAssignmentInCondition` cop already exists, but as mentioned above, literal assignments are Ruby's warned about regardless of the presence of parentheses: ```ruby $ ruby -we 'if (x = 42); end' -e:1: warning: found `= literal' in conditional, should be == ``` Therefore, a new cop has been created separate from `Lint/LiteralAssignmentInCondition`. Furthermore, as documented for `Lint/LiteralAssignmentInCondition` cop, literal assignments are never considered `good` case, so `= true` has been replaced with `= value`. ### `Lint/LiteralAsCondition` cop Additionally, the existing `Lint/LiteralAsCondition` cop addresses a slightly different Ruby warning: ```ruby $ ruby -we 'if 42; end' -e:1: warning: literal in condition ``` This is another reason for choosing to implement a new cop. commit c8d2d776cf242063af17f3b6fbb12461a3301d7b Author: Koichi ITO Date: Fri Dec 1 10:54:55 2023 +0900 [Fix #12424] Make `Style/HashEachMethods` aware of safe navigation operator Fixes #12424. This PR makes `Style/HashEachMethods` aware of safe navigation operator. commit 3db23fa0b7bc504487bb30dd0b99c8444d4c5177 Merge: 4753e929e 7f0a5890b Author: Koichi ITO Date: Fri Dec 1 15:38:49 2023 +0900 Merge pull request #12422 from fatkodima/optimize-tests Optimize rspec tests commit f92d4ea04972ef77b5174de02390aeb664885b18 Author: masato-bkn Date: Thu Nov 23 10:01:18 2023 +0900 Fix inline code for `Layout/HeredocIndentation` document commit 7f0a5890ba8649b4b48c4d3e2d90eec24f920b9f Author: fatkodima Date: Wed Nov 29 15:16:38 2023 +0200 Optimize rspec tests commit 4753e929e04d090df098ca8c53c8bd2b87a3756b Merge: a31a37cef 2f9a2d2d6 Author: Koichi ITO Date: Thu Nov 30 01:03:37 2023 +0900 Merge pull request #12421 from koic/make_style_self_assignment_aware_of_some_operators Make `Style/SelfAssignment` aware of some operators commit 2f9a2d2d64972649f145130ab26a6b7e69a5556e Author: Koichi ITO Date: Wed Nov 29 17:42:47 2023 +0900 Make `Style/SelfAssignment` aware of some operators Follow up https://github.com/rubocop/rubocop/issues/12410#issuecomment-1825941817. This PR makes `Style/SelfAssignment` aware of `%`, `^`, `<<`, and `>>` operators. commit a31a37cef46b707b8d4b2e221b5a40fd50915afe Merge: 518211603 7a66f24f0 Author: Koichi ITO Date: Wed Nov 29 16:42:46 2023 +0900 Merge pull request #12387 from Earlopain/fix-zero-method-for-float-comparison [Fix #12146] Fix a false positive for `Lint/FloatComparison` commit 7a66f24f0e69f5a46a2d0aaa622e8551429222d6 Author: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Wed Nov 29 08:24:50 2023 +0100 [Fix #12146] Fix a false positive for `Lint/FloatComparison` commit 518211603ba759d8f0a99767abed684ac2b83bfb Merge: af5b0d7da f45ae1035 Author: Koichi ITO Date: Tue Nov 28 16:46:58 2023 +0900 Merge pull request #12415 from fatkodima/enhance-lint-self_assignment Enhance `Lint/SelfAssignment` to check attribute assignment and key assignment commit af5b0d7da615a949e99040ac69a0620c9764ec44 Author: fatkodima Date: Tue Nov 28 09:44:10 2023 +0200 Add new `Style/ArrayFirstLast` cop (#12416) commit f45ae103543a4149ee15cccc95dbb8c41aa02f03 Author: fatkodima Date: Sat Nov 25 17:36:28 2023 +0200 Enhance `Lint/SelfAssignment` to check attribute assignment and key assignment commit cb43b34a8f6a53297c8fe7246520be75b6f3af88 Merge: 0c1671f8b fe5ed60d7 Author: Koichi ITO Date: Mon Nov 27 10:39:12 2023 +0900 Merge pull request #12418 from fatkodima/redundant_safe_navigation-conversions-with-defaults Enhance `Lint/RedundantSafeNavigation` to handle conversion methods with defaults commit 0c1671f8b8829e5e3c372bd97ec51aaa5191af4d Merge: f466f86b3 7512e8a48 Author: Koichi ITO Date: Mon Nov 27 02:47:44 2023 +0900 Merge pull request #12414 from koic/make_style_inverse_methods_aware_of_safe_navigation_operator [Fix #12413] Make `Style/InverseMethods` aware of safe navigation operator commit fe5ed60d7bff2a5d245a769814fd089e9e478144 Author: fatkodima Date: Sun Nov 26 03:06:51 2023 +0200 Enhance `Lint/RedundantSafeNavigation` to handle conversion methods with defaults commit f466f86b396c0d29bd1131f3942aab3bd5e73fe3 Merge: be4a19ad2 f4e46689c Author: Koichi ITO Date: Sun Nov 26 01:07:00 2023 +0900 Merge pull request #12408 from koic/make_style_map_to_hash_aware_of_safe_navigation_operator Make `Style/MapToHash` aware of safe navigation operator commit 7512e8a4890e6ae096ea863cccf125a286e211c9 Author: Koichi ITO Date: Sat Nov 25 16:05:15 2023 +0900 [Fix #12413] Make `Style/InverseMethods` aware of safe navigation operator Fixes #12413. This PR makes `Style/InverseMethods` aware of safe navigation operator. commit be4a19ad2acd6b5a57ebe6999145c01685af9a31 Merge: 09cba51d5 45ca1ebf8 Author: Koichi ITO Date: Sat Nov 25 09:02:52 2023 +0900 Merge pull request #12411 from koic/fix_incorrect_autocorrect_for_lint_safe_navigation_chain [Fix #12409] Fix an incorrect autocorrect for `Lint/SafeNavigationChain` commit 45ca1ebf8d87b54caac7d68313a4b4b09d09a8bd Author: Koichi ITO Date: Sat Nov 25 00:26:10 2023 +0900 [Fix #12409] Fix an incorrect autocorrect for `Lint/SafeNavigationChain` Fixes #12409. This PR fixes an incorrect autocorrect for `Lint/SafeNavigationChain` when ordinary method chain exists after safe navigation leading dot method call. commit 09cba51d58711bade818422be0b79fb87b0db8a1 Merge: 5c81b5687 84da43251 Author: Koichi ITO Date: Fri Nov 24 22:56:54 2023 +0900 Merge pull request #12407 from koic/fix_incorrect_autocorrect_for_layout_single_line_block_chain_with_style_map_to_hash Fix an incorrect autocorrect for `Style/MapToHash` with `Layout/SingleLineBlockChain` commit f4e46689cf499445c3f2ea5e9e239d758db2b148 Author: Koichi ITO Date: Fri Nov 24 18:50:16 2023 +0900 Make `Style/MapToHash` aware of safe navigation operator Follow up https://github.com/rubocop/rubocop/pull/12407#issuecomment-1825353313. This PR makes `Style/MapToHash` aware of safe navigation operator. commit 84da43251f380c0cc14eeb361e84bcaf2ead3f48 Author: Koichi ITO Date: Fri Nov 24 12:23:16 2023 +0900 Fix an incorrect autocorrect for `Style/MapToHash` and `Layout/SingleLineBlockChain` This PR fixes an incorrect autocorrect for `Style/MapToHash` with `Layout/SingleLineBlockChain` which makes the following syntax error occur: ```console $ cat example.rb obj.map { |i| foo(i) }.to_h .bar $ bundle exec rubocop -A example.rb --only Style/MapToHash,Layout/SingleLineBlockChain Inspecting 1 file F Offenses: example.rb:1:5: C: [Corrected] Style/MapToHash: Pass a block to to_h instead of calling map.to_h. obj.map { |i| foo(i) }.to_h ^^^ example.rb:1:23: C: [Corrected] Layout/SingleLineBlockChain: Put method call on a separate line if chained to a single line block. obj.map { |i| foo(i) }.to_h ^^^^^ example.rb:3:4: F: Lint/Syntax: unexpected token tDOT (Using Ruby 3.3 parser; configure using TargetRubyVersion parameter, under AllCops) .bar ^ 1 file inspected, 3 offenses detected, 2 offenses corrected ``` commit 5c81b568798f3c9d7d3bd7bcb0d3ddd637f4d548 Merge: 96878d3b7 eebd60b1b Author: Koichi ITO Date: Thu Nov 23 12:15:57 2023 +0900 Merge pull request #12405 from koic/fix_a_false_positive_for_layout_rescue_ensure_alignment [Fix #12404] Fix a false positive for `Layout/RescueEnsureAlignment` commit 96878d3b70b3ee7970da80bdf7d3733890208b47 Merge: de86a68a5 bce158b32 Author: Koichi ITO Date: Wed Nov 22 18:12:27 2023 +0900 Merge pull request #12403 from koic/fix_false_negatives_for_style_redundant_line_continuation [Fix #12402] Fix false negatives for `Style/RedundantLineContinuation` commit eebd60b1b56ea60ff34d808c05f2f4faf275c949 Author: Koichi ITO Date: Wed Nov 22 13:37:44 2023 +0900 [Fix #12404] Fix a false positive for `Layout/RescueEnsureAlignment` Fixes #12404. This PR fixes a false positive for `Layout/RescueEnsureAlignment` when aligned `rescue` in `do`-`end` numbered block in a method. commit de86a68a5260ce80ebac5691ecc6a8e929bd38a7 Author: Koichi ITO Date: Sun Nov 19 01:57:50 2023 +0900 [Fix #12370] Make `Style/HashEachMethods` aware of unused block value Fixes #12370. This PR makes `Style/HashEachMethods` aware of unused block value. And this PR suppresses the following new offense in this repository: ```console $ bundle exec rubocop --only Style/HashEachMethods -A (snip) Offenses: lib/rubocop/cop/style/bisected_attr_accessor.rb:36:11: C: [Corrected] Style/HashEachMethods: Use each_value instead of each, and remove the unused _visibility block argument. find_macros(class_node.body).each do |_visibility, macros| ... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1519 files inspected, 1 offense detected, 1 offense corrected ``` commit bce158b32a4c4e2ff1f5b6f92bcfdcd6571d403f Author: Koichi ITO Date: Tue Nov 21 12:39:48 2023 +0900 [Fix #12402] Fix false negatives for `Style/RedundantLineContinuation` Fixes #12402. This PR fixes false negatives for `Style/RedundantLineContinuation` when redundant line continuations for a block are used, especially without parentheses around first argument. commit 10c8d32581d7e3fb3665ba1022675761e4d15d77 Author: Koichi ITO Date: Sat Nov 18 01:31:34 2023 +0900 [Fix #12296] Support `Redundant*Names` options for `Style/ArgumentsForwarding` Fixes #12296. This PR supports `RedundantRestArgumentNames`, `RedundantKeywordRestArgumentNames`, and `RedundantBlockArgumentNames` options for `Style/ArgumentsForwarding`. Meaningless names that are commonly used can be anonymized by default as part of the new `Redundant*Names` defaults. e.g., `*args`, `**options`, `&block`, and some argument names. Names not on this list are likely to be meaningful and are allowed by default. This approach is designed to only detect generally meaningless names without the need for users to edit the configuration for each meaningful name, with the expectation that the default settings will work well for most cases. commit dc4cbf069b28c89d3a656d9c8153090b45242277 Author: Koichi ITO Date: Wed Nov 15 01:20:54 2023 +0900 [Fix #12353] Add new `Style/SuperWithArgsParentheses` cop Fixes #12353. This PR adds new `Style/SuperWithArgsParentheses` cop ```ruby # bad super name, age # good super(name, age) ``` The cop is named `Style/SuperWithArgsParentheses`, contrasting with `Style/MethodCallWithArgsParentheses`. Unlike `Style/MethodCallWithArgsParentheses`, which requires consideration for no-parentheses usage in DSL. `super` is not used as a DSL, so it is enabled by default. For these reasons, it has been made into a separate, new cop. commit 2c0f759c96c11a8da7811eec9904436c46632c02 Author: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Fri Nov 10 19:33:52 2023 +0100 [Fix #12373] Fix a false negative for Lint/SymbolConversion This PR fixes a false negative for `Lint/SymbolConversion` when using string interpolation commit 7449316f5f4481da4c944346be8fba68887ec520 Author: Koichi ITO Date: Mon Nov 20 17:35:17 2023 +0900 Remove useless `require 'etc'` Follow up https://github.com/rubocop/rubocop/pull/2408 commit 48808a31e19af0198eeaba1f3913d74b68863c29 Author: Koichi ITO Date: Sun Nov 19 17:19:34 2023 +0900 Use `RuboCop::Cop::Registry.global` instead of `RuboCop::Cop::Cop.registry` Follow up https://github.com/rubocop-hq/rubocop/pull/8095 commit 4c40a2df9ed41721991c04169939c667b311c93a Merge: 2b27768a6 053d68c91 Author: Koichi ITO Date: Sat Nov 18 15:09:25 2023 +0900 Merge pull request #12384 from koic/fix_false_positives_for_lint_void [Fix #12377] Fix false positives for `Lint/Void` commit 2b27768a61a5fd38ebc5e189bd2258a5ebb0b0ad Author: Koichi ITO Date: Fri Nov 17 15:09:05 2023 +0900 Fix false positive for `Style/RedundantReturn` Follow up https://github.com/rubocop/rubocop/pull/12395#issuecomment-1814927230. This PR fixes false positive for `Style/RedundantReturn` when `proc` ending with `return`. commit 5ccf58a239aeb5264a63d45a21a5674120e38809 Merge: 37fe32dfc c780552c2 Author: Koichi ITO Date: Fri Nov 17 00:17:30 2023 +0900 Merge pull request #12395 from koic/fix_false_negatives_for_style_redundant_return [Fix #12394] Fix false negatives for `Style/RedundantReturn` commit c780552c2cc930ade676d8ba459dc64793b1c6c6 Author: Koichi ITO Date: Thu Nov 16 11:19:00 2023 +0900 [Fix #12394] Fix false negatives for `Style/RedundantReturn` Fixes #12394. This PR fixes false negatives for `Style/RedundantReturn` when `lambda`, `->`, or `proc` ending with `return`. commit 053d68c9119513442d321dc5dfa8461e144a1642 Author: Koichi ITO Date: Sat Nov 11 02:48:13 2023 +0900 [Fix #12377] Fix false positives for `Lint/Void` Fixes #12377. This PR fixes false positives for `Lint/Void` when a collection literal that includes non-literal elements in a method definition. commit 37fe32dfce44b3568047cfb4568c566cac32b31c Merge: 16e8a30da 7a7568149 Author: Koichi ITO Date: Wed Nov 15 01:26:00 2023 +0900 Merge pull request #12389 from themilkman/sublime_text_doc_extensions [Docs] Add Sublime Text section for LSP usage commit 7a756814999426bc52535a3f9d612e5227450ac7 Author: Erik-B. Ernst Date: Tue Nov 14 15:06:37 2023 +0100 [Docs] Extend Sublime Text integration sections The already mentioned plugin is not actively maintained anymore, thus added the well maintained SublimeLinter-rubocop plugin. Also added docs on LSP usage with Sublime Text. commit 16e8a30da61a6b37439020ec93604c231e686f80 Author: Koichi ITO Date: Tue Nov 14 01:38:31 2023 +0900 [Docs] Update the LSP doc VS Code Follow up https://github.com/rubocop/vscode-rubocop/commit/bfbb570. commit 8b7974911ada1a8723fccf0dfdc4bd5cbc835ef8 Merge: 9f6bb354d 2bb0bc773 Author: Koichi ITO Date: Mon Nov 13 13:33:27 2023 +0900 Merge pull request #12381 from koic/make_style_redundant_parentheses_aware_of_lambda_or_proc [Fix #12380] Make `Style/RedundantParentheses` aware of lambda or proc commit 9f6bb354d32d2bc8d6a3b9609827283598719df9 Author: Koichi ITO Date: Sun Nov 12 15:26:09 2023 +0900 Use `RuboCop::Cop::Base` instead of deprecated `RuboCop::Cop::Cop` Follow up https://github.com/rubocop/rubocop/commit/f8813e76 This commit uses `RuboCop::Cop::Base` instead of deprecated `RuboCop::Cop::Cop` API. commit 106c17bc32c302f56567938d86910e433bd32ffd Author: Koichi ITO Date: Sat Nov 11 22:47:40 2023 +0900 [Docs] Update the organization of the fast-ruby repo https://github.com/JuanitoFatas/fast-ruby has been transferred to https://github.com/fastruby/fast-ruby. So this commit avoids useless HTTP redirect. commit e17d887e99618f281dd54100f796a46241c09ff5 Merge: 95b029055 cee469456 Author: Koichi ITO Date: Sat Nov 11 03:20:33 2023 +0900 Merge pull request #12378 from koic/fix_a_false_negative_for_style_semicolon Fix a false negative for `Style/Semicolon` commit 95b029055275c927f73e2840d49befa1a66c3eae Merge: 80fce1231 2a056d28d Author: Koichi ITO Date: Fri Nov 10 16:15:07 2023 +0900 Merge pull request #12376 from koic/fix_a_false_positive_for_layout_space_before_semicolon [Fix #12374] Fix a false positive for `Layout/SpaceBeforeSemicolon` commit 2bb0bc77326b1a1c463ce91fed654b9b8e8f9eb1 Author: Koichi ITO Date: Fri Nov 10 12:06:26 2023 +0900 [Fix #12380] Make `Style/RedundantParentheses` aware of lambda or proc Fixes #12380. This PR makes `Style/RedundantParentheses` aware of lambda or proc. commit cee46945686b8d629dd0be83530d75685c4b08ed Author: Koichi ITO Date: Fri Nov 10 02:30:44 2023 +0900 Fix a false negative for `Style/Semicolon` This PR fixes a false negative for `Style/Semicolon` when a semicolon at the beginning of a lambda block. commit 2a056d28d2facc9c91075f4c9045ab20fca24082 Author: Koichi ITO Date: Thu Nov 9 15:24:18 2023 +0900 [Fix #12374] Fix a false positive for `Layout/SpaceBeforeSemicolon` Fixes #12374. This PR fixes a false positive for `Layout/SpaceBeforeSemicolon` when a space between an opening lambda brace and a semicolon. NOTE: When `Token#left_curly_brace?` supports `:tLAMBEG`, the condition `token.type == :tLAMBEG` can be removed. commit 80fce12310e029a9bbfecfeaa63a9cbc040cb4d9 Author: Koichi ITO Date: Wed Nov 8 01:17:53 2023 +0900 [Fix #12311] Fix false negatives for `Style/RedundantParentheses` Fixes #12311. This PR fixes false negatives for `Style/RedundantParentheses` when parentheses around logical operator keywords in method definition. commit e312ea973dd17b9a45f9312fc52d87d0e68a01f0 Author: Koichi ITO Date: Thu Nov 9 10:58:09 2023 +0900 [Fix #12372] Fix a false negative for `Lint/Debugger` Fixes #12372. This PR fixes a false negative for `Lint/Debugger` when used within method arguments a `begin`...`end` block. commit f53f5a097f2dcdc51e0ccebeb6a1315b03d22c3d Author: Koichi ITO Date: Wed Nov 8 18:35:54 2023 +0900 Remove useless `require 'ostruct'` Follow up https://github.com/rubocop/rubocop/pull/10217. This commit removes useless `require 'ostruct'`. commit 2d48430f546f62cf48685b494992dfa1f6272c02 Merge: c0f5b35bc 95a9afda3 Author: Koichi ITO Date: Tue Nov 7 11:19:52 2023 +0900 Merge pull request #12366 from eugeneius/extra_spacing_two_comments Don't assume first and last comments are aligned commit 95a9afda3b04aeacf4705527672a0b34af9a6a03 Author: Eugene Kenny Date: Mon Nov 6 22:55:39 2023 +0000 Don't assume first and last comments are aligned Currently we use `each_cons(3)` to find comments that align with their neighbours, but this means the first and last comments aren't checked. We treat them as always aligned, but this leads to false negatives. We can instead use `each_cons(2)` to look at each pair of comments and add both if they're aligned. This does mean that sometimes lines are added twice, but this is fine since `Set#<<` is idempotent. commit c0f5b35bc641b12a3d1f7fbc7c7ac233b37ee87b Merge: d3fb79b24 e389a3326 Author: Koichi ITO Date: Tue Nov 7 01:10:46 2023 +0900 Merge pull request #12364 from koic/fix_incorrect_rendering_in_formatter_html_formatter [Fix #12363] Fix incorrect rendering in `HTMLFormatter` formatter commit e389a33266c0555d2544d95c58a52190ced2bf37 Author: Koichi ITO Date: Mon Nov 6 13:50:46 2023 +0900 [Fix #12363] Fix incorrect rendering in `HTMLFormatter` formatter Fixes #12363. This PR fixes incorrect rendering of HTML character entities in `HTMLFormatter` formatter. commit d3fb79b24c03b1b2ee1afe8e87b66564761e21f1 Author: Sam Bostock Date: Mon Oct 23 13:46:26 2023 -0400 Add `InternalAffairs/NodeFirstOrLastArgument` cop This cop checks for `node.arguments.first` and `node.arguments.last`, and corrects them to `node.first_argument` and `node.last_argument`, respectively. Version 1.30 of `rubocop-ast` adds support for `first_argument` on block nodes, and is therefore required for this cop not to produce false positives for those node types. commit 94161a805b17079514562114b0514d17d9fdaca9 Author: Koichi ITO Date: Sun Nov 5 15:44:28 2023 +0900 [Fix #12337] Support `EnforcedStyleForRationalLiterals` for `Layout/SpaceAroundOperators` Fixes #12337. This PR supports `EnforcedStyleForRationalLiterals` option for `Layout/SpaceAroundOperators`. Like `SupportedStylesForExponentOperator` option, the default follows the style guide with `no_space`. commit 857918124a1320cbc09f6cb6db9a3126dd6ff8ca Author: Koichi ITO Date: Sun Nov 5 23:06:10 2023 +0900 [Fix #12361] Fix an incorrect autocorrect for `Naming/BlockForwarding` Fixes #12361. Fix an incorrect autocorrect for `Naming/BlockForwarding` and `Style/ArgumentsForwarding` when autocorrection conflicts for anonymous arguments. commit d3de2ae819a8d3ae56fe4f7c9708d00e0ca45ff6 Merge: 623070763 4d9efdc8a Author: Koichi ITO Date: Mon Nov 6 00:25:21 2023 +0900 Merge pull request #12330 from koic/change_make_style_auto_resource_cleanup_aware_of_tempfile_open [Fix #12328] Make `Style/AutoResourceCleanup` aware of `Tempfile.open` commit 4d9efdc8a502eee35550f00ed220a4c07af63db8 Author: Koichi ITO Date: Fri Nov 3 17:41:21 2023 +0900 [Fix #12328] Make `Style/AutoResourceCleanup` aware of `Tempfile.open` Fixes #12328. This PR makes `Style/AutoResourceCleanup` aware of `Tempfile.open`. commit 6230707636517b887589ab0995cf271e27f0a520 Author: Koichi ITO Date: Sun Nov 5 16:31:38 2023 +0900 Add `StyleGuide` for `Style/SingleLineDoEndBlock` Follow up https://github.com/rubocop/ruby-style-guide/pull/922. commit 605a5e2174b540791aa33393253de4e9954004c7 Author: Koichi ITO Date: Sun Nov 5 02:07:20 2023 +0900 [Docs] Add missing spaces Follow up https://github.com/rubocop/ruby-style-guide/pull/928. commit c1d0505452116f3a5275e1a5fb94f244af72a801 Merge: d7dc94dd1 b1fe80011 Author: Koichi ITO Date: Sat Nov 4 01:58:46 2023 +0900 Merge pull request #12332 from koic/make_internal_affairs_method_name_equal_aware_of_negated_equal Make `InternalAffairs/MethodNameEqual` aware of `!=` commit b1fe8001101aeb117b147374e78422a22b319c90 Author: Koichi ITO Date: Sat Nov 4 00:20:16 2023 +0900 Make `InternalAffairs/MethodNameEqual` aware of `!=` This PR makes `InternalAffairs/MethodNameEqual` aware of `node.method_name != method_name` and suppresses the following new offenses: ```console $ bundle exec rubocop -a (snip) Offenses: lib/rubocop/cop/lint/duplicate_methods.rb:256:13: C: [Corrected] InternalAffairs/MethodNameEqual: Use !ancestor.method?(:class_eval) instead. ancestor.method_name != :class_eval && !ancestor.class_constructor? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/style/auto_resource_cleanup.rb:28:13: C: [Corrected] Style/NegatedIf: Favor unless over if for negative conditions. next if !node.method?(target_method) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/style/auto_resource_cleanup.rb:28:21: C: [Corrected] InternalAffairs/MethodNameEqual: Use !node.method?(target_method) instead. next if node.method_name != target_method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/style/conditional_assignment.rb:537:32: C: [Corrected] InternalAffairs/MethodNameEqual: Use !node.method?(:[]=) instead. node.send_type? && node.method_name != :[]= ^^^^^^^^^^^^^^^^^^^^^^^^ 1517 files inspected, 4 offenses detected, 4 offenses corrected ``` commit d7dc94dd16a7ad23a804ac5c4d485f82fc90d60a Merge: fbe72848c 930755cd4 Author: Koichi ITO Date: Fri Nov 3 01:20:24 2023 +0900 Merge pull request #12326 from koic/fix_an_error_for_style_redundant_double_splat_hash_braces Fix an error for `Style/RedundantDoubleSplatHashBraces` commit fbe72848c03d59ca5fe21c0b1c886799bd300a5b Merge: 3e39a762b 558a7399e Author: Koichi ITO Date: Thu Nov 2 01:49:09 2023 +0900 Merge pull request #12329 from koic/fix_error_for_style_combinable_loops [Fix #12322] Fix an error for `Style/CombinableLoops` commit 558a7399e5d1bf5b05d4a04c45337b75ac4bb045 Author: Koichi ITO Date: Wed Nov 1 13:29:31 2023 +0900 [Fix #12322] Fix an error for `Style/CombinableLoops` Fixes #12322. This PR fixes an error for `Style/CombinableLoops` when looping over the same data for the third consecutive time or more. commit 3e39a762b7e941e730fce65581152e4cf18b5637 Merge: f981a1ad4 4b468726b Author: Koichi ITO Date: Tue Oct 31 23:20:20 2023 +0900 Merge pull request #12325 from koic/fix_error_for_layout_rescue_ensure_alignment [Fix #12324] Fix an error for `Layout/RescueEnsureAlignment` commit 4b468726bfd789d86935e8fe80115f81c25cec5c Author: Koichi ITO Date: Tue Oct 31 00:03:01 2023 +0900 [Fix #12324] Fix an error for `Layout/RescueEnsureAlignment` Fixes #12324. This PR fixes an error for `Layout/RescueEnsureAlignment` when using `rescue` in `do`...`end` block assigned to object attribute. commit 930755cd46ebf3861ee0472a0cfb874413f4328d Author: Koichi ITO Date: Tue Oct 31 16:12:51 2023 +0900 Fix an error for `Style/RedundantDoubleSplatHashBraces` Fixes https://github.com/rubocop/rubocop/issues/12275#issuecomment-1786554892. This PR fixes an error for `Style/RedundantDoubleSplatHashBraces` when method call for parenthesized no hash double double splat. commit f981a1ad439a23a6d24c3bcda76764f14529f9cd Merge: fe802d9a3 afab18cdf Author: Koichi ITO Date: Mon Oct 30 13:59:41 2023 +0900 Merge pull request #12319 from koic/add_a_project_spec Add a project spec commit afab18cdf7903af585d412ce7de43281b734ef31 Author: Koichi ITO Date: Sat Oct 28 13:19:06 2023 +0900 Add a project spec Follow up https://github.com/rubocop/rubocop/commit/d995cb4 This PR adds a project spec to prevent an unexpected changelog entry file path. For instance, if an unexpected file named `changelog/changelog/fix_foo.md` exists, it will fail as follows: ```console $ bundle exec rspec spec/project_spec.rb:309 (snip) 1) RuboCop Project Changelog future entries will not have a directory Failure/Error: expect(Dir[dir].all? { |path| File.file?(path) }).to be(true) expected true got false # ./spec/project_spec.rb:309:in `block (4 levels) in ' Finished in 0.02034 seconds (files took 1.71 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/project_spec.rb:308 # RuboCop Project Changelog future entries will not have a directory ``` commit fe802d9a3b4dca31d1952d77205d2f3546882e93 Author: Koichi ITO Date: Sun Oct 29 15:23:14 2023 +0900 Fix typos commit 9109cc10315c35ed25189c616627a39cb1da04f5 Author: Koichi ITO Date: Sat Oct 28 14:24:30 2023 +0900 Use RuboCop RSpec 2.25 https://github.com/rubocop/rubocop-rspec/releases/tag/v2.25.0 commit d67dd0334edeec9ca9d9ac1d625b8da2d46e622a Merge: a4754075c afa41965a Author: Koichi ITO Date: Sat Oct 28 13:51:01 2023 +0900 Merge pull request #12318 from djpowers/patch-2 Update Helix LSP config based on v23.10 changes commit afa41965a9463dab806f124a2b48981cde39f32d Author: Dave Powers Date: Fri Oct 27 10:47:43 2023 -0400 Update Helix LSP config based on v23.10 changes - retain configuration example for older versions commit a4754075c0ddc6babf0a1a05dfee540650316a80 Author: Koichi ITO Date: Fri Oct 27 02:03:57 2023 +0900 Suppress a Ruby warning when using Ruby 3.3.0dev Follow up #12313. `base64` is not needed at runtime, but it was required as a test dependency. So, this PR suppresses the following warning when using Ruby 3.3.0dev: ```consle $ ruby -v ruby 3.3.0dev (2023-10-23T08:04:27Z master e6fcf07a6f) [x86_64-darwin22] $ cd path/to/rubocop $ bundle exec rspec /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/webmock-3.19.1/lib/webmock/util/headers.rb:3: warning: base64 which will no longer be part of the default gems since Ruby 3.4.0. Add base64 to your Gemfile or gemspec. ``` https://app.circleci.com/pipelines/github/rubocop/rubocop/10108/workflows/20097132-bbe3-4fa4-ad7e-de7c30c86e69/jobs/291956?invite=true#step-104-0_163 The `base64` dependency can be removed from Gemfile when https://github.com/bblimke/webmock/pull/1041 is merged and released. It's a workaround until then. commit fa2727e1e44322d12a0edbb9e2c419c549ffcecd Author: Bozhidar Batsov Date: Thu Oct 26 12:53:49 2023 +0300 Tweak wording commit 0a43c2f4dde06adf1e7b02c36bdd15cc86214e09 Author: Bozhidar Batsov Date: Thu Oct 26 12:46:08 2023 +0300 Switch back the docs version commit 47735efc2b410578a196fd2758da87d01802c655 Author: Bozhidar Batsov Date: Thu Oct 26 12:44:23 2023 +0300 Cut 1.57.2 commit 4ab36220f2cb0b13b45a2642024a1a33ac47efe5 Author: Bozhidar Batsov Date: Thu Oct 26 12:41:26 2023 +0300 Update Changelog commit d995cb457b1ca24ba3b2f5bb11ec72f1a63d4343 Author: Bozhidar Batsov Date: Thu Oct 26 12:40:50 2023 +0300 Fix a changelog entry commit d79ee4b3eefeabcef2de0894abe03bab69ab7ec5 Author: Koichi ITO Date: Thu Oct 26 12:10:56 2023 +0900 [Fix #12312] Fix an incorrect autocorrect for `Style/HashSyntax` Fixes #12312. This PR fixes an incorrect autocorrect for `Style/HashSyntax` when braced hash key and value are the same and it is used in `if`...`else`. commit b2b29da6406ed55fe42fe045435c29bed6635299 Author: Koichi ITO Date: Thu Oct 26 01:59:44 2023 +0900 [Fix #12310] Drop `base64` gem from runtime dependency Fixes #12310. This PR drops `base64` gem from runtime dependency. RuboCop only uses `Base64.encode64` from the `base64` gem. Therefore, there's no need to depend on the entire `base64` gem. The implementation of `Base64.encode64` is quite simple: https://github.com/ruby/base64/blob/v0.1.1/lib/base64.rb#L27-L40 This change is a better approach that has also been adopted by https://github.com/rack/rack/pull/2110. commit 36f62b6b4e98c64c27ab244b394ab8194036aea6 Author: Koichi ITO Date: Wed Oct 25 12:37:40 2023 +0900 [Fix #12307] Fix an infinite loop error for `Layout/EndAlignment` Fixes #12307. This PR fixes an infinite loop error for `Layout/EndAlignment` when `EnforcedStyleAlignWith: variable` and using a conditional statement in a method argument on the same line and `end` with method call is not aligned. commit 34e77c6f25be91cca0d20f1bebfe32ba163ff24d Author: Koichi ITO Date: Wed Oct 25 01:22:50 2023 +0900 Tweak offense message for `Lint/Void` This commit tweaks offense message for `Lint/Void` when registering offenses of void constants. commit 7bedbf497b390fe6527e8a75f248b62cf2485341 Author: Koichi ITO Date: Tue Oct 24 13:49:00 2023 +0900 [Fix #12274] Fix a false positive for `Lint/Void` Fixes #12274. This PR fixes a false positive for `Lint/Void` when `each`'s receiver is an object of `Enumerator` to which `filter` has been applied. `each` blocks are allowed to prevent false positives. The expression inside the following block is not void: ```ruby enumerator = [1, 2, 3].filter enumerator.each { |item| item >= 2 } #=> [2, 3] ``` This might introduce false negatives, but higher severity Lint cop should aim for as safe detections as possible, I think. commit 21cad5190a5d74751aae03590ba7458e0c1c11d2 Author: Jonas Arvidsson Date: Sat Oct 21 17:07:03 2023 +0200 [Fix #11652] Generate inherit_from correctly also with ERB The problem with the existing algorithm, for generating the inherit_from line in --auto-gen-config runs, was that we started by removing the inherit_from (if present) and then inserted it later. The things we must deal with in the algorithm are * there could be a pre-existing inherit_from in .rubocop.yml, or not * there could be a YAML doc start ---, or not * there could be inheritance from one or multiple files A more robust approach to the removing, generating, and re-inserting is to assume that any pre-existing inherit_from directive is already in the right place. By replacing it with a placeholder and later replacing the placeholder with the new inheritance directive, we will get it right without much effort. commit 41dda1ff1380a4f7b7d63cdec903dad496751754 Merge: 616060a39 1725bdc49 Author: Koichi ITO Date: Tue Oct 24 10:13:13 2023 +0900 Merge pull request #12304 from koic/fix_error_for_style_identical_conditional_branches [Fix 12300] Fix an error for `Style/IdenticalConditionalBranches` commit 1725bdc49d166da1fc2b6838b7c22782cc48c3ab Author: Koichi ITO Date: Mon Oct 23 19:21:32 2023 +0900 [Fix 12300] Fix an error for `Style/IdenticalConditionalBranches` Fixes #12300. This PR fixes an error for `Style/IdenticalConditionalBranches` when `if`...`else` with identical leading lines and using index assign. In RuboCop, the `send` node is used instead of the `indexasgn` node, so `name` cannot be used. https://github.com/rubocop/rubocop-ast/blob/v1.29.0/lib/rubocop/ast/node/indexasgn_node.rb commit 616060a39cc10826ff64207c8f42d9d8c6ba6efb Merge: a35f7c3af e5866b655 Author: Koichi ITO Date: Mon Oct 23 03:22:15 2023 +0900 Merge pull request #12285 from koic/fix_false_positives_for_style_single_argument_dig [Fix #12284] Fix false positives for `Style/SingleArgumentDig` commit a35f7c3af2a50d109ea3b52d0a62953a2f75aaf9 Merge: a797c9879 a17909d43 Author: Koichi ITO Date: Sun Oct 22 11:37:03 2023 +0900 Merge pull request #12302 from koic/make_style_redundant_filter_chain_aware_of_safe_navigation [Fix #12301] Make `Style/RedundantFilterChain` aware of safe navigation commit a17909d43a04fca98f7a153814e4bbe9413632d9 Author: Koichi ITO Date: Sat Oct 21 22:06:45 2023 +0900 [Fix #12301] Make `Style/RedundantFilterChain` aware of safe navigation Fixes #12301. This PR makes `Style/RedundantFilterChain` aware of safe navigation. commit a797c9879506139b2ceb2cb01e581fc24df09775 Merge: 79f81874f 9409b7208 Author: Koichi ITO Date: Sat Oct 21 03:23:09 2023 +0900 Merge pull request #12299 from koic/fix_a_false_positive_for_style_redundant_parentheses [Fix #12298] Fix a false positive for `Style/RedundantParentheses` commit 9409b720881098a5c6a6f7b5fe8d260aa55f8b74 Author: Koichi ITO Date: Fri Oct 20 12:31:58 2023 +0900 [Fix #12298] Fix a false positive for `Style/RedundantParentheses` Fixes #12298. This PR fixes a false positive for `Style/RedundantParentheses` when using a parenthesized hash literal as the first argument in a method call without parentheses. commit 79f81874f0f30f2b7857e9bfd088be60720229c7 Merge: e8a492b39 33deae5af Author: Koichi ITO Date: Fri Oct 20 01:05:35 2023 +0900 Merge pull request #12294 from koic/fix_a_false_positive_for_style_redundant_double_splat_hash_braces [Fix #12293] Fix a false positive for `Style/RedundantDoubleSplatHashBraces` commit e8a492b3984e02f50c233697eec68286cb183d7f Merge: 671331155 9eeb2f411 Author: Koichi ITO Date: Thu Oct 19 11:02:44 2023 +0900 Merge pull request #12292 from koic/fix_a_false_positive_for_metrics_class_length [Fix #12291] Fix a false positive for `Metrics/ClassLength` commit 33deae5af943ae955ce10b32d594b7fcb34ec148 Author: Koichi ITO Date: Wed Oct 18 20:51:21 2023 +0900 [Fix #12293] Fix a false positive for `Style/RedundantDoubleSplatHashBraces` Fixes #12293. This PR fixes a false positive for `Style/RedundantDoubleSplatHashBraces` when using double splat hash braces with `merge` and method chain. commit 9eeb2f411c51567a052ad57229118be259b1ef63 Author: Koichi ITO Date: Wed Oct 18 11:13:54 2023 +0900 [Fix #12291] Fix a false positive for `Metrics/ClassLength` Fixes #12291. This PR fixes a false positive for `Metrics/ClassLength` when a class with a singleton class definition. commit 6713311554d74f55fed0df20ab2bf2298d672006 Merge: affbe3b3a 2a1687aae Author: Koichi ITO Date: Wed Oct 18 00:01:32 2023 +0900 Merge pull request #12288 from koic/fix_false_positive_for_style_redundant_double_splat_hash_braces [Fix #12286] Fix false positives for `Style/RedundantDoubleSplatHashBraces` commit 2a1687aaec48bb2d70d21306ad773282069235d2 Author: Koichi ITO Date: Tue Oct 17 10:57:13 2023 +0900 [Fix #12286] Fix false positives for `Style/RedundantDoubleSplatHashBraces` Fixes #12286. This PR fix false positives for `Style/RedundantDoubleSplatHashBraces` when using double splat with a hash literal enclosed in parenthesized ternary operator. commit e5866b655b3c579bb97b9c25328fd5033161e5fe Author: Koichi ITO Date: Sun Oct 15 16:41:01 2023 +0900 [Fix #12284] Fix false positives for `Style/SingleArgumentDig` Fixes #12284. This PR fixes false positives for `Style/SingleArgumentDig` when using some anonymous argument syntax. commit affbe3b3a66ce15534021548e282270c4a688962 Merge: c3ac85d84 1e5bd7e9d Author: Koichi ITO Date: Mon Oct 16 00:23:18 2023 +0900 Merge pull request #12283 from koic/fix_an_error_for_style_single_line_do_end_block Fix an error for `Style/SingleLineDoEndBlock` commit 1e5bd7e9d80fcfc47521b7c1f2d5a09f58203c2a Author: Koichi ITO Date: Sun Oct 15 00:05:31 2023 +0900 Fix an error for `Style/SingleLineDoEndBlock` This PR fixes the following error for `Style/SingleLineDoEndBlock` when using single line `do`...`end` with no body ```console $ echo 'foo do end' | bunlde exec rubocop --stdin test.rb -d --only Style/SingleLineDoEndBlock (snip) An error occurred while Style/SingleLineDoEndBlock cop was inspecting /Users/koic/src/github.com/rubocop/rubocop/test.rb:1:0. Expected a Parser::Source::Range, Comment or RuboCop::AST::Node, got NilClass /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/corrector.rb:111:in `to_range' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/corrector.rb:120:in `check_range_validity' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/parser-3.2.2.4/ lib/parser/source/tree_rewriter.rb:398:in `combine' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/parser-3.2.2.4/ lib/parser/source/tree_rewriter.rb:207:in `wrap' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/parser-3.2.2.4/ lib/parser/source/tree_rewriter.rb:243:in `insert_after' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/single_line_do_end_block.rb:45:in `block in on_block' ``` commit c3ac85d8445e0d821a34e1539fc46657f1620b5a Author: Koichi ITO Date: Sat Oct 14 03:30:10 2023 +0900 [Fix #12279] Fix false positives for `Lint/EmptyConditionalBody` Fixes #12279. This PR fixes false positives for `Lint/EmptyConditionalBody` when missing 2nd `if` body with a comment. commit a8bea2b9852281c31fd2c05048272a278851c73b Author: Koichi ITO Date: Sat Oct 14 02:04:32 2023 +0900 [Fix #12275] Fix a false positive for `Style/RedundantDoubleSplatHashBraces` Fixes #12275. This PR fixes a false positive for `Style/RedundantDoubleSplatHashBraces` when using double splat within block argument containing a hash literal in an array literal. commit b7fb0641a8289dc93401f1a95963fa43f7ed4a7d Author: Bozhidar Batsov Date: Fri Oct 13 09:37:22 2023 +0200 Switch back the docs version commit 9141fe50b7c3a884852f5e49688a3f5dd3d2f7e0 Author: Bozhidar Batsov Date: Fri Oct 13 09:35:57 2023 +0200 Cut 1.57.1 commit a302d0cf3a34016d2240e0183a04d3012d022a54 Author: Bozhidar Batsov Date: Fri Oct 13 09:35:36 2023 +0200 Update Changelog commit 12016d8894cff2cb079a26a51e4e5dc6a6cb936f Author: Koichi ITO Date: Fri Oct 13 12:24:09 2023 +0900 [Fix #12271] Fix a false positive for `Lint/RedundantSafeNavigation` Fixes #12271. This PR fixes a false positive for `Lint/RedundantSafeNavigation` when using snake case constant receiver. Camel case is used for naming classes and modules, while snake case is used for all other constants. This naming conforms with `Naming/ConstantName` cop. Since constants that turn into classes or modules are normally not `nil`, they will continue to be detected. However, this PR will update to allow safe navigation for constants in snake case. This change resolves both issue https://github.com/rubocop/rubocop-rails/issues/1104 and #12271. commit 128618c7a8e3336bbe9ff8f800a73ff04dfc7a81 Author: Koichi ITO Date: Thu Oct 12 11:30:56 2023 +0900 Fix false positives for `Style/RedundantDoubleSplatHashBraces` Fixes #12263. This PR fixes false positives for `Style/RedundantDoubleSplatHashBraces` when method call for no hash braced double splat receiver. The code shown in #12263 is incompatible as shown below and is a false positive: ```ruby def x(opts) = puts(opts) h = {foo: :bar} x(**h.merge(k: :h)) #=> {:foo=>:bar, :k=>:h} x(k: :v, **h) #=> {:k=>:v, :foo=>:bar} ``` commit 03cdf044710db32bd90dc6afa0234502c2b59ffb Merge: 42898bc38 7edb5cab7 Author: Koichi ITO Date: Thu Oct 12 17:22:13 2023 +0900 Merge pull request #12267 from ydah/fix/12261 Fix an infinite loop for `Layout/MultilineMethodCallIndentation` commit 7edb5cab7487973809ddade987f80ae7b131c81e Author: ydah <13041216+ydah@users.noreply.github.com> Date: Thu Oct 12 15:22:08 2023 +0900 [Fix #12261] Fix an infinite loop for `Layout/MultilineMethodCallIndentation` Fix: https://github.com/rubocop/rubocop/issues/12261 commit 42898bc383d883fe20148119c05a4039ac7ad7de Merge: 84840b894 a4a505da3 Author: Koichi ITO Date: Thu Oct 12 01:54:27 2023 +0900 Merge pull request #12266 from koic/fix_an_error_for_layout_multiline_method_call_indentation [Fix #12265] Fix an error for `Layout/MultilineMethodCallIndentation` commit a4a505da327c7a0dcd0e2d6bed2149628ed3e614 Author: Koichi ITO Date: Thu Oct 12 00:43:54 2023 +0900 [Fix #12265] Fix an error for `Layout/MultilineMethodCallIndentation` Fixes #12265. This PR fixes an error for `Layout/MultilineMethodCallIndentation` when usingarithmetic operation with block inside a grouped expression. commit 84840b894ee6316d4367daf4cc96e03456e7374f Author: Koichi ITO Date: Thu Oct 12 00:47:27 2023 +0900 Fix typos This commit fixes the following build error: ``` Check spelling of all files with codespell: spec/rubocop/cop/style/redundant_exception_spec.rb#L120 valiable ==> variable, valuable, available Check spelling of all files with codespell: spec/rubocop/cop/style/redundant_exception_spec.rb#L125 valiable ==> variable, valuable, available ``` https://github.com/rubocop/rubocop/actions/runs/6484903585 commit 873cb9f1dfd2d02a574f0ad95de36a3f33547b3a Author: ydah <13041216+ydah@users.noreply.github.com> Date: Mon Sep 11 23:35:28 2023 +0900 Fix an incorrect autocorrect for `Style/RedundantException` when message is not string commit e162c99c066dc9b98f61b2d99ec4a3a919cf9852 Author: Koichi ITO Date: Wed Oct 11 20:51:03 2023 +0900 Fix an incorrect autocorrect for `Style/RedundantDoubleSplatHashBraces` This PR fixes the following incorrect autocorrect for `Style/RedundantDoubleSplatHashBraces` when using double splat hash braces with `merge` method call twice. ```console $ bundle exec rspec spec/rubocop/cop/style/redundant_double_splat_hash_braces_spec.rb:82 Run options: include {:locations=>{"./spec/rubocop/cop/style/redundant_double_splat_hash_braces_spec.rb"=>[82]}} (snip) Failures: 1) RuboCop::Cop::Style::RedundantDoubleSplatHashBraces registers an offense when using double splat hash braces with `merge` method call twice Failure/Error: expect(new_source).to eq(correction) expected: "do_something(foo: bar, **options)\ndo_something(baz: qux, **options)\n" got: "do_something(foo: bar, **options)\ndo_something(baz: qux.merge(options))\n" (compared using ==) Diff: @@ -1,3 +1,3 @@ do_something(foo: bar, **options) -do_something(baz: qux, **options) +do_something(baz: qux.merge(options)) # ./lib/rubocop/rspec/expect_offense.rb:164:in `expect_correction' # ./spec/rubocop/cop/style/redundant_double_splat_hash_braces_spec.rb:90:in `block (2 levels) in ' Finished in 0.15475 seconds (files took 1.24 seconds to load) 1 example, 1 failure ``` commit 215ab03ccdf722ebc3b0c43a62649755f4280451 Author: Bozhidar Batsov Date: Wed Oct 11 12:51:41 2023 +0200 Switch back the docs version commit bfdb5ff4fec74c0dd154268a8e4b97dba7a79aed Author: Bozhidar Batsov Date: Wed Oct 11 12:49:25 2023 +0200 Cut 1.57 commit 872d7137fd26977273146a70df8a903dedfe93bd Author: Bozhidar Batsov Date: Wed Oct 11 12:49:00 2023 +0200 Update Changelog commit 402542229238227ca9e1655efd210f3f8f0a1e1b Author: sergey Date: Sat Oct 7 00:43:37 2023 +0300 [Fix #12076] Explicitly require fileutils in RuboCop::Server::Cache The "fileutils.rb" item is dynamically added to the `$LOADED_FEATURES` due to the autoloading when calling the `RuboCop::Server::Cache.dir`. Explicit require is added to achieve idempotency when initializing the `RuboCop::ResultCache.rubocop_required_features`. This change resolves the issue where the top level cache folder was named differently during two consecutive runs of rubocop. commit b4e2bdd0718e00bc0346717091d94f22b33e5510 Author: Koichi ITO Date: Wed Oct 11 18:58:04 2023 +0900 [Fix #12259] Fix an error for `Lint/MixedCaseRange` Fixes #12259. This PR fixes an error for `Lint/MixedCaseRange` when using nested character class in regexp. commit 986d047b8a6d4163329cdd4925726eae7885b6e6 Author: Koichi ITO Date: Wed Oct 11 16:22:16 2023 +0900 Fix an error for `Style/RedundantDoubleSplatHashBraces` Follow up #12258. This PR fixes the following error for `Style/RedundantDoubleSplatHashBraces`: ```console $ echo 'do_something(**options.merge(foo: bar, baz: qux))' | bundle exec rubocop --stdin test.rb -d -a --only Style/RedundantDoubleSplatHashBraces (snip) An error occurred while Style/RedundantDoubleSplatHashBraces cop was inspecting /Users/koic/src/github.com/rubocop/rubocop/test.rb:1:29. undefined method `join' for nil /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/redundant_double_splat_hash_braces.rb:61:in `opening_brace' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/redundant_double_splat_hash_braces.rb:45:in `autocorrect' ``` commit 81ef51ea121989cdf756c6e1c016fc2b5414bf4b Author: Koichi ITO Date: Wed Oct 11 11:55:34 2023 +0900 [Fix #12257] Make `Style/RedundantDoubleSplatHashBraces` aware of `merge` Resolves #12257. This PR makes `Style/RedundantDoubleSplatHashBraces` aware of `merge` methods. Instead of introducing a new cop, this `Style/RedundantDoubleSplatHashBraces` cop can be extended. commit 86c0e8daf5f30c8745e79ff1fff12c2a8b950376 Author: Koichi ITO Date: Sun Oct 8 16:50:02 2023 +0900 [Fix #12249] Fix a false positive `Style/IdenticalConditionalBranches` Fixes #12249. This PR fixes a false positive `Style/IdenticalConditionalBranches` when `if`..`else` with identical leading lines and assign to condition value. commit 6a100e60868c4543517e701a1728dd7ddae73384 Merge: 7b05f2a8f fb3415206 Author: Koichi ITO Date: Tue Oct 10 14:39:39 2023 +0900 Merge pull request #12255 from ydah/followup-12176 Remove redundant true/false returns commit fb3415206c8fcc8c1a856a8529b5e94069782115 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Tue Oct 10 13:42:30 2023 +0900 Remove redundant true/false returns Follow up: https://github.com/rubocop/rubocop/pull/12176#issuecomment-1752002311 commit 7b05f2a8fb4f62e26697bac8ba12f0369645ead8 Merge: 11d412fad ab72b2b0b Author: Koichi ITO Date: Tue Oct 10 12:23:08 2023 +0900 Merge pull request #12254 from joesiewert/empty-block-text Edit empty block overview text commit ab72b2b0b1e76f6738c51a4b0c1b253f77735e94 Author: Joe Siewert Date: Mon Oct 9 22:00:13 2023 -0500 Edit empty block overview text commit 11d412fadd5b0ef8ffc1db52be209cdf2b48e049 Merge: ece1a95d0 bc1b6a89e Author: Koichi ITO Date: Tue Oct 10 10:48:01 2023 +0900 Merge pull request #12253 from knu/accept_empty_string_literal_interpolated_in_words_literal Lint/LiteralInInterpolation: Accept an empty string literal interpolated in %W[]/%I[] commit bc1b6a89ecc5873932313451fb8acc487255a2db Author: Akinori MUSHA Date: Mon Oct 9 21:28:46 2023 +0900 Update `Lint/LiteralInInterpolation` to accept an empty string literal interpolated in %W[]/%I[] An empty string in those words literals is significant and must not be expanded. e.g. ```ruby system(*%W[git commit -m #{""} file]) ``` commit ece1a95d07f78d3124d699f382179fbc1a246731 Merge: 42fbe75ac 706b625e4 Author: Koichi ITO Date: Mon Oct 9 01:14:36 2023 +0900 Merge pull request #12247 from koic/fix_false_negatives_for_style_redundant_parentheses Fix false negatives for `Style/RedundantParentheses` commit 42fbe75ac38f53663d3f135a3336c0f9f5a26ed5 Merge: b5683e47f aee06d058 Author: Koichi ITO Date: Sun Oct 8 20:00:04 2023 +0900 Merge pull request #12250 from koic/mark_lint_redundant_require_statement_as_unsafe_autocorrect Mark `Lint/RedundantRequireStatement` as unsafe autocorrect commit 706b625e47fcd67bba199c71e2fc8cbe9d4e1094 Author: Koichi ITO Date: Sat Oct 7 00:50:46 2023 +0900 Fix false negatives for `Style/RedundantParentheses` This PR fix false negatives for `Style/RedundantParentheses` when using logical or comparison expressions with redundant parentheses. e.g. `assert(('rubocop-minitest' == actual))` commit aee06d058b7b242f9043bf9678514f288fd894dc Author: Koichi ITO Date: Sun Oct 8 13:02:00 2023 +0900 Mark `Lint/RedundantRequireStatement` as unsafe autocorrect Follow up https://github.com/rubocop/rubocop/pull/11931#issuecomment-1603717583. This PR marks `Lint/RedundantRequireStatement` as unsafe autocorrect because if `require 'pp'` is removed from one file, `NameError` can be encountered when another file uses `PP.pp`. commit b5683e47f9cadf22cd0ab9ff6b58bfe2cdfa0e62 Author: Koichi ITO Date: Sat Oct 7 15:24:05 2023 +0900 Remove an unused `include Alignment` commit a455e9d55771f1e3dfea0cc4183e66f9632b431c Merge: 26681f70a b9a90b5d7 Author: Koichi ITO Date: Fri Oct 6 16:38:35 2023 +0900 Merge pull request #12234 from koic/enhance_style_format_string_autocorrection Enhance `Style/FormatString`'s autocorrection commit b9a90b5d7f18576eff235a43441fa2d8536f6fd6 Author: Koichi ITO Date: Sun Oct 1 01:07:27 2023 +0900 Enhance `Style/FormatString`'s autocorrection This PR enhances `Style/FormatString`'s autocorrection when using known conversion methods whose return value is not an array. commit 26681f70adf4cfdf9e4daa429bea00adbffbd467 Author: Koichi ITO Date: Thu Oct 5 16:14:37 2023 +0900 Fix a link address for #12246 commit 59021624ce276edaca12812c39943116de7ee763 Author: Koichi ITO Date: Thu Oct 5 14:15:30 2023 +0900 Make `Lint/RedundantSafeNavigation` aware of constant receiver Fixes https://github.com/rubocop/rubocop-rails/issues/1104. This is an issue with RuboCop Rails, but it can likely be addressed as a generic issue. So, this PR makes `Lint/RedundantSafeNavigation` aware of constant receiver. Because use cases where a constant is `nil` are rare and an offense is detected when the receiver is a constant. And this cop is already marked as unsafe. commit bd214bd9e9c4ead369b4a20ec329897e8dbb288c Author: Koichi ITO Date: Thu Oct 5 00:42:14 2023 +0900 [Fix #12244] Fix a false negative for `Lint/Debugger` Fixes #12244. This PR fixes a false negative for `Lint/Debugger` when using debugger method inside block. commit 76c2bc551d1b08a9e34eec1d29d22536d8ba1991 Author: Koichi ITO Date: Wed Oct 4 19:14:33 2023 +0900 [Fix #12198] Fix an error for flip-flop with beginless or endless ranges Fixes #12198. Parser 3.2.2.4 includes https://github.com/whitequark/parser/pull/946. This PR requires Parser 3.2.2.4+ to fix an error for flip-flop with beginless or endless ranges. commit 8bc658e6f4083fb8df10ced0051d47201002fb86 Merge: 65f10c114 45174dc61 Author: Koichi ITO Date: Wed Oct 4 02:32:42 2023 +0900 Merge pull request #12240 from koic/fix_a_false_negative_for_metrics_module_length [Fix #12231] Fix a false negative for `Metrics/ModuleLength` commit 45174dc6170b63e9ed812149cc49993712b1afa7 Author: Koichi ITO Date: Tue Oct 3 12:46:20 2023 +0900 [Fix #12231] Fix a false negative for `Metrics/ModuleLength` Fixes #12231. This PR fixes a false negative for `Metrics/ModuleLength` when defining a singleton class in a module. commit 65f10c1146aa52b4b12ee6623e84a5d881176acb Author: Koichi ITO Date: Tue Oct 3 12:56:31 2023 +0900 Fix a build error This PR fixes the following build error in the codespell: ```console Resulting CLI options --check-filenames --check-hidden --skip ./.git --ignore-words codespell.txt Error: ./CHANGELOG.md:3178: Mange ==> Manage Error: ./CHANGELOG.md:7143: Mange ==> Manage Error: ./CHANGELOG.md:7143: Mange ==> Manage Error: ./relnotes/v0.68.0.md:7: Mange ==> Manage Error: ./relnotes/v0.68.0.md:49: Mange ==> Manage Error: ./relnotes/v0.68.0.md:49: Mange ==> Manage Codespell found one or more problems ``` https://github.com/rubocop/rubocop/actions/runs/6388440493/job/17338272269 `Mange` is a account name, not a typo. commit 56e2e4a0f33cf722fd13c5bdec2a4575e8d82ea0 Merge: 2ec14cabf 5344c784a Author: Koichi ITO Date: Tue Oct 3 02:12:02 2023 +0900 Merge pull request #12238 from koic/fix_an_error_for_style_nested_ternary_operator [Fix #12237] Fix an error for `Style/NestedTernaryOperator` commit 5344c784a9a89be116fb3f7c447baa1188d5a239 Author: Koichi ITO Date: Mon Oct 2 17:37:44 2023 +0900 [Fix #12237] Fix an error for `Style/NestedTernaryOperator` Fixes #12237. This PR fixes an error for `Style/NestedTernaryOperator` when a ternary operator has a nested ternary operator within an `if`. commit 2ec14cabfa4a9aa07f3b82b2c86ae80c52cbd674 Merge: 80de379af 948d64106 Author: Koichi ITO Date: Mon Oct 2 01:10:11 2023 +0900 Merge pull request #12235 from aboutsource/feature/auto_parallel_with_explicit_config Enable auto parallel inspection when config file is specified commit 948d64106d2eaa4058a3dde452c58b4728a24c3c Author: Moritz Nisblé Date: Sun Oct 1 13:29:29 2023 +0200 Enable auto parallel inspection when config file is specified commit 80de379af60a4df60a9e6707da1c3056e9d233ea Author: Koichi ITO Date: Sun Oct 1 18:41:32 2023 +0900 [Docs] Tweak docs for `Metrics/BlockLength` and `Metrics/ClassLength` Move `NOTE:` above `@example`. commit c9819f1ea4f4ec0361dcfc874844233253e56cb4 Author: Koichi ITO Date: Sat Sep 30 14:37:35 2023 +0900 Tweak autocorrection for `Style/RedundantBegin` This PR tweaks autocorrection for `Style/RedundantBegin` when using endless method definition with redundant `begin`. ```ruby def foo = begin bar end ``` ## Before ```console % bundle exec rubocop --only Style/RedundantBegin -a (snip) example.rb:1:11: C: [Corrected] Style/RedundantBegin: Redundant begin block detected. def foo = begin ^^^^^ 1 file inspected, 1 offense detected, 1 offense corrected ``` ```ruby def foo = bar ``` ## After ```ruby def foo = bar ``` This would be more closer to a one-liner endless idiom. commit 5f1774992f434654503c5e71a4b91725a5fa10c6 Author: Koichi ITO Date: Sat Sep 30 00:31:58 2023 +0900 [Fix #12226] Fix false positives for `Layout/MultilineMethodCallIndentation` Fixes #12226. This PR fixes false positives for `Layout/MultilineMethodCallIndentation` when aligning methods in multiline block chain. commit 08f475dc46585ee6d8f9afd609a9e36f7b9758e2 Author: Koichi ITO Date: Fri Sep 29 01:02:48 2023 +0900 Add new `Style/SingleLineDoEndBlock` cop This PR adds new `Style/SingleLineDoEndBlock` cop that checks for single-line `do`...`end` blocks. ```ruby # bad foo do |arg| bar(arg) end # good foo do |arg| bar(arg) end # bad ->(arg) do bar(arg) end # good ->(arg) { bar(arg) } ``` In practice a single line `do`...`end` is autocorrected when `EnforcedStyle: semantic` in `Style/BlockDelimiters`. It can also be detected by this cop if it is written by handcraft. So I decided to introduce this new cop instead of an autocorrect extension of `Style/BlockDelimiters`. commit 3bc4ebe50c666f8687d3a3ce6a37cbd398152cf4 Author: Koichi ITO Date: Fri Sep 29 15:55:52 2023 +0900 Fix false negatives for `Style/MultilineBlockChain` This PR fixes false negatives for `Style/MultilineBlockChain` when using multiline block chain with safe navigation operator. commit 91d3a8138fb27e285c6a08c9e10f3128aa5af4ef Author: Koichi ITO Date: Fri Aug 11 01:53:52 2023 +0900 [Fix #12097] Mark unsafe autocorrect for `Style/ClassEqualityComparison` Fixes #12097. This PR marks unsafe autocorrect for `Style/ClassEqualityComparison` because there is no guarantee that the constant `Foo` exists when autocorrecting `var.class.name == 'Foo'` to `var.instance_of?(Foo)`. commit 4bec69e32bad3068fca1abe8f5f8d9a02547ae57 Author: Koichi ITO Date: Thu Aug 17 01:18:04 2023 +0900 Make `Style/RedundantFilterChain` aware of `select.present?` Resolves: rubocop/rubocop-rails#1048. This PR makes `Style/RedundantFilterChain` aware of `select.present?` when `AllCops/ActiveSupportExtensionsEnabled: true`. commit 5537b0c1eb7613e38cbb35a59259596efbfc8a2c Author: Koichi ITO Date: Fri Aug 18 01:22:32 2023 +0900 [Fix #12128] Make `Style/GuardClause` aware of `define_method` Fixes #12128. This PR makes `Style/GuardClause` aware of `define_method`. commit 32968e195ad0d9d171e4f6d4528dbf784b8e75f2 Author: Koichi ITO Date: Wed Sep 20 19:17:41 2023 +0900 [Fix #12210] Mark `Style/RedundantFilterChain` as unsafe autocorrect Fixes #12210. This PR marks `Style/RedundantFilterChain` as unsafe autocorrect. commit e0c22a3a1714556fd505897435acf31f81185663 Author: Bozhidar Batsov Date: Thu Sep 28 15:07:04 2023 +0300 Switch back the docs version commit fc57892974c3bd597d9faa7abd5e02679ddea9d4 Author: Bozhidar Batsov Date: Thu Sep 28 15:04:23 2023 +0300 Cut 1.56.4 commit b7d99b8e857e60d8fc436cf8d61652196cd8a85d Author: Bozhidar Batsov Date: Thu Sep 28 15:03:51 2023 +0300 Update Changelog commit 0f550020b042fd7f50c340383bee431e3a6db727 Merge: 59fb188bb 9b04830b2 Author: Koichi ITO Date: Thu Sep 28 01:25:52 2023 +0900 Merge pull request #12222 from koic/fix_a_false_positive_for_layout_empty_line_after_guard_clause [Fix #12221] Fix a false positive for `Layout/EmptyLineAfterGuardClause` commit 59fb188bb349736edd1803bb82228b385ca86dfc Merge: c62622980 d0d612e81 Author: Koichi ITO Date: Wed Sep 27 00:14:42 2023 +0900 Merge pull request #12220 from koic/fix_an_incorrect_autocorrect_for_disable_uncorrectable_option [Fix #12208] Fix an incorrect autocorrect for the `--disable-uncorrectable` option commit 9b04830b2200ede77426984c848b0bcad2315328 Author: Koichi ITO Date: Tue Sep 26 19:04:03 2023 +0900 [Fix #12221] Fix a false positive for `Layout/EmptyLineAfterGuardClause` Fixes #12221. This PR fixes a false positive for `Layout/EmptyLineAfterGuardClause` when using `return` before guard condition with heredoc. commit d0d612e812def28bb13bf4d7dcb465009785fe3b Author: Koichi ITO Date: Tue Sep 26 01:40:25 2023 +0900 [Fix #12208] Fix an incorrect autocorrect for the `--disable-uncorrectable` option Fixes #12208. This PR fixes an incorrect autocorrect for the `--disable-uncorrectable` command line option when registering an offense is outside a percent array. commit c626229801455c05ef645834d1b335775d4a4f70 Merge: 3e921603d a2c1100aa Author: Koichi ITO Date: Mon Sep 25 10:31:37 2023 +0900 Merge pull request #12218 from koic/fix_a_false_positive_for_lint_ordered_magic_comments [Fix #12213] Fix a false positive for `Lint/OrderedMagicComments` commit a2c1100aaf9f735fc0f79c61a33c711ad57334d4 Author: Koichi ITO Date: Fri Sep 22 20:18:41 2023 +0900 [Fix #12213] Fix a false positive for `Lint/OrderedMagicComments` Fixes #12213. This PR fixes a false positive for `Lint/OrderedMagicComments` when comment text `# encoding: ISO-8859-1` is embedded within example code as source code comment. commit 3e921603d854885a985406dd6c342f86b95a4e41 Author: Koichi ITO Date: Sun Sep 24 22:40:31 2023 +0900 Disable `RSpec/FilePath` to resolve build error This PR commits `RSpec/FilePath` to suppress the following offenses: ```console $ bundle exec rake internal_investigation (snip) Offenses: spec/rubocop/cop/internal_affairs/redundant_let_rubocop_config_new_spec.rb:3:1: C: RSpec/FilePath: Spec path should end with rubocop/cop/internal_affairs/redundant_let_rubo_cop_config_new*_spec.rb. RSpec.describe RuboCop::Cop::InternalAffairs::RedundantLetRuboCopConfigNew, :config do ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ spec/rubocop/cop/mixin/enforce_superclass_spec.rb:3:1: C: RSpec/FilePath: Spec path should end with rubocop/cop/enforce_superclass*_spec.rb. RSpec.describe RuboCop::Cop::EnforceSuperclass, :restore_registry do ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ spec/rubocop/formatter/junit_formatter_spec.rb:3:1: C: RSpec/FilePath: Spec path should end with rubocop/formatter/j_unit_formatter*_spec.rb. RSpec.describe RuboCop::Formatter::JUnitFormatter, :config do ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` https://app.circleci.com/pipelines/github/rubocop/rubocop/9942/workflows/0c732f10-f59d-45a9-be69-5af5ceb0c5d8/jobs/289057 The offenses are due to a change in RuboCop RSpec 2.24.1, and it will ignore the deprecated `RSpec/FilePath`. https://github.com/rubocop/rubocop-rspec/pull/1718 commit 1e438220122afa680a8fc0eaf536c5b8647b6cb4 Merge: b242173c0 eac9f3e35 Author: Koichi ITO Date: Sun Sep 24 00:08:09 2023 +0900 Merge pull request #12215 from koic/update_the_doc_of_style_return_nil [Docs] Update the doc for `Style/ReturnNil` commit eac9f3e3500eeddc70524ac2105a06d9c18f6f2b Author: Koichi ITO Date: Sat Sep 23 09:40:46 2023 +0900 [Docs] Update the doc for `Style/ReturnNil` This PR updates the doc for `Style/ReturnNil` based on the following comments about why `Style/ReturnNil` cop is disabled by default. https://github.com/rubocop/rubocop/pull/4638#issuecomment-325219286 commit b242173c05f8de02796e60544a2c3af14410e0bd Author: Koichi ITO Date: Fri Sep 22 00:35:20 2023 +0900 Use `safe_navigation?` instead of custom method commit 2d4b944593d4ad5179a104a32fca3894cd3c2b52 Author: Koichi ITO Date: Thu Sep 21 01:12:21 2023 +0900 Fix duplicate contributor names when generating changelog Follow up https://github.com/rubocop/rubocop/commit/08dbb42. This commit fixes duplicate contributor names when generating changelog. commit 9fdc532bc8c448c43dab537cbf7949370bb58f68 Merge: d6b5ecf6e 1483f3107 Author: Koichi ITO Date: Wed Sep 20 01:15:18 2023 +0900 Merge pull request #12206 from koic/fix_an_incorrect_autocorrect_for_style_operator_method_call Fix an incorrect autocorrect for `Style/OperatorMethodCall` commit 1483f310708e2f4cbb944e4e2d5e885a1c5ca138 Author: Koichi ITO Date: Mon Sep 18 16:00:03 2023 +0900 Fix an incorrect autocorrect for `Style/OperatorMethodCall` This PR fixes an incorrect autocorrect for `Style/OperatorMethodCall` when using `foo./bar`: ```console % echo 'arg./100.0' | bundle exec rubocop --stdin example.rb -a -d (snip) F Offenses: example.rb:1:4: C: [Corrected] Style/OperatorMethodCall: Redundant dot detected. arg./100.0 ^ example.rb:1:5: F: Lint/Syntax: ambiguous first argument; put parentheses or a space even after the operator (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) arg /100.0 ^ 1 file inspected, 2 offenses detected, 1 offense corrected ==================== arg /100.0 ``` It solves the above `Lint/Syntax`. commit d6b5ecf6e30f5b9a1657d93423566939708404d8 Merge: 1af7e1137 ed9a4bd73 Author: Koichi ITO Date: Tue Sep 19 11:14:27 2023 +0900 Merge pull request #12207 from koic/fix_an_error_for_style_operator_method_call [Fix #12205] Fix an error for `Style/OperatorMethodCall` commit ed9a4bd7340156955ca6f344a0c2961f522e9c2a Author: Koichi ITO Date: Mon Sep 18 16:28:47 2023 +0900 [Fix #12205] Fix an error for `Style/OperatorMethodCall` Fixes #12205. This PR fixes an error for `Style/OperatorMethodCall` when using `foo bar./ baz`. commit 1af7e11373727ca7c9bd55044ca9649db40f3373 Merge: 9ddcca40c afe15a899 Author: Koichi ITO Date: Mon Sep 18 00:04:43 2023 +0900 Merge pull request #12204 from koic/support_autocorrect_for_internal_affairs_example_description Support autocorrect for `InternalAffairs/ExampleDescription` commit afe15a899937a72f674e71a28fa749aad3c6f687 Author: Koichi ITO Date: Sun Sep 17 03:13:39 2023 +0900 Support autocorrect for `InternalAffairs/ExampleDescription` This PR supports autocorrect for `InternalAffairs/ExampleDescription`. commit 9ddcca40c3e36be6db79713c303f1f8fab374aaa Author: Koichi ITO Date: Sat Sep 16 01:15:56 2023 +0900 Add a project spec to prevent error when running `rake changelog:merge` This PR resolves the following error when running `rake changelog:merge` in RuboCop Rails. So it will prevent the same error from occurring in this repository. ```conosle $ bundle exec rake changelog:merge rake aborted! NoMethodError: undefined method `[]' for nil /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:139:in `block in contributors' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:138:in `each' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:138:in `flat_map' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:138:in `contributors' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:132:in `new_contributor_lines' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:126:in `merge_content' /Users/koic/src/github.com/rubocop/rubocop-rails/tasks/changelog.rb:115:in `merge!' tasks/changelog.rake:21:in `block (2 levels) in ' /Users/koic/.rbenv/versions/3.3.0-dev/bin/bundle:25:in `load' /Users/koic/.rbenv/versions/3.3.0-dev/bin/bundle:25:in `
' Tasks: TOP => changelog:merge (See full trace by running task with --trace) ``` This error was caused by the absence of a space after the period: ```diff -* [#42](https://github.com/rubocop/rubocop-rails/issues/42): Fix an error for `Rails/RedundantActiveRecordAllMethod`.([contributor_name]) +* [#42](https://github.com/rubocop/rubocop-rails/issues/42): Fix an error for `Rails/RedundantActiveRecordAllMethod`. ([contributor_name]) ``` The added test verifies that there is a single space between the period and the parentheses. And tweaks changelog entries NOTE: For compatibility with outdated formats, if there's no contributor name, it checks that the line ends with a period. commit c1994c71a843eaf64e8d43d39ed03445764bd31b Merge: 7ad9d85ae 65f28e8ba Author: Koichi ITO Date: Fri Sep 15 00:08:14 2023 +0900 Merge pull request #12203 from koic/fix_an_incorrect_autocorrect_for_lint_safe_navigation_chain Fix an incorrect autocorrect for `Lint/SafeNavigationChain` commit 65f28e8baea40a47a9a6bb17b53cb5c32fba6fd6 Author: Koichi ITO Date: Thu Sep 14 01:17:19 2023 +0900 Fix an incorrect autocorrect for `Lint/SafeNavigationChain` This PR fixes an incorrect autocorrect for `Lint/SafeNavigationChain` when using safe navigation with comparison operator as an expression of logical operator or comparison operator's operand: ## Before The autocorrected code is a syntax error: ```console $ echo 'do_something && x&.foo >= bar' | be rubocop --stdin example.rb -a Inspecting 1 file F Offenses: example.rb:1:2: C: [Corrected] Layout/InitialIndentation: Indentation of first line in file detected. do_something && x&.foo >= bar ^^^^^^^^^^^^ example.rb:1:24: W: [Corrected] Lint/SafeNavigationChain: Do not chain ordinary method call after safe navigation operator. do_something && x&.foo >= bar ^^^^^^^ example.rb:1:29: F: Lint/Syntax: unexpected token tIDENTIFIER (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) do_something && x&.foo&. >= bar ^^^ 1 file inspected, 3 offenses detected, 2 offenses corrected ==================== do_something && x&.foo&. >= bar ``` ```console $ ruby -ce 'do_something && x&.foo&. >= bar' -e:1: syntax error, unexpected local variable or method, expecting end-of-input do_something && x&.foo&. >= bar -e: compile error (SyntaxError) ``` ## After Adding the necessary parentheses will autocorrect the syntax to make it valid: ```console $ echo 'do_something && x&.foo >= bar' | be rubocop --stdin example.rb -a Inspecting 1 file W Offenses: example.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment. do_something && (x&.foo&.>= bar) ^ example.rb:1:2: C: [Corrected] Layout/InitialIndentation: Indentation of first line in file detected. do_something && x&.foo >= bar ^^^^^^^^^^^^ example.rb:1:24: W: [Corrected] Lint/SafeNavigationChain: Do not chain ordinary method call after safe navigation operator. do_something && x&.foo >= bar ^^^^^^^ example.rb:1:26: C: [Corrected] Layout/SpaceAroundMethodCallOperator: Avoid using spaces around a method call operator. do_something && (x&.foo&. >= bar) ^ 1 file inspected, 4 offenses detected, 3 offenses corrected, 1 more offense can be corrected with `rubocop -A` ==================== do_something && (x&.foo&.>= bar) ``` commit 7ad9d85ae6b9b768c1155faf9eecd37bc46116cf Merge: 1b7da8189 cd5d1f5dc Author: Koichi ITO Date: Wed Sep 13 02:21:01 2023 +0900 Merge pull request #12202 from ydah/fix-incorrect-autocorrect-redundant-conditional Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results commit cd5d1f5dc1d28110d79d05a97c1600ea016c7898 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Wed Sep 13 02:05:27 2023 +0900 Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results commit 1b7da8189e0aaebc15b906a41c46ed9f46aa15f4 Author: Koichi ITO Date: Tue Sep 12 00:45:35 2023 +0900 [Fix #12199] Fix false negatives for `Layout/MultilineMethodCallIndentation` Fixes #12199. This PR fixes false negatives for `Layout/MultilineMethodCallIndentation` when using safe navigation operator. commit aaf4f5698384c84dbe46d56893bf1f3583bce2a6 Merge: 70fd31938 e59f119fa Author: Koichi ITO Date: Tue Sep 12 00:04:16 2023 +0900 Merge pull request #12200 from ydah/fixUselessMessageAssertion Fix an error for `InternalAffairs/UselessMessageAssertion` when empty file commit e59f119fa670654d4c892a1de8e09a555cac0bb7 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Mon Sep 11 23:37:54 2023 +0900 Fix an error for `InternalAffairs/UselessMessageAssertion` when empty file This PR fix an error for `InternalAffairs/UselessMessageAssertion` when empty file. ``` ❯ bundle exec rubocop foo_spec.rb -d For /ydah/rubocop-rspec: configuration from /ydah/rubocop-rspec/.rubocop.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-performance-1.19.0/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-performance-1.19.0/config/default.yml Default configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rake-0.6.0/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-rake-0.6.0/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-capybara-2.18.0/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-capybara-2.18.0/lib/../config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-factory_bot-2.23.1/config/default.yml configuration from /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-factory_bot-2.23.1/lib/../config/default.yml configuration from /ydah/rubocop-rspec/config/default.yml configuration from /ydah/rubocop-rspec/config/default.yml Inheriting configuration from /ydah/rubocop-rspec/.rubocop_todo.yml Use parallel by default. Skipping parallel inspection: only a single file needs inspection Inspecting 1 file Scanning /ydah/rubocop-rspec/foo_spec.rb An error occurred while InternalAffairs/UselessMessageAssertion cop was inspecting /ydah/rubocop-rspec/foo_spec.rb. undefined method `each_node' for nil:NilClass /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb:24:in `described_class_msg' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb:40:in `each' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb:40:in `reject' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb:40:in `assertions_using_described_class_msg' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb:30:in `on_new_investigation' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:160:in `block (2 levels) in invoke' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:171:in `with_cop_error_handling' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:160:in `block in invoke' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:160:in `each' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:160:in `invoke' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/commissioner.rb:84:in `investigate' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/team.rb:156:in `investigate_partial' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cop/team.rb:98:in `investigate' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:345:in `block in inspect_file' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:344:in `each' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:344:in `flat_map' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:344:in `inspect_file' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:287:in `block in do_inspection_loop' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:321:in `block in iterate_until_no_changes' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:314:in `loop' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:314:in `iterate_until_no_changes' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:283:in `do_inspection_loop' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:164:in `block in file_offenses' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:189:in `file_offense_cache' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:163:in `file_offenses' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:154:in `process_file' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:135:in `block in each_inspected_file' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:134:in `each' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:134:in `reduce' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:134:in `each_inspected_file' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:120:in `inspect_files' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/runner.rb:73:in `run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/command/execute_runner.rb:26:in `block in execute_runner' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/command/execute_runner.rb:52:in `with_redirect' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/command/execute_runner.rb:25:in `execute_runner' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/command/execute_runner.rb:17:in `run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/command.rb:11:in `run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli/environment.rb:18:in `run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli.rb:118:in `run_command' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli.rb:125:in `execute_runners' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli.rb:51:in `block in run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli.rb:77:in `profile_if_needed' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/lib/rubocop/cli.rb:43:in `run' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/exe/rubocop:19:in `block in ' /.rbenv/versions/3.2.2/lib/ruby/3.2.0/benchmark.rb:311:in `realtime' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.56.3/exe/rubocop:19:in `' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/bin/rubocop:25:in `load' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/bin/rubocop:25:in `' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli/exec.rb:58:in `load' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli/exec.rb:58:in `kernel_load' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli/exec.rb:23:in `run' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli.rb:492:in `exec' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/vendor/thor/lib/thor.rb:392:in `dispatch' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli.rb:34:in `dispatch' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/vendor/thor/lib/thor/base.rb:485:in `start' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/cli.rb:28:in `start' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bundler-2.4.18/exe/bundle:37:in `block in ' /.rbenv/versions/3.2.2/lib/ruby/site_ruby/3.2.0/bundler/friendly_errors.rb:117:in `with_friendly_errors' /.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bundler-2.4.18/exe/bundle:29:in `' /.rbenv/versions/3.2.2/bin/bundle:25:in `load' /.rbenv/versions/3.2.2/bin/bundle:25:in `
' W Offenses: foo_spec.rb:1:1: W: Lint/EmptyFile: Empty file detected. 1 file inspected, 1 offense detected 1 error occurred: An error occurred while InternalAffairs/UselessMessageAssertion cop was inspecting /ydah/rubocop-rspec/foo_spec.rb. Errors are usually caused by RuboCop bugs. Please, report your problems to RuboCop's issue tracker. https://github.com/rubocop/rubocop/issues Mention the following information in the issue report: 1.56.3 (using Parser 3.2.2.3, rubocop-ast 1.29.0, running on ruby 3.2.2) [x86_64-darwin21] ``` commit 70fd3193878252680c10360d1ec84585e15cd954 Author: Koichi ITO Date: Mon Sep 11 01:24:00 2023 +0900 Make `Style/CollectionMethods` aware of `collect_concat` This PR makes `Style/CollectionMethods` aware of `collect_concat` because matches the existing `map` and `collect` terminology selection. commit 3dda01cbdc607060b76928962cdcff36dd22eb0b Author: Bozhidar Batsov Date: Mon Sep 11 09:27:52 2023 +0300 Cut 1.56.3 commit 796fcb34b9b11f632ae7d3bffc6da36e9bd0b781 Author: Bozhidar Batsov Date: Mon Sep 11 09:27:07 2023 +0300 Cut 1.56.3 commit 2c10ba8ee3ba2a946e059dafcdfca9dd665f22a9 Author: Bozhidar Batsov Date: Mon Sep 11 09:26:10 2023 +0300 Move a changelog entry commit fa8bc616c3b086fe68e6dd651f59b5541ac01158 Author: Bozhidar Batsov Date: Mon Sep 11 09:25:43 2023 +0300 Update Changelog commit 52d0b72e04bbce9e206b5583009334c0c6e7db43 Author: Martin Emde Date: Thu Aug 24 15:04:45 2023 -0700 Try avoiding project_root leak to fix flaky error commit 3d427bb323b54d15d9e380e6762ac924f0695d3b Author: Martin Emde Date: Thu Aug 24 14:25:07 2023 -0700 Fix isolated test files should not break isolation. Ensures that files created during isolated tests do not get added outside of the isolated directory tree. This prevents tests from being created in a way that relies on the test infrastructure to pass that would not pass in a real world scenario. commit 8abcf7ea8a919e213fae44129b75326c61f40617 Author: Martin Emde Date: Thu Aug 24 13:21:58 2023 -0700 Fix shadowing of FileFinder stop_dir in isolated tests. Previously, stop_dir was ignored when root_level was present. Tests relied on the root_level matching the stop_dir which allowed some tests to pass even when stop_dir was being ignored. Use FileFinder.root_level only for protecting test env by setting it at the actual root of the tmpdir in isolated environment tests. commit 77a6b227096e88a639e518cf3e11e3d603d6accc Author: Koichi ITO Date: Fri Aug 25 16:38:46 2023 +0900 [Fix #12151] Make `Layout/EmptyLineAfterGuardClause` allow `:nocov:` directive Resolves #12151. This PR makes `Layout/EmptyLineAfterGuardClause` allow `:nocov:` directive after guard clause. SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`: https://github.com/simplecov-ruby/simplecov#ignoringskipping-code commit b1c67e9dbdc2984bd5087b76c0b4467b718e5af9 Author: Koichi ITO Date: Sun Sep 10 03:21:02 2023 +0900 Constantize fixed arrays of `Style/SymbolArray` commit aab9391e5a037e41e2223e18e709588cc272aab1 Author: Koichi ITO Date: Sat Sep 9 00:50:52 2023 +0900 Use RuboCop RSpec 2.24 This commit uses RuboCop RSpec 2.24 and suppresses the following `RSpec/FilePath` error: ```console $ bundle exec rubocop Error: The `RSpec/FilePath` cop has been split into `RSpec/SpecFilePathFormat` and `RSpec/SpecFilePathSuffix`. (obsolete configuration found in .rubocop.yml, please update it) ``` https://github.com/rubocop/rubocop-rspec/releases/tag/v2.24.0 commit 4ba4104507d3f765d2c9ad1d52abee397ba226c0 Author: ymap Date: Fri Sep 8 13:49:32 2023 +0000 [Fix #12195] Fix a false negative for `Layout/SpaceAfterNot` Fixes #12195. This PR fixes a false negative for `Layout/SpaceAfterNot` when a newline is present after `!`. commit 9c0b891207e25dbfabe833fdbbd60c364add9961 Author: Koichi ITO Date: Thu Sep 7 13:14:28 2023 +0900 [Fix #12181] Fix an incorrect autocorrect for `Lint/UselessAssignment` Fixes #12181. This PR fixes an incorrect autocorrect for `Lint/UselessAssignment` when variables are assigned with sequential assignment using the comma operator and unreferenced. commit d740953654b854d8db0fea9b5fe96843bdc024f7 Author: Koichi ITO Date: Fri Sep 1 03:00:50 2023 +0900 [Fix #12171] Fix a false positive for `Style/ArrayIntersect` Fixes #12171. This PR fixes a false positive for `Style/ArrayIntersect` when using block argument for `Enumerable#any?`. Note: This cop is already marked as unsafe. commit 1042911d9d20e4b9b9c9bed96f65eb9f25c93882 Author: Koichi ITO Date: Fri Sep 8 17:10:06 2023 +0900 [Docs] Tweak the doc for `Style/YodaExpression` commit a2eb409186b19e0e2489d17f10d250f1d0bbb99a Author: Koichi ITO Date: Mon Sep 4 00:03:24 2023 +0900 [Fix #12182] Fix an error for `Lint/UselessAssignment` Fixes #12182. This PR fixes an error for `Lint/UselessAssignment` when variables are assigned with chained assignment and unreferenced. As we added to spec/rubocop/cli/autocorrect_spec.rb, detection and autocorrection will eventually be possible as before. commit bc2ec8385bf23921eec1605c7fd38e96d85ecf1d Merge: d06288ae9 cd1bdeb71 Author: Koichi ITO Date: Thu Sep 7 01:23:23 2023 +0900 Merge pull request #12193 from ymap/fix_a_false_positive_for_layout_redundant_line_break [Fix #12192] Fix a false positive for `Layout/RedundantLineBreak` commit cd1bdeb71bef217031d872d1fb766e16a56a9e3c Author: ymap Date: Wed Sep 6 15:25:28 2023 +0000 [Fix #12192] Fix a false positive for `Layout/RedundantLineBreak` Fixes #12192. This PR fixes a false positive for `Layout/RedundantLineBreak` when using quoted symbols with a single newline. commit d06288ae9233e557a58379f28057269f58f4362e Merge: 4b0905776 3efcef1de Author: Koichi ITO Date: Wed Sep 6 11:19:02 2023 +0900 Merge pull request #12191 from koic/fix_a_false_positive_for_layout_space_around_operators [Fix #12190] Fix a false positive for `Layout/SpaceAroundOperators` commit 4b0905776f893b670c19d4f2e038d94fb3dcc5d4 Merge: e3b72ee3f 61cc07abc Author: Koichi ITO Date: Tue Sep 5 16:42:34 2023 +0900 Merge pull request #12185 from tagliala/bugfix/add-minimum-required-ruby-version-to-layout-heredoc-indentation Set target version for Layout/HeredocIndentation commit 3efcef1de8b2be0a24a5bfad47dfd597687201a0 Author: Koichi ITO Date: Tue Sep 5 12:45:42 2023 +0900 [Fix #12190] Fix a false positive for `Layout/SpaceAroundOperators` Fixes #12190. This PR fixes a false positive for `Layout/SpaceAroundOperators` when aligning operators vertically. commit 61cc07abc199562812a17527bd93b914eac78d22 Author: Geremia Taglialatela Date: Mon Sep 4 20:19:37 2023 +0200 Set target version for `Layout/HeredocIndentation` The squiggly heredoc syntax was introduced in Ruby 2.3. Therefore, this linter should not flag any offenses for Ruby < 2.3 code. Additionally, this linter is considered to be safe for autocorrection, meaning that it is likely to break compatibility with older Ruby versions. commit e3b72ee3f1a558782435a2bab108ae10d01da886 Merge: b20b3089e aaec1a21a Author: Koichi ITO Date: Tue Sep 5 00:34:41 2023 +0900 Merge pull request #12188 from ymap/fix_an_incorrect_autocorrect_for_style_sole_nested_conditional [Fix #12187] Fix an incorrect autocorrect for `Style/SoleNestedConditional` commit b20b3089e949bd2b5cbfaf9d7631deeeab572436 Merge: 9f20aa390 a6d12356f Author: Koichi ITO Date: Tue Sep 5 00:03:01 2023 +0900 Merge pull request #12189 from rubocop/dependabot/github_actions/actions/checkout-4 Bump actions/checkout from 3 to 4 commit a6d12356f5bb44d82b55e0e5934dab12fa0f36a8 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon Sep 4 14:25:56 2023 +0000 Bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] commit aaec1a21a7144106db1e49a7ffd30b6d24ff188a Author: ymap Date: Mon Sep 4 08:36:03 2023 +0000 [Fix rubocop#12187] Fix an incorrect autocorrect for `Style/SoleNestedConditional` Fixes rubocop#12187. This PR fixes an incorrect autocorrect for `Style/SoleNestedConditional` when comment is in an empty nested `if` body. commit 9f20aa39003fae55366d6d2f9264506833ece0ea Author: Koichi ITO Date: Mon Sep 4 12:43:51 2023 +0900 Remove comments in `Style/InvertibleUnlessCondition` for Rails This is a change similar to https://github.com/rubocop/rubocop/commit/ffa0c10. It will be implemented in RuboCop Rails instead of commented out: https://github.com/rubocop/rubocop-rails/pull/1097 commit 9e6d3b5824074be3f0e8a123cee86fc44b8b7b47 Merge: dad9147ed e939335cd Author: Koichi ITO Date: Sun Sep 3 22:06:31 2023 +0900 Merge pull request #12183 from koic/fix_an_incorrrect_autocorrect_for_style_multiline_ternary_operator Fix an incorrect autocorrect for `Style/MultilineTernaryOperator` commit e939335cdf85b0befc4bd46d2d0e2c64571b51cc Author: Koichi ITO Date: Sun Sep 3 00:26:21 2023 +0900 Fix an incorrect autocorrect for `Style/MultilineTernaryOperator` This PR fixes an incorrect autocorrect for `Style/MultilineTernaryOperator` when returning a multiline ternary operator expression with safe navigation method call: ```ruby $ cat example.rb obj&.x foo ? bar : baz ``` ## Before It is autocorrected to invalid syntax as follows: ```console $ bundle exec rubocop --only Style/MultilineTernaryOperator -a Inspecting 1 file F Offenses: example.rb:1:8: C: [Corrected] Style/MultilineTernaryOperator: Avoid multi-line ternary operators, use if or unless instead. obj&.x foo ? ... ^^^^^ example.rb:3:1: F: Lint/Syntax: unexpected token kELSE (Using Ruby 3.3 parser; configure using TargetRubyVersion parameter, under AllCops) else ^^^^ 1 file inspected, 2 offenses detected, 1 offense corrected $ cat example.rb obj&.x if foo bar else baz end $ ruby -c example.rb example.rb: example.rb:3: syntax error, unexpected `else' (SyntaxError) ``` ## After It will be autocorrected to a valid syntax as shown below: ```console $ bundle exec rubocop --only Style/MultilineTernaryOperator -a Inspecting 1 file C Offenses: example.rb:1:8: C: [Corrected] Style/MultilineTernaryOperator: Avoid multi-line ternary operators, use single-line instead. obj&.x foo ? ... ^^^^^ 1 file inspected, 1 offense detected, 1 offense corrected $ cat example.rb obj&.x foo ? bar : baz ``` commit dad9147ed06bd89282fe8535be37400232ea8802 Author: Koichi ITO Date: Sat Sep 2 02:00:45 2023 +0900 [Docs] Add Helix to the LSP doc This PR adds [Helix](https://docs.helix-editor.com/languages.html) to the LSP doc. commit cb89f9745d27272885edf39de583d0b76939d7e2 Merge: ab65d1835 ed00680bd Author: Koichi ITO Date: Sat Sep 2 01:28:32 2023 +0900 Merge pull request #12174 from koic/fix_a_false_positive_for_style_empty_case_condition [Fix #12172] Fix a false positive for `Style/EmptyCaseCondition` commit ab65d1835122d949d044b2de0283329601451d88 Merge: 87587b897 69503006c Author: Koichi ITO Date: Fri Sep 1 08:16:18 2023 +0900 Merge pull request #12169 from owst/fix_bug_in_style_arguments_forwarding_with_duplicate_sends [Fix #12168]: Fix bug in `Style/ArgumentsForwarding` commit 69503006c5b29ab7c93b9f2626fcbb2f2f3aa9d1 Author: Owen Stephens Date: Tue Aug 29 23:07:24 2023 +0100 [Fix #12168]: Fix bug in `Style/ArgumentsForwarding` We were using nodes as Hash keys, which is not supported - the metadata (source location) is not used to distinguish nodes. Thus the two occurrences of the same send (method name and args) were collapsed into one, causing only one of two offense sites to be reported. commit ed00680bd7c333e4c5815600ab9ecabe4af0fbc8 Author: Koichi ITO Date: Fri Sep 1 03:26:58 2023 +0900 [Fix #12172] Fix a false positive for `Style/EmptyCaseCondition` Fixes #12172. This PR fixes a false positive for `Style/EmptyCaseCondition` when using `return`, `break`, `next` or method call before empty case condition. commit 87587b8979ce1d67d039f132271191f1730027d8 Merge: 1a8350960 63b7893d0 Author: Koichi ITO Date: Thu Aug 31 20:37:44 2023 +0900 Merge pull request #12170 from koic/make_internal_affairs_redundant_method_dispatch_node_aware_of_method_p Make `InternalAffairs/RedundantMethodDispatchNode` aware of `method?` commit 63b7893d0eba4f2c35d690088b88119f5d1c8d71 Author: Koichi ITO Date: Thu Aug 31 12:04:06 2023 +0900 Make `InternalAffairs/RedundantMethodDispatchNode` aware of `method?` This PR makes `InternalAffairs/RedundantMethodDispatchNode` aware of `method?`: ```ruby # bad node.send_node.method?(:method_name) # good node.method?(:method_name) ``` commit 1a83509606075a9944ca201f9ffe12ca9cde3007 Author: Koichi ITO Date: Tue Aug 29 14:33:25 2023 +0900 [Fix #12162] Fix an error for `Bundler/DuplicatedGroup` Fixes #12162. This PR fixes an error for `Bundler/DuplicatedGroup` when there's a duplicate set of groups and the `group` value contains a splat. commit 0b3fbae0b5715932235530b5b8525beba0667507 Author: Koichi ITO Date: Wed Aug 30 01:47:46 2023 +0900 Switch back the docs version commit b85e080c2528b298d9c8b96db7845537af10f3ff Author: Bozhidar Batsov Date: Tue Aug 29 10:13:47 2023 +0300 Cut 1.56.2 commit 7a35bde9d538bdc502312cad43d398cc5cf9f376 Author: Bozhidar Batsov Date: Tue Aug 29 10:13:22 2023 +0300 Update Changelog commit 27744269060da77d3a102def3b9b225a4974e575 Merge: c4cb471a5 2d741ee73 Author: Koichi ITO Date: Tue Aug 29 01:57:34 2023 +0900 Merge pull request #12161 from ymap/fix_duplicate_word_typos Fix duplicate word typos commit 2d741ee7331861daf93578d2d6a8b920e11c74ec Author: ymap Date: Mon Aug 28 15:27:15 2023 +0000 Fix duplicate word typos commit c4cb471a506a0c6b60aeb6b5c8a90e6378200bb2 Author: Koichi ITO Date: Sun Aug 27 16:41:27 2023 +0900 [Fix #12154] Fix incorrect `diagnosticProvider` value of LSP Fixes #12154. This PR fixes incorrect `diagnosticProvider` value of LSP. `diagnosticProvider` cannot accept true as below. This PR replaces the originally acceptable value. ```typescript /** * The server has support for pull model diagnostics. * * @since 3.17.0 */ diagnosticProvider?: DiagnosticOptions | DiagnosticRegistrationOptions; ``` https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize commit 6ac9eceacb0d8d1aee498722f538d7c7539c219e Author: Koichi ITO Date: Mon Aug 28 00:34:24 2023 +0900 [Docs] Add Emacs (LSP Mode) to the LSP doc Follow up https://github.com/emacs-lsp/lsp-mode/pull/4090. Emacs LSP Mode supports the built-in language server. So, This PR adds Emacs LSP Mode to the LSP doc. commit 0e1d4da22d4b7e8a8270d9d828638e4e41e13ea5 Merge: 4f46bc446 90cd056ce Author: Koichi ITO Date: Mon Aug 28 01:27:57 2023 +0900 Merge pull request #12155 from koic/fix_a_false_positive_for_layout_redundant_line_break Fix a false positive for `Layout/RedundantLineBreak` commit 4f46bc446785743db5df9d2950be8ca8b2afe6d7 Merge: bea319d6e 8829d3304 Author: Koichi ITO Date: Sun Aug 27 16:14:07 2023 +0900 Merge pull request #12157 from kyoshidajp/update_doc_create_a_new_cop Update document in create a new cop commit 8829d3304e00c1c96f56d90d77ea398b1b212306 Author: Katsuhiko YOSHIDA Date: Sun Aug 27 10:31:57 2023 +0900 Update document in create a new cop commit 90cd056ce085421fc3157832401fec68a4e11223 Author: Koichi ITO Date: Sun Aug 27 03:03:40 2023 +0900 Fix a false positive for `Layout/RedundantLineBreak` This PR fixes false positive for `Layout/RedundantLineBreak` to prevent the following infinite loop error: ```console $ echo 'x def self.y; z end' | be rubocop --stdin example.rb -a --only Layout/RedundantLineBreak,Style/SingleLineMethods Inspecting 1 file C Offenses: example.rb:1:1: C: [Corrected] Layout/RedundantLineBreak: Redundant line break detected. x def self.y; ... ^^^^^^^^^^^^^^ example.rb:1:3: C: [Corrected] Style/SingleLineMethods: Avoid single-line method definitions. x def self.y; z end ^^^^^^^^^^^^^^^^^ 0 files inspected, 2 offenses detected, 2 offenses corrected Infinite loop detected in /Users/koic/src/github.com/rubocop/rubocop/example.rb and caused by Style/SingleLineMethods -> Layout/RedundantLineBreak /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/runner.rb:332:in `check_for_infinite_loop' ``` commit bea319d6ec9a7c070c16bd5e8cd089b8ca93c152 Merge: 0ff3a62c1 b1b7742cb Author: Koichi ITO Date: Sat Aug 26 03:53:21 2023 +0900 Merge pull request #12153 from koic/suppress_warning_bigdecimal_will_be_bundled_gem Suppress a Ruby warning when using Ruby 3.3.0dev commit b1b7742cbbc870bff44d53e57efd9203c5066f41 Author: Koichi ITO Date: Sat Aug 26 01:19:43 2023 +0900 Suppress a Ruby warning when using Ruby 3.3.0dev Follow up https://github.com/ruby/ruby/commit/1c93288f8bbf667cb95eb7137b2fe64213894b77. This PR suppresses the following warning when using Ruby 3.3.0dev ```consle $ cd path/to/rubocop $ ruby -v ruby 3.3.0dev (2023-08-22T14:46:32Z master 7127f39bac) [x86_64-darwin22] $ bundle exec rake spec /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/crack-0.4.5/lib/crack/xml.rb:9: warning: bigdecimal will be not part of the default gems since Ruby 3.4.0. Add it to your Gemfile. ``` crack is a dependency for the testing tool WebMock, so it will be added to the Gemfile: ```console $ cat Gemfile.lock (snip) webmock (3.18.1) addressable (>= 2.8.0) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) ``` The `bigdecimal` dependency can be removed when https://github.com/jnunemaker/crack/pull/75 is merged and released. It's a workaround until then. commit 0ff3a62c1357acc25f1fe22ed364b272d21b9f40 Merge: 342bbbe82 7aaf70fda Author: Koichi ITO Date: Fri Aug 25 20:27:21 2023 +0900 Merge pull request #12148 from koic/fix_an_incorrect_autocorrect_for_lint_non_atomic_file_operation Fix an incorrect autocorrect for `Lint/NonAtomicFileOperation` commit 7aaf70fdad9e9ab2019f760bd957a6a440806607 Author: Koichi ITO Date: Fri Aug 25 01:26:18 2023 +0900 Fix an incorrect autocorrect for `Lint/NonAtomicFileOperation` This PR fixes an incorrect autocorrect for `Lint/NonAtomicFileOperation` when using `FileUtils.remove_dir`, `FileUtils.remove_entry`, or `FileUtils.remove_entry_secure`. The behavior of these methods is closer to `FileUtils.rm_rf` than `FileUtils.rm`, since it also deletes the directory specified as an argument. commit 342bbbe82043509e006741a88d3413d6a9574480 Merge: 4c83f86a5 5b47705ab Author: Koichi ITO Date: Thu Aug 24 10:15:28 2023 +0900 Merge pull request #12139 from ymap/fix_a_false_positive_for_layout_line_continuation_leading_space [Fix #12138] Fix a false positive for `Layout/LineContinuationLeadingSpace` commit 5b47705aba115afd7fdb9686b69cef6290a941ee Author: ymap Date: Wed Aug 23 12:54:02 2023 +0000 [Fix #12138] Fix a false positive for `Layout/LineContinuationLeadingSpace` Fixes rubocop#12138. This PR fixes a false positive for `Layout/LineContinuationLeadingSpace` when a backslash is part of a multiline string literal. commit 4c83f86a52509aca58323ada0c3c25eb9e51ca75 Merge: de6971bbd f1b2832c2 Author: Koichi ITO Date: Wed Aug 23 01:25:00 2023 +0900 Merge pull request #12145 from koic/fix_a_false_positive_for_lint_to_enum_arguments [Fix #12143] Fix a false positive for `Lint/ToEnumArguments` commit f1b2832c2ca20cde33181913907af2d6fc0ce1b1 Author: Koichi ITO Date: Tue Aug 22 21:28:35 2023 +0900 [Fix #12143] Fix a false positive for `Lint/ToEnumArguments` Fixes #12143. This PR fixes a false positive for `Lint/ToEnumArguments` when using anonymous keyword arguments forwarding. commit de6971bbdd425e76b284777dfd04a7f5a6417ae6 Merge: 51ed9ab68 81ce84fe6 Author: Koichi ITO Date: Tue Aug 22 10:24:45 2023 +0900 Merge pull request #12142 from owst/correct_style_arguments_forwarding_with_additional_kwarg [Fix #12141] Fix false positive for `Style/ArgumentsForwarding` commit 81ce84fe6e6e42e2d1def115b12c22e82682d831 Author: Owen Stephens Date: Tue Aug 22 00:24:44 2023 +0100 [Fix #12141] Fix false positive for `Style/ArgumentsForwarding` If additional kwargs are supplied then forward-all (`...`) cannot be used. commit 51ed9ab6812f03e2cd5ace714fdcf48f8970978a Author: Bozhidar Batsov Date: Mon Aug 21 11:03:05 2023 +0300 Switch back the docs version commit 24e7411d9606fd064e720ecb65a965646b6f8a06 Author: Bozhidar Batsov Date: Mon Aug 21 11:01:01 2023 +0300 Cut 1.56.1 commit a3c111b38a1ea88c1c2edc47ad54260f51ed8bb1 Author: Bozhidar Batsov Date: Mon Aug 21 11:00:34 2023 +0300 Update Changelog commit 53433c4100d1628eed8518e5e1e8dfc1cb52c043 Author: Koichi ITO Date: Mon Aug 21 01:02:46 2023 +0900 Fix a false negative for `Layout/LeadingCommentSpace` This PR fixes a false negative for `Layout/LeadingCommentSpace` when using `#+` or `#-` as they are not RDoc comments. They are followed by `+` or `-` twice, such as `#++` and `#--`. commit ce93abdb36b8d1ac6f5732567e1cea13376a62b8 Author: Koichi ITO Date: Sun Aug 20 15:39:10 2023 +0900 [Fix #12134] Fix a false positive for `Style/MethodCallWithArgsParentheses` Fixes #12134. This PR fixes a false positive for `Style/MethodCallWithArgsParentheses` when parentheses are used in one-line `in` pattern matching. commit 68152904be485342c3241f109f360efd25d7951a Merge: dd2999484 75580b36f Author: Koichi ITO Date: Sun Aug 20 01:00:43 2023 +0900 Merge pull request #12133 from r7kamura/style-redundant-self-assignment-branch-heredoc Fix `Style/RedundantSelfAssignmentBranch` to handle heredocs commit 75580b36f81ae08095b0d88eb854ab93f25141b2 Author: r7kamura Date: Sat Aug 19 20:23:03 2023 +0900 Fix `Style/RedundantSelfAssignmentBranch` to handle heredocs commit dd299948479c15cc7dd254a339631d241938b20b Author: Koichi ITO Date: Sat Aug 19 01:14:57 2023 +0900 Use squiggly heredoc commit 23dc4de9b202e291c9f3dc3e6d0e37e46ef6cdbf Merge: 2cb9dea50 252af0d4e Author: Koichi ITO Date: Fri Aug 18 00:24:27 2023 +0900 Merge pull request #12127 from ItsEcholot/bugfix/required_ruby_version_gem_requirement_matching [Fix #12105] Adjust target ruby gem requirement matcher and version parsing to support multiple version constraints commit 252af0d4e517b3fabdb926a4cc22f90ca9a479f2 Author: Marc Berchtold Date: Thu Aug 17 10:42:09 2023 +0200 [Fix #12105] Adjust target ruby gem requirement matcher and version parsing to support multiple version constraints [Fix #12105] Add changelog entry [Fix #12105] Fix changelog entry commit 2cb9dea506ac3c4fb033ac5d51584ec71a62db52 Merge: 909564c35 f8f5875b4 Author: Koichi ITO Date: Thu Aug 17 14:38:58 2023 +0900 Merge pull request #12121 from chulkilee/fix-warning Fix instance variable not initialized warning commit f8f5875b465e119e5cb556b47914aba09f606513 Author: Chulki Lee Date: Mon Aug 14 17:53:42 2023 -0700 fix instance variable not initialized warning / memoization commit 909564c356b44e9b4dc20537781bcc7cc033cf1c Author: Koichi ITO Date: Wed Aug 16 14:42:16 2023 +0900 [Fix #12124] Fix false positives for `Style/RedundantParentheses` Fixes #12124. This PR fixes false positives for `Style/RedundantParentheses` when parentheses in `super` or `yield` call with multiline style argument. commit dfddfa942e1f4bcea44452dc0e81737c2ce6932d Author: Koichi ITO Date: Sat Aug 12 00:04:05 2023 +0900 [Fix #12113] Fix a false positive for `Bundler/DuplicatedGroup` Fix #12113. This PR fixes a false positive for `Bundler/DuplicatedGroup` when groups are duplicated but `source`, `git`, `platforms`, or `path` values are different. commit aba88959eea0551cf4c47824fa5a45a7c92ca945 Author: Koichi ITO Date: Wed Aug 16 00:06:09 2023 +0900 Fix a PR number in a changelog entry commit 9a143e667793588893b8436ff849ebaf009d9891 Merge: 5ca04a234 89eb90533 Author: Koichi ITO Date: Wed Aug 16 00:05:06 2023 +0900 Merge pull request #12120 from koic/fix_a_false_positive_for_style_symbol_array Fix false positives for `Style/SymbolArray` commit 89eb905332f627ee56d64a865e5e372a71485575 Author: Koichi ITO Date: Tue Aug 15 01:21:57 2023 +0900 Fix false positives for `Style/SymbolArray` This PR fixes false positives for `Style/SymbolArray` when `%i` array containing unescaped `[`, `]`, `(`, or `)`. I noticed the following false positive in the RuboCop AST repository: ```console $ cd path/to/rubocop-ast $ bundle exec rubocop --only Style/SymbolArray (snip) spec/rubocop/ast/node_pattern/lexer_spec.rb:36:9: C: [Correctable] Style/SymbolArray: Use [:'(', :array, :sym, :'$', :int, :+, :x, :')'] for an array of symbols. %i[( array sym $ int + x )] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 163 files inspected, 1 offense detected, 1 offense autocorrectable ``` commit 5ca04a234a61c1a694bfd3bd66fd613a47807083 Merge: 5b9ca710f 62a7cb993 Author: Koichi ITO Date: Mon Aug 14 01:31:57 2023 +0900 Merge pull request #12118 from owst/fix_arguments_forwarding_splat_without_block [Fix #12117] Fix `Style/ArgumentsForwarding` when not always forwarding a block commit 62a7cb9932271b386cc4c790278c3442b3438af4 Author: Owen Stephens Date: Sat Aug 12 11:42:25 2023 +0100 [Fix #12117] Fix `Style/ArgumentsForwarding` when not always forwarding a block commit 5b9ca710fa172e0725d1c208f33f6d344f76deb6 Author: Koichi ITO Date: Sun Aug 13 17:36:08 2023 +0900 Use RuboCop Performance 1.19 This commit uses RuboCop Performance 1.19 and suppresses the following new offenses: ```console $ bundle exec rubocop (snip) lib/rubocop/cop/layout/line_continuation_spacing.rb:112:20: C: Performance/MapMethodChain: Use map { |x| x.loc.expression } instead of map method chain. comments.map(&:loc).map(&:expression) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/layout/redundant_line_break.rb:121:37: C: Performance/MapMethodChain: Use map { |x| x.loc.line } instead of map method chain. processed_source.comments.map(&:loc).map(&:line).any? do |comment_line_number| ^^^^^^^^^^^^^^^^^^^^^^ lib/rubocop/cop/style/concat_array_literals.rb:77:30: C: Performance/MapMethodChain: Use map { |x| x.value.inspect } instead of map method chain. arg.children.map(&:value).map(&:inspect) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1515 files inspected, 3 offenses detected ``` commit b6e294fc1ef40bd8a6eb5a0a941456d3d1be4fa3 Author: Koichi ITO Date: Sat Aug 12 19:35:13 2023 +0900 Use `delete_prefix` and `delete_suffix` commit d929f688c7d1e68caa1f806ee1b1ca4d55a89fdc Author: Koichi ITO Date: Fri Aug 11 17:22:24 2023 +0900 Fix an error for `Style/Lambda` This PR fixes the following error for `Style/Lambda` when using numbered parameter with a multiline `->` call: ```console $ cat example.rb -> { _1.do_something } $ bundle exec rubocop example.rb --only Style/Lambda -d (snip) An error occurred while Style/Lambda cop was inspecting /Users/koic/src/github.com/koic/rubocop-issues/lambda/example.rb:1:0. undefined method `loc' for []:Array /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb:96:in `arguments_end_pos' ``` commit d9219f104bd49a0ec7dcb8ecad815268c0dfe31d Author: Koichi ITO Date: Thu Aug 10 12:02:11 2023 +0900 [Fix #12111] Fix an error for `Bundler/DuplicatedGroup` Fixes #12111. This PR fixes an error for `Bundler/DuplicatedGroup` group declaration has keyword option. commit 7d192907a118cd93d69d364e100632500ca7d92e Author: Koichi ITO Date: Thu Aug 10 20:40:36 2023 +0900 [Docs] Update example of `rubocop -V` RuboCop still supports Ruby 2.7 as a runtime, but the Ruby version is EOL. commit ff8c5fff039a04cdfea1025ccec9a3b3bd5d0f5d Merge: 1e143c909 1fbfb83c5 Author: Koichi ITO Date: Wed Aug 9 22:23:59 2023 +0900 Merge pull request #12110 from ydah/fix/12109 [Fix: #12109] Fix an error for `Style/ArgumentsForwarding` cop when forwarding kwargs/block arg and an additional arg commit 1fbfb83c587d467eac30665a9ebadcd4694a0b40 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Wed Aug 9 20:18:48 2023 +0900 [Fix: #12109] Fix an error for `Style/ArgumentsForwarding` cop when forwarding kwargs/block arg and an additional arg Fix: https://github.com/rubocop/rubocop/issues/12109 commit 1e143c9093f68bb3443f55e5edae8f766fa68f41 Author: Bozhidar Batsov Date: Wed Aug 9 09:35:09 2023 +0300 Switch back the docs version commit e597ca1121705764b6d009ff85a0caf8cd98000c Author: Bozhidar Batsov Date: Wed Aug 9 09:33:53 2023 +0300 Cut 1.56 commit 3036b2c4eff493f1032964a988c739e3ad14d839 Author: Bozhidar Batsov Date: Wed Aug 9 09:33:11 2023 +0300 Tweak whitespace commit 74f00323ddc76a98797c099483ace3dfbbf58149 Author: Bozhidar Batsov Date: Wed Aug 9 09:29:46 2023 +0300 Update Changelog commit 964235ce6453f13851dc88118ed4d954d6aa788f Author: OwlKing Date: Wed Aug 9 07:28:47 2023 +0100 Add new `Bundler/DuplicatedGroup` cop (#12074) commit c078235581f0c361c441c35b78de1d3e94c15874 Author: Evan Goldenberg Date: Tue Aug 1 14:27:41 2023 -0700 With `--fail-level A` ignore non-correctable offenses at :info severity The current implementation of `--fail-level autocorrect` fails for all offenses, no matter what. Notably, this includes non-correctable offenses with the :info severity. Change the implementation to only fail: * Any _correctable_ offense, regardless of severity * Non-correctable offenses with severity :refactor (the default) or higher commit 320ac56ee32ba2014c04919ae723b7871abb43ea Merge: f871c38c5 08e614ff6 Author: Koichi ITO Date: Wed Aug 9 05:48:41 2023 +0900 Merge pull request #12103 from owst/fixup_additional_args_forwarding [Fix #12087] Fix false positives for Style/ArgumentsForwarding commit 08e614ff64f153fff8b746619f28701a5a79e732 Author: Owen Stephens Date: Tue Aug 8 09:20:37 2023 +0100 [Fix #12087] Fix false positives for Style/ArgumentsForwarding Additionally fixes: * #12089 * #12096 * #12100 In Ruby < 3.2 this cop was overzealous and not considering various additional args/kwargs and other reasons to not allow forward-all (`...`), and was additionally assuming that forward-all meant all arguments were replaced, which was not always the case. commit f871c38c5f40d0e5b4c110843b862b3aa424a2c2 Author: Koichi ITO Date: Wed Aug 9 00:14:27 2023 +0900 [Fix #12106] Fix a false negative for `Style/RedundantReturn` Fixes #12106. This PR fixes a false negative for `Style/RedundantReturn` when returning value with guard clause and `return` is used. commit 235f7491c0657d6e97b994d50f0f41fc8a5ed339 Merge: 56b4edf52 57dd39246 Author: Koichi ITO Date: Wed Aug 9 00:09:03 2023 +0900 Merge pull request #12102 from koic/fix_an_error_for_style_lambda_call Fix an error for `Style/LambdaCall` commit 57dd39246028b70ef493d8898675b92b19e01390 Author: Koichi ITO Date: Tue Aug 8 01:00:02 2023 +0900 Fix an error for `Style/LambdaCall` This PR fixes an error for `Style/LambdaCall` when using nested lambda call `x.().()`: ```console $ cat example.rb x.(a, b).(c) $ buncle exec rubocop example.rb --only Style/LambdaCall -a -d (snip) An error occurred while Style/LambdaCall cop was inspecting /Users/koic/src/github.com/koic/rubocop-issues/lambda_call/example.rb:1:0. Parser::Source::TreeRewriter detected clobbering /Users/koic/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/parser-3.2.2.3/lib/parser/source/tree_rewriter.rb:427:in `trigger_policy' ``` commit 56b4edf52c431d7e48b7ed097b1912310e10971d Merge: 55fd38019 e068bdd60 Author: Koichi ITO Date: Mon Aug 7 00:04:28 2023 +0900 Merge pull request #12099 from koic/fix_an_incorrect_autocorrect_for_style_alias Fix an incorrect autocorrect for `Style/Alias` commit e068bdd60bab1df9e544467ead23bd6f86d6bf64 Author: Koichi ITO Date: Sun Aug 6 01:16:19 2023 +0900 Fix an incorrect autocorrect for `Style/Alias` This PR fixes the following incorrect autocorrection for `Style/Alias` when `EncforcedStyle: prefer_alias_method` and using `alias` with interpolated symbol argument: ```console $ cat example.rb alias :"string#{interpolation}" :symbol $ cat .rubocop.yml Style/Alias: EnforcedStyle: prefer_alias_method ``` ```console $ bundle exec rubocop -a --only Style/Alias (snip) Offenses: example.rb:1:1: C: [Corrected] Style/Alias: Use alias_method instead of alias. alias :"string#{interpolation}" :symbol ^^^^^ example.rb:1:14: F: Lint/Syntax: unexpected token tCOLON (Using Ruby 3.2 parser; configure using TargetRubyVersion parameter, under AllCops) alias_method :, :symbol ^ 1 file inspected, 2 offenses detected, 1 offense corrected ``` ```console $ cat example.rb alias_method :, :symbol $ ruby -c example.rb example.rb: example.rb:1: syntax error, unexpected ',', expecting literal content or terminator or tSTRING_DBEG or tSTRING_DVAR (SyntaxError) alias_method :, :symbol ^ ``` commit 55fd38019e40330ea2b34d857ba47912dae96135 Author: Koichi ITO Date: Sat Aug 5 04:45:36 2023 +0900 Fix a false positive for `Style/ClassEqualityComparison` This PR fixes a false positive to prevent an incorrect autocorrect for `Style/ClassEqualityComparison` when comparing interpolated string class name for equality. For example, autocorrect the code below: ```console $ cat example.rb var.class.name == "String#{interpolation}" $ bundle exec rubocop --only Style/ClassEqualityComparison -a Inspecting 1 file C Offenses: example.rb:1:5: C: [Corrected] Style/ClassEqualityComparison: Use instance_of?("String#{interpolation}") instead of comparing classes. var.class.name == "String#{interpolation}" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1 file inspected, 1 offense detected, 1 offense corrected ``` The `instance_of?` argument is still a string. ```console $ cat example.rb var.instance_of?("String#{interpolation}") ``` But the `instance_of?` argument requires class or module. So the above case cannot be replaced by `instace_of?`. ```console $ ruby -e "''.instance_of?('String')" -e:1:in `instance_of?': class or module required (TypeError) ''.instance_of?('String') ^^^^^^^^ from -e:1:in `
' ``` commit 8b98c532492824b58278748f7e2c03fbe2b82131 Merge: f94f42657 d5e572061 Author: Koichi ITO Date: Sat Aug 5 00:28:03 2023 +0900 Merge pull request #12095 from koic/fix_a_false_positive_for_style_alias Fix a false positive for `Style/Alias` commit d5e572061991c83578dd2b64dae87ad458480a05 Author: Koichi ITO Date: Fri Aug 4 12:06:54 2023 +0900 Fix a false positive for `Style/Alias` This PR fixes the following false positive to prevent incorrect autocorrection for `Style/Alias` when `EncforcedStyle: prefer_alias` and using `alias` with interpolated symbol argument: ```console $ ruby -ce 'alias :"string#{interpolation}" :symbol' Syntax OK ``` ```console $ echo 'alias :"string#{interpolation}" :symbol' | bundle exec rubocop --stdin example.rb -a --only Style/Alias Inspecting 1 file F Offenses: example.rb:1:7: F: Lint/Syntax: unexpected token tSTRING_BEG (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) alias "string#{interpolation}" symbol ^ example.rb:1:7: C: [Corrected] Style/Alias: Use alias "string#{interpolation}" symbol instead of alias :"string#{interpolation}" :symbol. alias :"string#{interpolation}" :symbol ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ example.rb:1:32: F: Lint/Syntax: unexpected token tIDENTIFIER (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) alias "string#{interpolation}" symbol ^^^^^^ 1 file inspected, 3 offenses detected, 1 offense corrected ==================== alias "string#{interpolation}" symbol ``` commit f94f42657fac7e6ecb0ef8fc6c96cc62ee262536 Author: Koichi ITO Date: Sat Jul 29 01:03:27 2023 +0900 Make LSP server support `rubocop.formatAutocorrectsAll` execute command This PR makes LSP server support `rubocop.formatAutocorrectsAll` execute command. The user can run `rubocop -A` with the execute command in the editor. The existing `rubocop.formatAutocorrects` execute command equivalent to `rubocop -a` can be used as follows: https://github.com/rubocop/vscode-rubocop#manually-triggering-a-format-with-autocorrects The new `rubocop.formatAutocorrectsAll` execute command is the provide execute command for that `rubocop -A`. commit edde3ebc746f94ed7fa06feda5964190560b516f Author: Koichi ITO Date: Thu Aug 3 12:19:35 2023 +0900 Add `base64` to runtime dependency This PR add `base64` to runtime dependency to suppress the following Ruby 3.3's warning: ```console $ ruby -v ruby 3.3.0dev (2023-08-03T00:11:08Z master 4b6c584023) [x86_64-darwin22] $ bundle exec rubocop base64 is not part of the default gems since Ruby 3.4.0. Add it to your Gemfile. ``` commit 3eb5ddab52f9aeec71a4a01731d003b1185da4ea Merge: fe172e44b 8b4de3aa1 Author: Koichi ITO Date: Thu Aug 3 00:24:59 2023 +0900 Merge pull request #12092 from jonas054/12061_StringLiteralsInInterpolation_regex [Fix #12061] Support regex in StringLiteralsInInterpolation commit 8b4de3aa1e2715de1f2a0d4dcea8482a40b15061 Author: Jonas Arvidsson Date: Wed Aug 2 13:29:58 2023 +0200 [Fix #12061] Support regex in StringLiteralsInInterpolation Interpolation can occur in strings, symbols, and regular expressions, so update code to support regex and extend code examples in documentation comments. commit fe172e44b3397ef69f55757270e80471a22430a7 Merge: d8646b484 43879cecd Author: Koichi ITO Date: Wed Aug 2 01:25:35 2023 +0900 Merge pull request #12086 from koic/fix_error_for_lint_suppressed_exception [Fix #12085] Fix an error for `Lint/SuppressedException` commit d8646b4844830717deda5ff4e25b019053b11e2e Merge: 4a759953d c5cefaeb3 Author: Koichi ITO Date: Tue Aug 1 12:27:52 2023 +0900 Merge pull request #12088 from jasondoc3/jason/fix-false-positive-symbol-array [Fix #12071] Fix `Style/SymbolArray` false positives when using square brackets or interpolation in a symbol literal within a percent style array commit c5cefaeb3961bfdd2863fc598d7e374049cec030 Author: Jason Dougherty Date: Mon Jul 31 18:23:16 2023 -0700 [Fix #12071] Fix Style/SymbolArray false positives commit 43879cecd75ed06b75e70be5579ed6e693c5ff21 Author: Koichi ITO Date: Tue Aug 1 03:12:29 2023 +0900 [Fix #12085] Fix an error for `Lint/SuppressedException` Fixes #12085. This PR fixes an error for `Lint/SuppressedException` when `AllowNil: true` is set and endless method definition is used. commit 4a759953dc48465daabe068d323f6a220306ea02 Author: Bozhidar Batsov Date: Mon Jul 31 08:20:41 2023 +0300 Switch back the docs version commit 000ae5784e4e14657c4927376be41ac2be2c323b Author: Bozhidar Batsov Date: Mon Jul 31 08:19:31 2023 +0300 Cut 1.55.1 commit 89c304547e43e5cfb8ca87ebda24e79732f4ca8c Author: Bozhidar Batsov Date: Mon Jul 31 08:19:01 2023 +0300 Update Changelog commit 6e01713b5dc3144374ff71e849e402654c7ab287 Author: Koichi ITO Date: Mon Jul 31 00:00:22 2023 +0900 [Fix #12079] Fix an error for `Style/MixinGrouping` Fixes #12079. This PR fixes an error for `Style/MixinGrouping` when mixin method has no arguments. commit ee26d06619af5a95f12a337d943fba0dec96a57a Author: Koichi ITO Date: Mon Jul 31 12:58:51 2023 +0900 [Fix #12082] Fix an error for `Lint/UselessAssignment` Fixes #12082. This PR fixes an error for `Lint/UselessAssignment` when a variable is assigned and unreferenced in `for` with multiple variables. commit 59e940bbd7e3beb28c29a7230b771092776c8de1 Author: Koichi ITO Date: Sun Jul 30 23:04:14 2023 +0900 Use RuboCop RSpec 2.23 This commit uses RuboCop RSpec 2.23 and suppresses new `RSpec/ReceiveMessages` offenses. https://github.com/rubocop/rubocop-rspec/releases/tag/v2.23.0 commit 28e14569786103e875c9d7381c5cbb67fc9c219d Author: Koichi ITO Date: Sun Jul 30 16:34:00 2023 +0900 Make `InternalAffairs/ExampleDescription` aware of an incorrect term This PR makes `InternalAffairs/ExampleDescription` aware of an incorrect term `accepts` when using `expect_offense`. commit 2e1d3f9d2c745823572b66a25c6023068f7391bb Author: Koichi ITO Date: Sat Jul 29 15:42:29 2023 +0900 Fix a typo commit 24f6e997b9f30e90eb964248c674417d0c0f7e3a Author: Owen Stephens Date: Fri Jul 28 00:22:31 2023 +0100 [Fix #12070] Fix false positive in `Style/ArgumentsForwarding` Fixes a false positive caused by incorrectly searching in the receiver as well as arguments. commit 14e81adc3c11a2129d4e9c3f2991b15fb58ed528 Author: Koichi ITO Date: Wed Jul 26 02:48:35 2023 +0900 [Fix #12068] Fix a false positive for `Style/ReturnNilInPredicateMethodDefinition` Fixes #12068. This PR fixes a false positive for `Style/ReturnNilInPredicateMethodDefinition` when the last method argument in method definition is `nil`. commit d5b52dc23a1d6179ba7dc500360cd5a0e7e8917e Author: Koichi ITO Date: Fri Jul 28 12:30:09 2023 +0900 [Docs] Tweak examples for `Bundler/OrderedGems` and `Gemspec/OrderedDependencies` commit 46eb567f619dd2c6ceec58e15bf8db8abd28f891 Author: Steve Dierker Date: Tue Feb 28 11:30:52 2023 +0100 Correct Rubocop for `private_class_method` method documentation. See PR #11637 commit dcbfddf36066f6c57cec7052b50c33412987dd2e Author: Koichi ITO Date: Thu Jul 27 11:11:21 2023 +0900 [Docs] Use `Cop::Base` instead of `Cop::Cop` Follow up https://github.com/rubocop/rubocop/commit/f8813e76. commit 3f8582b2f32a219e37caf9c93928e3cdeadefc4c Author: Bozhidar Batsov Date: Tue Jul 25 18:29:55 2023 +0300 Switch back the docs version commit f3790afce259aec75bb94d571803c7e5488f1807 Author: Bozhidar Batsov Date: Tue Jul 25 18:26:49 2023 +0300 Cut 1.55 commit 6279c5750b6aa3341f38346e08536f7d03712264 Author: Bozhidar Batsov Date: Tue Jul 25 18:26:21 2023 +0300 Update Changelog commit 1dfe3862d95d33df31a5d29e3741cf34e4be2a5a Merge: d379d8e27 e00f96c2a Author: Koichi ITO Date: Wed Jul 26 00:07:09 2023 +0900 Merge pull request #12067 from p0deje/patch-1 Add changelog entry for #12062 commit e00f96c2aae979ac140fba48f04e1b264394e51e Author: Alex Rodionov Date: Tue Jul 25 07:39:32 2023 -0700 Add changelog entry for #12062 commit d379d8e278ef602f07682546595a96a61946159c Author: Alex Rodionov Date: Sat Jul 22 15:02:35 2023 -0700 Fix `LoadError` on Windows when loading RuboCop from symlinks There is a particular edge case when RuboCop is loaded from a fully symlinked environment. This is the default for Bazel which creates a tree of symlinks for every dependency, mimicking the real file tree structure. In such a setup, RuboCop would fail to load with an error. Resolving the path to an absolute one fixes it. ``` No such file or directory - //?/D:/_bazel/external/bundle/ruby/3.0.0/gems/rubocop-1.36.0/lib/rubocop/../../exe ... //?/D:/_bazel/external/bundle/ruby/3.0.0/gems/rubocop-1.36.0/lib/rubocop/result_cache.rb:208:in `each' ``` commit a1b302a3bc38703919666057bf0cdca6f753c48d Author: Owen Stephens Date: Tue Jul 25 07:43:24 2023 +0100 Enable anonymous forwarding in Style/ArgumentsForwarding for Ruby 3.2+ (#11794) commit 80efbc0f8afd95813a5515198ed93b73e3735484 Merge: 9bc006400 72ea08560 Author: Koichi ITO Date: Tue Jul 25 12:50:57 2023 +0900 Merge pull request #12065 from alexeyschepin/fix_ebug_for_lint_shadowing_outer_local_variable [Fix #11834] Fix false positive for variable in inside conditional branch in nested node commit 72ea0856030b398d63d98d9f2bb9e26c304b8f1d Author: Alexey Schepin Date: Mon Jul 24 22:05:22 2023 +0100 [Fix #11834] Fix false positive for when variable in inside conditional branch in nested node commit 9bc0064008f69533e25f4d7c375898c1121f6652 Author: Koichi ITO Date: Mon Jul 24 17:09:11 2023 +0900 Make `Style/RedundantArgument` aware of `exit` and `exit!` This PR makes aware of `Style/RedundantArgument` aware of `exit` and `exit!`. It require RuboCop AST 1.28.1+ that includes https://github.com/rubocop/rubocop-ast/pull/262. commit 7989e7d8cc3a924bc65b63a5b0efdc56f5c57e3f Author: Koichi ITO Date: Wed Jul 19 01:41:35 2023 +0900 Make LSP server support `lintMode` parameter This PR will provide `lintMode` (`rubocop -l`) as well as `layoutMode` (`rubocop -x`) . I think it's probably less demanding than LSP integration for formatters only, but this PR can provide it in advance. LSP client can run lint cops by passing the following `lintMode` parameter in the `initialize` request if you only want to enable the feature as a linter like `ruby -w`: ```json { "jsonrpc": "2.0", "id": 42, "method": "initialize", "params": { "initializationOptions": { "lintMode": true } } } ``` Furthermore, enabling autocorrect in a LSP client at the time of saving equates to the effect of `rubocop -l` option. For detailed instructions on setting the parameter, please refer to the configuration methods of your LSP client. commit fec9ed14eea32f23e7e46571e52084a5c7f1138a Merge: 2dd8281d1 c4f103c7d Author: Koichi ITO Date: Sun Jul 23 13:19:59 2023 +0900 Merge pull request #12063 from fatkodima/fix-combinable_loops-when-empty-loop Fix `Style/CombinableLoops` when one of the loops is empty commit c4f103c7d103c371134cda5ed319cce983dd792f Author: fatkodima Date: Sun Jul 23 03:45:51 2023 +0300 Fix `Style/CombinableLoops` when one of the loops is empty commit 2dd8281d169fc38197efca39e28ddf9871964b8b Merge: 765ed7d85 f3b33f0a6 Author: Koichi ITO Date: Sat Jul 22 04:19:09 2023 +0900 Merge pull request #12060 from fatkodima/fix-string_literals_in_interpolation-dsym Fix a false negative for `Style/StringLiteralsInInterpolation` for symbols with interpolation commit f3b33f0a6bda468a7385279bf367bd913257a365 Author: fatkodima Date: Fri Jul 21 11:23:19 2023 +0300 Fix a false negative for `Style/StringLiteralsInInterpolation` for symbols with interpolation commit 765ed7d855374928244aa4398ec499bd792b84a7 Merge: 3bf6d4132 80acfbdd7 Author: Koichi ITO Date: Sat Jul 22 03:34:15 2023 +0900 Merge pull request #12037 from jasondoc3/consider_brackets_as_bad_for_style_symbol_array [Fix #11802] Improve handling of [] and () with percent symbol arrays commit 80acfbdd7aeba5e20bdc3770f4ad11045017a395 Author: Jason Dougherty Date: Sun Jul 9 20:44:13 2023 -0700 [Fix rubocop#11802] Improve handling of delimiters with percent style symbol arrays commit 3bf6d4132736ac228efdaf0e85901acbaa968ce0 Author: Koichi ITO Date: Fri Jul 21 12:21:01 2023 +0900 Use `delete_suffix` to delete file extension `\z` will suffice rather than `\Z` in the regexp, since newline is never used in single file path name. So, `delete_suffix` can be used for file path name. commit c568070f2fb6f689823b69af79dff4497ae4b3ae Author: Koichi ITO Date: Thu Jul 20 06:50:43 2023 +0900 [Docs] Update the LSP document Confirmation has been made for the operation of coc.nvim in Vim. commit dd98af0b75503f4e6af761f97657a3725641258a Merge: 5fd11c415 7fcd2908a Author: Koichi ITO Date: Wed Jul 19 03:00:32 2023 +0900 Merge pull request #12054 from meric426/master [Fix #12052] Handle all glob special characters commit 5fd11c41576a5154f51f5f403ee5add8bda4368f Author: Koichi ITO Date: Tue Jul 18 11:58:00 2023 +0900 [Docs] Update the LSP document commit 7fcd2908a9709731d9e4d2fb83ae974ab3ae39f1 Author: Martin Ericson Date: Mon Jul 17 13:51:17 2023 +0200 [Fix #12052] Handle all glob special characters Co-Authored-By: Love Ottosson commit 8e3046338488277e3d4e6071b7ee81647684a7a5 Merge: a01e6f4c8 d9c59d12c Author: Koichi ITO Date: Tue Jul 18 00:13:46 2023 +0900 Merge pull request #12055 from gsamokovarov/parentheses-in-single-line-pattern-match Allow parentheses in single-line match patterns commit d9c59d12c599ea722933484902b4d4a7b721be8e Author: Genadi Samokovarov Date: Mon Jul 17 17:03:04 2023 +0300 Allow parentheses in single-line match patterns ```ruby execute(query) => {elapsed:, sql_count:} # (match-pattern # (send nil :execute # (send nil :query)) # (hash-pattern # (match-var :elapsed) # (match-var :sql_count))) ``` is a single-line pattern-match. The current version of the `omit_parentheses` style in `Style/MethodCallWithArgsParentheses` forces us to omit the parens in the call, making it a call with an options hash that has a string key and a value omitted hash as an value: ```ruby execute query => {elapsed:, sql_count:} # (send nil :execute # (kwargs # (pair # (send nil :query) # (hash # (pair # (sym :elapsed) # (send nil :elapsed)) # (pair # (sym :sql_count) # (send nil :sql_count)))))) ``` This is yet another ambiguity and we need to allow the parentheses when we pattern match the value of a call. commit a01e6f4c8c07314493498242be350ee3761ff66a Author: Koichi ITO Date: Mon Jul 17 00:29:31 2023 +0900 [Docs] Update some links in the Integration with Other Tools doc This commit updates old URLs to their corresponding new redirected URLs. commit 63b351527e07976c69ab7984bbec9bafd72c889e Merge: ac4a94bdc 6e62586b0 Author: Koichi ITO Date: Sun Jul 16 00:27:10 2023 +0900 Merge pull request #12050 from koic/fix_an_error_for_layout_redundant_line_break Fix a false positive for `Layout/RedundantLineBreak` commit 6e62586b03e9c913a51ebb77fbe5d729d3528979 Author: Koichi ITO Date: Sat Jul 15 02:20:59 2023 +0900 Fix a false positive for `Layout/RedundantLineBreak` This PR fixes a false positive for `Layout/RedundantLineBreak` to prevent the following incorrect autocorrection when inspecting the `%` form string `%\n\n`. First, `Layout/RedundantLineBreak` cop detects an offense upon inspection, but it's valid syntax: ```console $ echo "x = %\n\n" | be rubocop --stdin example.rb --enable-pending-cops --only Layout/RedundantLineBreak Inspecting 1 file C Offenses: example.rb:1:1: C: [Correctable] Layout/RedundantLineBreak: Redundant line break detected. x = % ... ^^^^^ 1 file inspected, 1 offense detected, 1 offense autocorrectable ``` Next, `Layout/RedundantLineBreak` cop autocorrects to an invalid syntax and `Lint/Syntax` occurs: ```console % echo "x = %\n\n" | be rubocop --stdin example.rb --enable-pending-cops --only Layout/RedundantLineBreak -a Inspecting 1 file F Offenses: example.rb:1:1: C: [Corrected] Layout/RedundantLineBreak: Redundant line break detected. x = % ... ^^^^^ example.rb:1:5: F: Lint/Syntax: unterminated string meets end of file (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) x = % ^ 1 file inspected, 2 offenses detected, 1 offense corrected ==================== x = % ``` commit ac4a94bdc13fe386d2b55847fa4213ddb644e8e9 Author: Koichi ITO Date: Fri Jul 14 12:59:24 2023 +0900 [Docs] Add reference to LSP to quickstart section This PR adds reference to RuboCop's built-in LSP to quickstart section in the README. While I recognize that the quickstart section is expanding, I think that due to its potential to dramatically change the development experience, LSP is worth mentioning as a second form of magic. To keep the quickstart text concise, I have not mentioned the required RuboCop version. It can be easily found by referring to the linked page. commit 44ef1bc70c83646642a803e3bd4b4ab9e47033de Author: Koichi ITO Date: Mon Jul 3 10:53:42 2023 +0900 [Fix #12015] Mark `Style/HashConversion` as unsafe autocorrection Fixes #12015. This PR marks `Style/HashConversion` as unsafe autocorrection. This cop's autocorrection is unsafe because `ArgumentError` occurs if the number of elements is odd: ```ruby Hash[[[1, 2], [3, 4], [5]]] #=> {1=>2, 3=>4, 5=>nil} [[1, 2], [3, 4], [5]].to_h #=> wrong array length at 2 (expected 2, was 1) (ArgumentError) ``` For example, this cannot be avoided when the arguments are variables. commit dd218290e3e71fe7af498e5ca4b5ac0fac4cb767 Author: Koichi ITO Date: Thu Jul 13 19:37:36 2023 +0900 [Fix #12046] Make `ReturnNilInPredicateMethodDefinition` aware of `nil` at the end of method Fixes #12046. This PR makes `ReturnNilInPredicateMethodDefinition` aware of `nil` at the end of predicate method definition. commit f8f8ffcda1d2ad5c0134a5c6ab66cafca43563e9 Author: Koichi ITO Date: Thu Jul 13 00:53:24 2023 +0900 [Fix #12044] Make LSP server support `layoutMode` parameter Fixes #12044. LSP client can run layout cops by passing the following `layoutMode` parameter in the `initialize` request. ```json { "jsonrpc": "2.0", "id": 42, "method": "initialize", "params": { "initializationOptions": { "layoutMode": true } } } ``` Furthermore, enabling autocorrect in a LSP client at the time of saving equates to the effect of `rubocop -x` option. For detailed instructions on setting the parameter, please refer to the configuration methods of your LSP client. commit c52feac313a71aaa3fd6a1006698f81aef3e03cc Author: Bozhidar Batsov Date: Thu Jul 13 14:11:51 2023 +0300 [Docs] Add a footnote commit 021ae3c1623064a197295352b58288ee45b9b8a9 Author: Bozhidar Batsov Date: Thu Jul 13 14:03:17 2023 +0300 Switch back the docs version commit bfbf59751175dae02db38ece1960ede920049ece Author: Bozhidar Batsov Date: Thu Jul 13 14:02:11 2023 +0300 Cut 1.54.2 commit 514f52e45869d740108278ef0d05eebeb92dce70 Author: Bozhidar Batsov Date: Thu Jul 13 14:01:49 2023 +0300 Update Changelog commit 6fc9a2146a4309e422cfa4402e121fa975a6eeae Author: Koichi ITO Date: Thu Jul 13 16:44:17 2023 +0900 [Doc] Fix an incorrect link in the LSP doc commit 02c32b4cf3801f9cf4cca4b3f1f4288aaee2ad5c Author: Koichi ITO Date: Wed Jul 12 00:09:01 2023 +0900 Fix a false negative for `Layout/ExtraSpacing` This PR fixes a false negative for `Layout/ExtraSpacing` when some character are vertically aligned. For example, there is a wasted space before the `do` keyword. ```ruby d_is_vertically_aligned do _______________________d end ``` The `d` char is accidentally vertically aligned and cannot be detected: ```console $ bundle exec rubocop --only Layout/ExtraSpacing (snip) 1 file inspected, no offenses detected ``` Looking at the test code, it looks like this is to allow vertical alignment of dots in method calls: ```ruby y, m = (year * 12 + (mon - 1) + n).divmod(12) m, = (m + 1) .divmod(1) ``` https://github.com/rubocop/rubocop/blob/v1.54.1/spec/rubocop/cop/layout/extra_spacing_spec.rb#L172-L177 Therefore, this PR tweaks the alignment logic to be closer to the expected behavior. And it also suppresses the following new offenses found with this tweak: ```console $ bundle exec rubocop (snip) lib/rubocop/string_interpreter.rb:37:18: C: [Correctable] Layout/ExtraSpacing: Unnecessary spacing detected. when /\d/ then interpret_octal(escape) ^^^^^^ spec/rubocop/target_finder_spec.rb:74:35: C: [Correctable] Layout/ExtraSpacing: Unnecessary spacing detected. create_file('dir1/executable', '#!/usr/bin/env ruby') ^ 1513 files inspected, 3 offenses detected, 3 offenses autocorrectable ``` commit bd4e0dbc9d8e2e6026a951b3700ed522f1676dcb Merge: 6a8e06d68 dbde254d2 Author: Koichi ITO Date: Tue Jul 11 01:57:55 2023 +0900 Merge pull request #12040 from koic/fix_a_false_positive_for_layout_trailing_empty_lines Fix a false positive for `Layout/TrailingEmptyLines` commit 6a8e06d687041b3e68d9a9fbcb31bd58e2a2066e Author: Koichi ITO Date: Tue Jul 11 01:11:12 2023 +0900 [Doc] Add a configuration example of nvim-lspconfig to the LSP doc commit a6d5a17ed159f3c5bc0bbbf680d4d8f49f2c67a5 Author: Koichi ITO Date: Mon Jul 10 19:28:25 2023 +0900 Use `AST::Node#call_type?` commit dbde254d2aa033f9ae2200b36de4667da2fc6db8 Author: Koichi ITO Date: Mon Jul 10 09:37:33 2023 +0900 Fix a false positive for `Layout/TrailingEmptyLines` This PR fixes a false positive for `Layout/TrailingEmptyLines` to prevent the following incorrect autocorrection when inspecting the `%` form string `%\n\n`. First, `Layout/TrailingEmptyLines` cop detects an offense upon inspection, but it's valid syntax: ```console $ echo "x = %\n\n" | be rubocop --stdin example.rb --only Layout/TrailingEmptyLines Inspecting 1 file C Offenses: example.rb:2:1: C: [Correctable] Layout/TrailingEmptyLines: 2 trailing blank lines detected. 1 file inspected, 1 offense detected, 1 offense autocorrectable ``` Next, `Layout/TrailingEmptyLines` cop autocorrects to an invalid syntax and `Lint/Syntax` occurs: ``` $ echo "x = %\n\n" | be rubocop --stdin example.rb --only Layout/TrailingEmptyLines -a Inspecting 1 file F Offenses: example.rb:1:5: F: Lint/Syntax: unterminated string meets end of file (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) x = % ^ example.rb:2:1: C: [Corrected] Layout/TrailingEmptyLines: 2 trailing blank lines detected. 1 file inspected, 2 offenses detected, 1 offense corrected ==================== x = % ``` commit a57385598c9b26d594fdef0f09bde341aa81573f Merge: 97af12887 34faa8cc9 Author: Koichi ITO Date: Sun Jul 9 16:04:31 2023 +0900 Merge pull request #12038 from knu/output_restarting_message_to_stderr Output the "server restarting" message to stderr commit 34faa8cc9ec360b75bc642e21751fa35dba89e49 Author: Akinori MUSHA Date: Sun Jul 9 13:57:44 2023 +0900 Output the "server restarting" message to stderr When using Rubocop with `--autocorrect --stderr`, the standard output should not contain anything other than the autocorrected source. commit 97af12887b80855ee626bc86907e1efd3d56fbbb Merge: d15a2a1da a27433ac8 Author: Koichi ITO Date: Sun Jul 9 09:02:50 2023 +0900 Merge pull request #12035 from koic/fix_an_error_when_using_an_invalid_encoding_string [Fix #12034] Fix an error when using an invalid encoding string commit d15a2a1dab5837f583dfb33113f71946af563229 Merge: 1fc59fc57 2ee5549bb Author: Koichi ITO Date: Sat Jul 8 14:57:17 2023 +0900 Merge pull request #12032 from koic/fix_an_error_when_allcops_exclude_is_empty [Fix #1867] Fix an error when `AllCops:Exclude` is empty in .rubocop.yml commit a27433ac89137b5c704056dcb0281249ad9357a8 Author: Koichi ITO Date: Sat Jul 8 14:15:07 2023 +0900 [Fix #12034] Fix an error when using an invalid encoding string Fixes #12034. This PR fixes invalid byte sequence in UTF-8 error when using an invalid encoding string. commit 1fc59fc575fb1dc6634b2f687e854a7eb9ff713a Author: Koichi ITO Date: Sat Jul 8 01:26:43 2023 +0900 [Doc] Add a configuration example of Neovim to the LSP doc commit 1a13d7ad982ee30cc9678be5c66077ac8044a1a7 Author: Koichi ITO Date: Fri Jul 7 03:53:26 2023 +0900 [Doc] Tweak the Integration with Other Tools doc commit 814d4e9a2861b6bb6c8e40c14e21d957376c1a65 Author: Koichi ITO Date: Thu Jul 6 22:07:04 2023 +0900 Remove a redundant return condition for `Style/Semicolon` https://github.com/rubocop/rubocop/pull/11300 made the condition unnecessary. commit 2ee5549bbd664dc9a941f74d7f3ae0bb090447ca Author: Koichi ITO Date: Thu Jul 6 00:01:54 2023 +0900 [Fix #1867] Fix an error when `AllCops:Exclude` is empty in .rubocop.yml Fixes #1867. This PR fixes the following error when `AllCops:Exclude` is empty in .rubocop.yml. ```console $ cat .rubocop.yml AllCops: Exclude: $ rubocop (snip) private method `select' called for nil /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/rubocop-1.54.1/lib/rubocop/target_finder.rb:118: in `combined_exclude_glob_patterns' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/rubocop-1.54.1/lib/rubocop/target_finder.rb:85: in `find_files' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/rubocop-1.54.1/lib/rubocop/target_finder.rb:59: in `target_files_in_dir' ``` commit 77706a8860af55400c77cf18ccc4ebec3988cb8e Author: Koichi ITO Date: Wed Jul 5 01:10:00 2023 +0900 Tweak offense range highlight for `Naming/HeredocDelimiterNaming` Follow https://github.com/rubocop/rubocop/pull/11999#issuecomment-1613469560 This PR tweaks offense range highlight. ```console $ cat /tmp/heredoc.rb <<~'' ``` ## Before It was registering an offense as expected, but the offense range was not showing: ```console $ bundle exec rubocop /tmp/heredoc.rb --only Naming/HeredocDelimiterNaming Inspecting 1 file C Offenses: /tmp/heredoc.rb:1:1: C: Naming/HeredocDelimiterNaming: Use meaningful heredoc delimiters. 1 file inspected, 1 offense detected ``` ## After It registers an offense as expected and shows the offense range: ```console $ bundle exec rubocop /tmp/heredoc.rb --only Naming/HeredocDelimiterNaming Inspecting 1 file C Offenses: /tmp/heredoc.rb:1:1: C: Naming/HeredocDelimiterNaming: Use meaningful heredoc delimiters. <<~'' ^^^^^ 1 file inspected, 1 offense detected ``` commit a5fea4311a57787cc498ecdc63bedc68bf444160 Merge: eae61bb17 6f9919f5e Author: Koichi ITO Date: Wed Jul 5 12:15:30 2023 +0900 Merge pull request #12031 from lucthev/return-nil-typo Fix typo in Style/ReturnNilInPredicateMethodDefinition docs commit 6f9919f5e3cbbdd457581fc5a79ff47bd225ad90 Author: Luc Thevenard Date: Tue Jul 4 22:50:05 2023 -0400 Fix typo in Style/ReturnNilInPredicateMethodDefinition docs commit eae61bb17ff39beecc1d8aa8c959ad2bc5921c92 Author: Bozhidar Batsov Date: Tue Jul 4 10:34:32 2023 +0300 Switch back the docs version commit dbee3c228ae3ca3e9331f7fe8487193d706424d7 Author: Bozhidar Batsov Date: Tue Jul 4 10:33:33 2023 +0300 Cut 1.54.1 commit 32e08848febedd4a48b21b994c984d919d113b4e Author: Bozhidar Batsov Date: Tue Jul 4 10:33:12 2023 +0300 Update Changelog commit 3ec4959989f8f832e1150f267306193bdf79d7d3 Author: Koichi ITO Date: Tue Jul 4 01:39:13 2023 +0900 [Fix #12020] Fix an error for `Layout/SpaceAfterComma` with `Layout/SpaceBeforeSemicolon` Fixes #12020. This PR fixes an infinite loop error for `Layout/SpaceAfterComma` with `Layout/SpaceBeforeSemicolon` when autocorrection conflicts. The use of semicolon after comma (`,;`) is limited, so making it difficult to default the presence or absence of space between the semicolon and the comma. This PR aims to prevent an infinite loop error occurrences by always allowing the absence of space after comma when it is followed by semicolon. commit c969b34464c5bdace2132f7e8d6cb52cee15a9a3 Author: Koichi ITO Date: Tue Jul 4 02:08:11 2023 +0900 [Fix #12024] Fix a false positive for `Lint/RedundantRegexpQuantifiers` Fixes #12024. This PR fixes a false positive for `Lint/RedundantRegexpQuantifiers` when interpolation is used in a regexp literal. commit 0932941b791812e91394d03a4cf869517fc63983 Author: Koichi ITO Date: Mon Jul 3 10:12:05 2023 +0900 [Fix #12014] Fix an error for `Lint/UselessAssignment` Fixes #12014. This PR fixes an error for `Lint/UselessAssignment` when part of a multiple assignment is enclosed in parentheses. commit fb54dac37ebba8ff0dedd5656c429e0e18e31220 Merge: fa8c74edf 0583bce5f Author: Koichi ITO Date: Mon Jul 3 01:35:34 2023 +0900 Merge pull request #12012 from ydah/fix-internal-affairs-location-line-equality-comparison Fix an error for `InternalAffairs/LocationLineEqualityComparison` when inside block commit 0583bce5f38f0f8afdd713c8a47971e376961617 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Sun Jul 2 20:33:03 2023 +0900 Fix an error for `InternalAffairs/LocationLineEqualityComparison` when inside block This PR if fix an error for `InternalAffairs/LocationLineEqualityComparison` when inside block. Code to reproduce: ```ruby nodes.select do |node| node.first_line == nodes.first.first_line end ``` Log: ``` An error occurred while InternalAffairs/LocationLineEqualityComparison cop was inspecting /ydah/rubocop-rspec/a.rb:2:2. undefined method `method?' for s(:lvar, :node):RuboCop::AST::Node /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb:54:in `extract_receiver' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb:41:in `on_send' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:107:in `public_send' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:107:in `block (2 levels) in trigger_responding_cops' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:171:in `with_cop_error_handling' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:106:in `block in trigger_responding_cops' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:105:in `each' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:105:in `trigger_responding_cops' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:69:in `on_send' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-ast-1.29.0/lib/rubocop/ast/traversal.rb:158:in `on_block' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:71:in `on_block' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-ast-1.29.0/lib/rubocop/ast/traversal.rb:20:in `walk' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/commissioner.rb:87:in `investigate' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/team.rb:156:in `investigate_partial' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cop/team.rb:98:in `investigate' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:345:in `block in inspect_file' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:344:in `each' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:344:in `flat_map' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:344:in `inspect_file' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:287:in `block in do_inspection_loop' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:321:in `block in iterate_until_no_changes' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:314:in `loop' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:314:in `iterate_until_no_changes' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:283:in `do_inspection_loop' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:164:in `block in file_offenses' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:189:in `file_offense_cache' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:163:in `file_offenses' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:154:in `process_file' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:135:in `block in each_inspected_file' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:134:in `each' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:134:in `reduce' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:134:in `each_inspected_file' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:120:in `inspect_files' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/runner.rb:73:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/command/execute_runner.rb:26:in `block in execute_runner' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/command/execute_runner.rb:52:in `with_redirect' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/command/execute_runner.rb:25:in `execute_runner' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/command/execute_runner.rb:17:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/command.rb:11:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli/environment.rb:18:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli.rb:118:in `run_command' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli.rb:125:in `execute_runners' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli.rb:51:in `block in run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli.rb:77:in `profile_if_needed' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/lib/rubocop/cli.rb:43:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/exe/rubocop:19:in `block in ' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/benchmark.rb:311:in `realtime' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/rubocop-1.54.0/exe/rubocop:19:in `' /ydah/.rbenv/versions/3.2.2/bin/rubocop:25:in `load' /ydah/.rbenv/versions/3.2.2/bin/rubocop:25:in `' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli/exec.rb:58:in `load' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli/exec.rb:58:in `kernel_load' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli/exec.rb:23:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli.rb:492:in `exec' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/vendor/thor/lib/thor.rb:392:in `dispatch' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli.rb:34:in `dispatch' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/vendor/thor/lib/thor/base.rb:485:in `start' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/cli.rb:28:in `start' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bundler-2.4.10/libexec/bundle:45:in `block in ' /ydah/.rbenv/versions/3.2.2/lib/ruby/3.2.0/bundler/friendly_errors.rb:117:in `with_friendly_errors' /ydah/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bundler-2.4.10/libexec/bundle:33:in `' /ydah/.rbenv/versions/3.2.2/bin/bundle:25:in `load' /ydah/.rbenv/versions/3.2.2/bin/bundle:25:in `
' ``` RuboCop version: ``` rubocop -V 1.54.0 (using Parser 3.2.2.3, rubocop-ast 1.29.0, running on ruby 3.2.2) [x86_64-darwin21] - rubocop-performance 1.18.0 - rubocop-rake 0.6.0 - rubocop-rspec 2.22.0 ``` commit fa8c74edf32aacc8ca97a6ca1cb188ba9c17e2e6 Author: Koichi ITO Date: Sun Jul 2 02:45:39 2023 +0900 Fix an error for `Metrics/MethodLength` This PR fixes the following error for `Metrics/MethodLength` when using a heredoc in a block without block arguments: ```console $ cd path/to/rubocop-ast $ bundle exec rubocop -d --only Metrics/MethodLength lib/rubocop/ast/node_pattern/compiler/sequence_subcompiler.rb (snip) Scanning /Users/koic/src/github.com/rubocop/rubocop-ast/lib/rubocop/ast/node_pattern/compiler/sequence_subcompiler.rb An error occurred while Metrics/MethodLength cop was inspecting /Users/koic/src/github.com/rubocop/rubocop-ast/lib/ rubocop/ast/node_pattern/compiler/sequence_subcompiler.rb:88:10. undefined method `last_line' for nil /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/parser-3.2.2.3/lib/parser/source/map.rb:118: in `last_line' /Users/koic/src/github.com/rubocop/rubocop-ast/lib/rubocop/ast/node.rb:266:in `last_line' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/metrics/utils/code_length_calculator.rb:199: in `block in source_from_node_with_heredoc' ``` commit 59984740f34847f8194f241e9a9d8027de99d342 Author: Koichi ITO Date: Sun Jul 2 00:33:50 2023 +0900 Fix false negatives for `Style/RedundantRegexpArgument` This PR fixes false negatives for `Style/RedundantRegexpArgument` when using safe navigation operator. commit ff0effde9b7490578ee2713da17a0ebfa5e755cc Author: Bozhidar Batsov Date: Sat Jul 1 11:17:07 2023 +0300 Switch back the docs version commit 1b578aa82fd27ab39c4ffdb7284f8aeb04443973 Author: Bozhidar Batsov Date: Sat Jul 1 11:13:56 2023 +0300 Cut 1.54 commit a31da695306b051ddcc02634f0ddcf8f861698e3 Author: Bozhidar Batsov Date: Sat Jul 1 11:13:11 2023 +0300 Update Changelog commit a60b19d68abcdad50dc1c7cbe99489e2a595b319 Author: Koichi ITO Date: Sat Jul 1 00:01:28 2023 +0900 Fix an error for `Style/YodaCondition` This PR fixes an error for `Style/YodaCondition` when equality check method is used without the first argument: ```ruby foo.== ``` ```console % rubocop /tmp/example.rb --only Style/YodaCondition -d (snip) For /tmp: An error occurred while Style/YodaCondition cop was inspecting /tmp/example.rb:1:0. undefined method `literal?' for nil:NilClass An error occurred while Style/YodaCondition cop was inspecting /tmp/example.rb:1:0. undefined method `literal?' for nil /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/rubocop-1.53.1/lib/ rubocop/cop/style/yoda_condition.rb:144:in `constant_portion?' /Users/koic/.rbenv/versions/3.3.0-dev/lib/ruby/gems/3.3.0+0/gems/rubocop-1.53.1/lib/ rubocop/cop/style/yoda_condition.rb:126:in `valid_yoda?' ``` commit 00dff1331a2b70ff818cf3670a0e5facd466988d Author: Koichi ITO Date: Fri Jun 30 23:31:13 2023 +0900 [Fix #12007] Fix an error for `Layout/SpaceAroundOperators` Fixes #12007. This PR fixes an error for `Layout/SpaceAroundOperators` when using unary operator with double colon. commit 2a606c4be884afedbe9159e938f0ca1a827bebdd Author: Koichi ITO Date: Fri Jun 30 21:46:25 2023 +0900 [Fix #12005] Fix a false negative for `Lint/Debugger` Fixes #12005. This PR fixes a false negative for `Lint/Debugger` when using debugger method inside lambda. commit 7e8c47d0e943ee6bce839f7ae5159f1b50b25607 Author: Koichi ITO Date: Sat Jun 10 02:53:56 2023 +0900 Support safe or unsafe autocorrect config for LSP This PR supports safe or unsafe autocorrect config for LSP. The autocorrection is still safe by default (`rubocop -a`). LSP client can switch to unsafe autocorrection (`rubocop -A`) by passing the following `safeAutocorrect` parameter in the `initialize` request. ```json { "jsonrpc": "2.0", "id": 42, "method": "initialize", "params": { "initializationOptions": { "safeAutocorrect": false } } } ``` Some users may want to set unsafe autocorrection as the default for the LSP, understanding the risks involved. However, considering that the default should be safe, unsafe is an option. commit 94fac02a7fc9e4b3597e6e710093dffb79f2cd97 Author: Koichi ITO Date: Fri Jun 30 00:38:05 2023 +0900 [Fix #11998] Fix an error when inspecting blank heredoc delimiter Fixes #11998. This PR fixes an error when inspecting blank heredoc delimiter. commit 00bd55ba0fcd6f45a0c2f93c071faf9934bc0f95 Author: fatkodima Date: Fri Jun 30 02:14:58 2023 +0300 Fix code length calculator for method calls with heredoc commit 293b7f41f8112ccb9f6afb2b1d46f9bd659b3789 Merge: 4f83077d0 c7821e2d5 Author: Koichi ITO Date: Fri Jun 30 10:25:48 2023 +0900 Merge pull request #12004 from fatkodima/fix-lint-void-for-__encoding__ Fix `Lint/Void` cop for `__ENCODING__` constant commit c7821e2d5f1471705c921e5c2cc5ed4a75f16da9 Author: fatkodima Date: Fri Jun 30 03:02:09 2023 +0300 Fix `Lint/Void` cop for `__ENCODING__` constant commit 4f83077d045135b411dca3f59cfd5c8290ab5322 Author: Koichi ITO Date: Thu Jun 29 18:50:29 2023 +0900 [Fix #11994] Fix an error for `Layout/LineEndStringConcatenationIndentation` Fixes #11994. This PR fixes an error for `Layout/LineEndStringConcatenationIndentation` when inspecting the `%` form string `%\n\n`. commit 141121a5115c7031623ac1bc9da7ef8ade064b7a Author: Koichi ITO Date: Thu Jun 29 22:57:27 2023 +0900 [Fix #11996] Fix an error for `Style/IfWithSemicolon` Fixes #11996. This PR fixes an error for `Style/IfWithSemicolon` when without branch bodies. commit aaf1c3f6285e5e9e84d43c37944a7faaacb3bf60 Author: Koichi ITO Date: Thu Jun 29 01:36:25 2023 +0900 Use `LambdaNode#lambda_literal?` commit a51af25ae61c58c82b4c672cb66334bfab6f326f Author: Koichi ITO Date: Wed Jun 28 21:22:34 2023 +0900 [Fix #11992] Fix an error for built-in language server Fixes #11992. This PR fixes an unexpected `NoMethodError` for LSP mode when an internal error occurs. commit 2b646aa9a9f81807610cb1c061190a5efc299457 Author: Koichi ITO Date: Wed Jun 28 11:47:52 2023 +0900 [Fix #11989] Fix an incorrect autocorrect for `Style/RedundantRegexpArgument` Fixes #11989. This PR fixes an incorrect autocorrect for `Style/RedundantRegexpArgument` when using unicode chars. This is a resolution applying the feedback below: https://github.com/rubocop/rubocop/pull/11595#discussion_r1231268032 commit 408a76603d203d03158fa3012b3354d2238f8cd6 Author: Koichi ITO Date: Tue Jun 27 01:26:54 2023 +0900 [Doc] Tweak the LSP doc I've observed an instance where a user manually execute `rubocop --lsp`, which is unnecessary for starting the LSP server. This PR will clarify in the documentation that it is not necessary to run `rubocop --lsp`. And, the sections have been reorganized in the order of most likely to draw user interest. commit d69fcd0964a441e085a199deb0f55d2e87731a0d Merge: 16b893429 892dc4061 Author: Koichi ITO Date: Tue Jun 27 02:18:08 2023 +0900 Merge pull request #11987 from koic/fix_a_false_positive_for_lint_mixed_case_range [Fix #11986] Fix a false positive for `Lint/MixedCaseRange` commit 892dc406148583b213132599d5c40bca5bcae9ff Author: Koichi ITO Date: Mon Jun 26 22:20:32 2023 +0900 [Fix #11986] Fix a false positive for `Lint/MixedCaseRange` Fixes #11986. This PR fixes a false positive for `Lint/MixedCaseRange` when the number of characters at the start or end of range is other than 1. commit 16b893429666524af16b7cf39acee06eb6b597f1 Author: ydah <13041216+ydah@users.noreply.github.com> Date: Mon Jun 26 12:52:26 2023 +0900 Add Ridgepole files to default `Include` list With ridgepole, we can write Ruby DSLs in files called `Schemafile` or `.schema`. https://github.com/ridgepole/ridgepole For example: ```ruby create_table "users", force: :cascade do |t| t.string "last_name" t.string "first_name" t.virtual "full_name", type: :string, as: "concat(`last_name`,' ',`first_name`)", stored: true end ``` commit 77a756d5e62a50a212b9269caa80d3f5aec55685 Author: Chester Twomey Date: Sun Mar 5 17:02:07 2023 -0600 [Fix #11738]: Enhances empty_line_between_defs to treat configured macros like defs commit 2598f72d83038426ffad04d708d986550c8c8b09 Author: Bozhidar Batsov Date: Mon Jun 26 13:57:41 2023 +0300 Switch back the docs version commit c4913f4a1acad8aad727d2ec6e647f7920a2961a Author: Bozhidar Batsov Date: Mon Jun 26 13:55:54 2023 +0300 Cut 1.53.1 commit 9db2b2e5ead6608b7a3114b6d080e5f04785e2fa Author: Bozhidar Batsov Date: Mon Jun 26 13:55:32 2023 +0300 Update Changelog commit eac0642849c8e3b58f8c6036a1322c18d7412299 Author: Koichi ITO Date: Mon Jun 26 11:17:00 2023 +0900 [Fix #11981] Fix an incorrect autocorrect for `Style/RedundantRegexpArgument` Fixes #11981. This PR fixes an incorrect autocorrect for `Style/RedundantRegexpArgument` when using double quote and single quote characters. commit 2339e262c5995fe1ce81bc23881e25412004be97 Merge: 8d2c6ae75 a263e4e28 Author: Koichi ITO Date: Sun Jun 25 01:18:50 2023 +0900 Merge pull request #11970 from KessaPassa/feat/symbol-conversion-in-double-quote [#11836] should not offense single-quoted symbol containing double quotes in `Lint/SymbolConversion` commit 8d2c6ae75c898a4a8d55d19f3b2e72a48026d949 Author: Koichi ITO Date: Fri Jun 23 19:40:14 2023 +0900 [Fix #11974] Fix an error for `Style/RedundantCurrentDirectoryInPath` Fixes #11974. This PR fixes an error for `Style/RedundantCurrentDirectoryInPath` when using string interpolation in `require_relative`. commit 5a38fe3dbfff922fe19d3b3330eaf1995595f1ac Author: Takuya N Date: Sat Jun 24 15:51:45 2023 +0900 Fix PR reference in CHANGELOG.md 1.51.0 Ruby 2.6 runtime support was dropped in PR: https://github.com/rubocop/rubocop/pull/11791 commit a263e4e28ca5de79d8ff426865323b74b822dc87 Author: KessaPassa Date: Fri Jun 23 13:41:03 2023 +0900 [Fix rubocop#11836] should not offense single-quoted symbol containing double quotes fix: split tests for independence commit b3841fb778764667f04806ad6440482ab2988f35 Merge: 08dbb424a 508269ff1 Author: Koichi ITO Date: Sat Jun 24 02:13:23 2023 +0900 Merge pull request #11976 from koic/add_vscode_rubocop_to_lsp_doc Add vscode-rubocop to the LSP doc commit 508269ff1dbd9bf0abc8343ca647a9f00ef28824 Author: Koichi ITO Date: Fri Jun 23 20:19:49 2023 +0900 [Doc] Add vscode-rubocop to the LSP doc vscode-rubocop has been released: https://marketplace.visualstudio.com/items?itemName=rubocop.vscode-rubocop This PR adds vscode-rubocop to the LSP doc. commit 08dbb424a327d406cc49f61ba20a0b26d8ccc475 Author: Koichi ITO Date: Fri Jun 23 18:54:20 2023 +0900 Fix a build error This commit fixes the following build error: ```console Failures: 1) RuboCop Project Changelog entry contributor name has a unique contributor name Failure/Error: expect(contributor_names.uniq.size).to eq contributor_names.size expected: 621 got: 620 (compared using ==) Shared Example Group: "has Changelog format" called from ./spec/project_spec.rb:280 ``` https://github.com/rubocop/rubocop/actions/runs/5355047135/jobs/9712842760 commit 0be62c2a40dfdd92286bf01e502de4b9e1270be5 Author: Bozhidar Batsov Date: Fri Jun 23 12:44:49 2023 +0300 Switch back the docs version commit 80485d201d62b605118eb81416db6b999444c65d Author: Bozhidar Batsov Date: Fri Jun 23 12:43:44 2023 +0300 Cut 1.53 commit f6bac40672c0b03a9ca973538265c82a26dbd062 Author: Bozhidar Batsov Date: Fri Jun 23 12:43:07 2023 +0300 Update Changelog commit f23bd40b35b359d90e18d635455d3503db43ad16 Author: Koichi ITO Date: Fri Jun 23 17:47:00 2023 +0900 [Fix #11972] Fix an error for `Lint/Void` Fixes #11972. This PR fixes an error for `Lint/Void` when `CheckForMethodsWithNoSideEffects: true` and using a method definition. commit 04ea2073d689b8578be547da3e45bc7750b82c56 Author: Koichi ITO Date: Tue Jun 6 02:41:00 2023 +0900 Fix a false positive for `Lint/RedundantRequireStatement` Follow up https://github.com/rubocop/rubocop/issues/11099#issuecomment-1577117258 This PR fixes a false positive for `Lint/RedundantRequireStatement` when using `PP.pp`. commit 273f9bd0b12cca0e1f1ea3db92661379a3c545b4 Author: Evan Goldenberg Date: Thu Jun 22 22:38:54 2023 -0700 Revert "Change include paths to be relative to working directory rather than derived dir" This reverts commit c9ccb2f35c752b42c3e87f926ee7ed74fd26dca8. commit 1ed69f8bfc85113b65e2660c316634e8c6089938 Author: Koichi ITO Date: Wed Jun 21 00:50:18 2023 +0900 Add new `Style/ReturnNilInPredicateMethodDefinition` cop This PR adds new `Style/ReturnNilInPredicateMethodDefinition` cop that checks for `return` or `return nil` is used in predicate method definitions. ```ruby # bad def foo? return if condition do_something? end # bad def foo? return nil if condition do_something? end # good def foo? return false if condition do_something? end ``` Autocorrection is marked as unsafe because the change of the return value from `nil` to `false` could potentially lead to incompatibility issues. commit 0c5c4fc010c1f79ae37773784aa673f50cf25f33 Author: Koichi ITO Date: Fri Jun 23 00:53:47 2023 +0900 Remove a useless style guide URL Follow up https://github.com/rubocop/rubocop/pull/4090. There is no style guide called https://rubystyle.guide/#syntax. commit 766e2084a82d14d120edf19caf5e72bd88c4fb11 Author: nick evans Date: Tue May 30 16:52:20 2023 -0400 Mark Layout/ClassStructure as unsafe to autocorrect Autocorrection is unsafe because class methods and module inclusion can behave differently, based on which methods or constants have already been defined. commit 1e2d84a4bfbd795e1f287c8f48c46899d2d00d8c Merge: 9c9c04a89 09d0ff547 Author: Koichi ITO Date: Thu Jun 22 00:21:25 2023 +0900 Merge pull request #11940 from iMacTia/fix/lint-missing-super-configurable-stateless-classes [Fix #8506] Add AllowedParentClasses config to Lint/MissingSuper. commit 09d0ff5470da42864ffc1986213641503af311dd Author: Mattia Giuffrida Date: Thu Jun 8 14:16:50 2023 +0100 [Fix #8506] Add AllowedParentClasses config to Lint/MissingSuper. The default value of %w[BasicObject Object] is kept for backwards compatibility, but users can now add to that list using the AllowedParentClasses config value. commit 9c9c04a89aae78ff560365615edee59a8974194c Merge: d9b431b51 4c1195687 Author: Koichi ITO Date: Wed Jun 21 13:30:47 2023 +0900 Merge pull request #11562 from rwstauner/rwstauner/duplicate-regexp-char-octals Fix handling of escaped octals in duplicate regexp cop commit d9b431b51f91acc36d4d66deca73882af65be101 Author: Koichi ITO Date: Tue Jun 20 17:17:47 2023 +0900 Prevent false positives for `Style/RedundantRegexpArgument` Follow up https://github.com/rubocop/rubocop/pull/11595#discussion_r1232129711. This commit prevents the following false positives for `Style/RedundantRegexpArgument` when using `index` and `rindex`: ```console [/foo/, /bar/, /baz/].index(/foo/) [/foo/, /bar/, /baz/].rindex(/foo/) ``` commit f15a85a7d8b9862a03f207aaca01d91d153243a2 Author: Koichi ITO Date: Sun Feb 19 03:44:30 2023 +0900 Add new `Style/RedundantRegexpArgument` cop This PR adds new `Style/RedundantRegexpArgument` cop. It identifies places where argument can be replaced from a deterministic regexp to a string. ```ruby # bad 'foo'.byteindex(/f/) 'foo'.byterindex(/f/) 'foo'.gsub(/f/, 'x') 'foo'.gsub!(/f/, 'x') 'foo'.index(/f/) 'foo'.partition(/f/) 'foo'.rindex(/f/) 'foo'.rpartition(/f/) 'foo'.scan(/f/) 'foo'.split(/f/) 'foo'.sub(/f/, 'x') 'foo'.sub!(/f/, 'x') # good 'foo'.byteindex('f') 'foo'.byterindex('f') 'foo'.gsub('f', 'x') 'foo'.gsub!('f', 'x') 'foo'.index('f') 'foo'.partition('f') 'foo'.rindex('f') 'foo'.rpartition('f') 'foo'.scan('f') 'foo'.split('f') 'foo'.sub('f', 'x') 'foo'.sub!('f', 'x') ``` This is a superset of `Performance/RedundantSplitRegexpArgument` which only handles `String#split`: https://docs.rubocop.org/rubocop-performance/1.16/cops_performance.html#performanceredundantsplitregexpargument Changing the argument from regexp to string have a positive effect on readability as well as performance. So this cop is promoting Style department, not Performance department. In the future `Performance/RedundantSplitRegexpArgument` can be deprecated and replaced by this cop. commit 87f839957834091c04db15de6b92c99977c03de0 Author: Koichi ITO Date: Thu Mar 30 12:24:12 2023 +0900 Add new `Style/YAMLFileRead` cop This PR adds new `Style/YAMLFileRead` cop. It checks for the use of `YAML.load`, `YAML.safe_load`, and `YAML.parse` with `File.read` arguemnt. NOTE: `YAML.safe_load_file` was introduced in Ruby 3.0. ```ruby # bad YAML.load(File.read(path)) YAML.parse(File.read(path)) # good YAML.load_file(path) YAML.parse_file(path) # bad YAML.safe_load(File.read(path)) # Ruby 3.0 and newer # good YAML.safe_load_file(path) # Ruby 3.0 and newer ``` These good cases use intentionally shorthand methods. commit d7eaec708acf8b1ca6b68f03c03e69dbb6935c53 Author: Janosch Müller Date: Fri Feb 10 17:58:10 2023 +0100 Add new `Lint/RedundantRegexpQuantifiers` cop This cop checks for redundant quantifiers (a.k.a. repeat operators) in regular expression literals. Such redundant quantifiers also trigger a warning in the Ruby parser / Onigmo: ```sh ruby -e '/(?:a+)+/' -e:1: warning: regular expression has redundant nested repeat operator '+': /(?:a+)+/ ``` commit a127b04b1096ae919dcdab65b9ede79a1757b51c Author: Koichi ITO Date: Tue Jun 20 00:59:59 2023 +0900 [Fix #11962] Fix an error for `Style/RedundantStringEscape` Fixes #11962. This PR fixes an error for `Style/RedundantStringEscape` when an escaped double quote precedes interpolation in a symbol literal. commit 8509ced4facf74caf5a9782752475a0579f7c2b7 Author: Randy Stauner Date: Mon Jun 19 04:06:39 2023 -0700 Add new MixedCaseRange cop (#11561) commit 9caeab0643c0d0e064df80888b65f6147cfdf173 Author: Koichi ITO Date: Sun Jun 4 15:10:51 2023 +0900 [Fix #11924] Add new `Style/RedundantCurrentDirectoryInPath` cop Resolves #11924. This PR adds new `Style/RedundantCurrentDirectoryInPath` cop. It checks for uses a redundant current directory in path. ```ruby # bad require_relative './path/to/feature' # good require_relative 'path/to/feature' ``` The cop name `Style/RedundantCurrentDirectoryInPath` does not contain `RequireRelative` (`require_relative`). Because I thought it could be an abstract name that detects redundant current directory in path (`./`). So, if there are methods other than `require_relative` that certainly uses redundant current directory in path, this cop could be extended. commit fd4580193ce4bc2321568dbc36ec53ef17eb62f3 Author: Koichi ITO Date: Thu Jun 15 16:28:55 2023 +0900 [Fix #11953] Fix a false negative for `Lint/DuplicateHashKey` Fixes #11953. This PR fixes a false negative for `Lint/DuplicateHashKey` when there is a duplicated constant key in the hash literal. commit 9f1e478e84a8468b9260f3779f7d3c0360c7255f Author: Koichi ITO Date: Mon Jun 19 01:15:57 2023 +0900 Fix false negatives for `Layout/EmptyLinesAroundExceptionHandlingKeywords` This PR fixes a false negatives for `Layout/EmptyLinesAroundExceptionHandlingKeywords` when using Ruby 2.5's `rescue` inside block and Ruby 2.7's numbered block. commit 78c55dac31d67769c5002857c483860147af8b6d Merge: 35d5286ae d3cb57d32 Author: Koichi ITO Date: Sun Jun 18 00:36:56 2023 +0900 Merge pull request #11958 from koic/fix_an_error_for_style_identical_conditional_branches Fix an error for `Style/IdenticalConditionalBranches` commit d3cb57d32c6a405e786e7b2a895d8a8febab1d7f Author: Koichi ITO Date: Sat Jun 17 00:53:00 2023 +0900 Fix an error for `Style/IdenticalConditionalBranches` This PR fixes the following error for `Style/IdenticalConditionalBranches` when using empty parentheses in the `if` branch: ```console $ cat example.rb if condition () else foo end $ bundle exec rubocop --only Style/IdenticalConditionalBranches -d (snip) An error occurred while Style/IdenticalConditionalBranches cop was inspecting /Users/koic/src/github.com/koic/rubocop-issues/identical_conditional_branches/example.rb:1:0. undefined method `assignment?' for nil:NilClass /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/identical_conditional_branches.rb:161:in `duplicated_expressions?' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/identical_conditional_branches.rb:146:in `check_branches' /Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/style/identical_conditional_branches.rb:120:in `on_if' ``` commit 35d5286ae52ea89826732b6a05df23625a6432eb Merge: 144b578b2 f89aadb4e Author: Koichi ITO Date: Fri Jun 16 01:13:05 2023 +0900 Merge pull request #11951 from koic/fix_a_false_negative_for_style_redundant_self_assignment_branch [Fix #11945] Fix a false negative for `Style/RedundantSelfAssignmentBranch` commit f89aadb4ecc861ab96644d1401a58c1ad20fa212 Author: Koichi ITO Date: Wed Jun 14 14:34:25 2023 +0900 [Fix #11945] Fix a false negative for `Style/RedundantSelfAssignmentBranch` Fixes #11945. This PR fixes a false negative for `Style/RedundantSelfAssignmentBranch` when using method chaining or arguments in ternary branch. commit 4c1195687da1ad8826995d7f22febd49e9a00393 Author: Randy Stauner Date: Fri Feb 10 11:30:21 2023 -0700 Simplify range length construction te is the same as ts + length plus te is angering the spell checker commit e9cd864d5d509635c3bbd54930b2e4089f11396d Author: Randy Stauner Date: Fri Feb 10 11:26:52 2023 -0700 Use comments and a constant to clarify octal logic commit 198ffb535bdfe0d093b989b70c610cc7fb2ca007 Author: Randy Stauner Date: Thu Feb 9 12:35:06 2023 -0700 Add changelog entry commit 90e7a5434abafe85d26be4a649d0b6ce5beb8e13 Author: Randy Stauner Date: Thu Feb 9 12:30:36 2023 -0700 Fix handling of escaped octals in duplicate regexp cop --- .circleci/config.yml | 37 +- .github/ISSUE_TEMPLATE/bug_report.md | 6 +- .github/workflows/linting.yml | 2 +- .github/workflows/rubocop.yml | 8 +- .github/workflows/spell_checking.yml | 4 +- .rubocop.yml | 16 +- CHANGELOG.md | 469 ++++- CONTRIBUTING.md | 6 +- Gemfile | 4 +- LICENSE.txt | 2 +- README.md | 8 +- Rakefile | 4 +- ...ge_error_message_on_incorrect_namespace.md | 1 + .../change_mark_style_raise_args_as_unsafe.md | 1 + .../change_source_order_for_target_ruby.md | 1 + ...ositive_for_layout_redundant_line_break.md | 1 - ...fix_an_error_for_lint_number_conversion.md | 1 - .../fix_an_error_for_style_case_like_if.md | 1 + ...correct_for_lint_empty_conditional_body.md | 1 + ...tyle_map_compact_with_conditional_block.md | 1 + .../fix_an_incorrect_for_style_object_then.md | 1 + ...x_error_for_layout_redundant_line_break.md | 1 + ..._error_for_style_conditional_assignment.md | 1 - ...or_for_style_multiline_ternary_operator.md | 1 + ...lse_negative_for_style_redundant_return.md | 1 + ...ives_for_lint_redundant_safe_navigation.md | 1 + changelog/fix_false_positive_for_lint_void.md | 1 + ...lse_positives_for_style_inverse_methods.md | 1 + ...error_for_style_redundant_regexp_escape.md | 1 - ...umblock_regressions_in_omit_parentheses.md | 1 + changelog/new_add_editor_mode_option.md | 1 + .../new_extend_autocorrect_option_for_lsp.md | 1 + ...t_formatter_display_autocorrection_info.md | 1 + changelog/new_publish_lsp_enable_api.md | 1 + changelog/new_support_built_in_lsp.md | 1 - changelog/new_support_dot_config.md | 1 + codespell.txt | 1 + config/default.yml | 177 +- config/obsoletion.yml | 5 + docs/modules/ROOT/pages/about/history.adoc | 2 +- docs/modules/ROOT/pages/about/license.adoc | 2 +- docs/modules/ROOT/pages/compatibility.adoc | 7 +- docs/modules/ROOT/pages/configuration.adoc | 47 +- docs/modules/ROOT/pages/cops.adoc | 12 + docs/modules/ROOT/pages/cops_bundler.adoc | 106 +- docs/modules/ROOT/pages/cops_gemspec.adoc | 24 +- docs/modules/ROOT/pages/cops_layout.adoc | 91 +- docs/modules/ROOT/pages/cops_lint.adoc | 325 +++- docs/modules/ROOT/pages/cops_metrics.adoc | 15 +- docs/modules/ROOT/pages/cops_migration.adoc | 6 + docs/modules/ROOT/pages/cops_naming.adoc | 6 + docs/modules/ROOT/pages/cops_security.adoc | 8 +- docs/modules/ROOT/pages/cops_style.adoc | 730 ++++++- docs/modules/ROOT/pages/development.adoc | 11 +- docs/modules/ROOT/pages/extensions.adoc | 16 +- docs/modules/ROOT/pages/formatters.adoc | 18 +- docs/modules/ROOT/pages/installation.adoc | 2 +- .../pages/integration_with_other_tools.adoc | 33 +- .../modules/ROOT/pages/usage/basic_usage.adoc | 8 +- docs/modules/ROOT/pages/usage/lsp.adoc | 243 ++- lib/rubocop.rb | 13 + lib/rubocop/cli.rb | 9 +- .../cli/command/auto_generate_config.rb | 15 +- lib/rubocop/cli/command/lsp.rb | 4 +- lib/rubocop/config.rb | 2 - lib/rubocop/config_finder.rb | 18 +- lib/rubocop/config_loader.rb | 1 - lib/rubocop/config_loader_resolver.rb | 7 +- lib/rubocop/config_obsoletion.rb | 19 +- .../config_obsoletion/parameter_rule.rb | 10 +- lib/rubocop/config_validator.rb | 21 +- lib/rubocop/cop/autocorrect_logic.rb | 11 +- lib/rubocop/cop/base.rb | 15 +- lib/rubocop/cop/bundler/duplicated_gem.rb | 1 + lib/rubocop/cop/bundler/duplicated_group.rb | 127 ++ lib/rubocop/cop/bundler/gem_comment.rb | 6 +- lib/rubocop/cop/bundler/gem_version.rb | 4 +- lib/rubocop/cop/bundler/ordered_gems.rb | 10 +- .../cop/correctors/each_to_for_corrector.rb | 12 +- .../cop/correctors/for_to_each_corrector.rb | 18 +- .../lambda_literal_to_method_corrector.rb | 11 +- lib/rubocop/cop/exclude_limit.rb | 2 +- lib/rubocop/cop/gemspec/dependency_version.rb | 4 +- .../deprecated_attribute_assignment.rb | 4 +- .../cop/gemspec/ordered_dependencies.rb | 10 +- .../cop/generator/require_file_injector.rb | 2 +- lib/rubocop/cop/internal_affairs.rb | 2 + .../internal_affairs/example_description.rb | 69 +- .../location_line_equality_comparison.rb | 4 +- .../internal_affairs/method_name_end_with.rb | 14 +- .../cop/internal_affairs/method_name_equal.rb | 39 +- .../node_first_or_last_argument.rb | 53 + .../node_matcher_directive.rb | 10 +- .../redundant_expect_offense_arguments.rb | 34 + .../redundant_method_dispatch_node.rb | 13 +- .../useless_message_assertion.rb | 2 + lib/rubocop/cop/layout/argument_alignment.rb | 2 +- lib/rubocop/cop/layout/class_structure.rb | 7 + .../cop/layout/closing_heredoc_indentation.rb | 2 +- lib/rubocop/cop/layout/dot_position.rb | 6 +- .../layout/empty_line_after_guard_clause.rb | 51 +- .../cop/layout/empty_line_between_defs.rb | 31 +- ...ines_around_exception_handling_keywords.rb | 2 + lib/rubocop/cop/layout/end_alignment.rb | 18 +- lib/rubocop/cop/layout/extra_spacing.rb | 14 +- .../layout/first_array_element_indentation.rb | 29 +- .../cop/layout/first_parameter_indentation.rb | 2 +- .../heredoc_argument_closing_parenthesis.rb | 4 +- lib/rubocop/cop/layout/heredoc_indentation.rb | 5 +- lib/rubocop/cop/layout/indentation_style.rb | 2 +- lib/rubocop/cop/layout/indentation_width.rb | 6 +- .../cop/layout/leading_comment_space.rb | 2 +- .../layout/line_continuation_leading_space.rb | 26 +- .../cop/layout/line_continuation_spacing.rb | 2 +- ...ne_end_string_concatenation_indentation.rb | 2 + .../multiline_method_call_indentation.rb | 21 +- .../cop/layout/redundant_line_break.rb | 27 +- .../cop/layout/rescue_ensure_alignment.rb | 8 +- .../cop/layout/single_line_block_chain.rb | 5 + lib/rubocop/cop/layout/space_after_comma.rb | 10 +- lib/rubocop/cop/layout/space_after_not.rb | 2 +- .../space_around_method_call_operator.rb | 4 +- .../cop/layout/space_around_operators.rb | 74 +- lib/rubocop/cop/layout/space_inside_parens.rb | 2 +- .../cop/layout/space_inside_range_literal.rb | 2 +- .../cop/layout/trailing_empty_lines.rb | 5 + .../cop/lint/assignment_in_condition.rb | 8 +- ...binary_operator_with_identical_operands.rb | 4 +- .../lint/constant_overwritten_in_rescue.rb | 2 +- lib/rubocop/cop/lint/debugger.rb | 24 +- lib/rubocop/cop/lint/duplicate_hash_key.rb | 3 +- lib/rubocop/cop/lint/duplicate_methods.rb | 2 +- ...uplicate_regexp_character_class_element.rb | 65 +- lib/rubocop/cop/lint/empty_block.rb | 2 +- .../cop/lint/empty_conditional_body.rb | 2 +- lib/rubocop/cop/lint/erb_new_arguments.rb | 6 +- lib/rubocop/cop/lint/float_comparison.rb | 10 + .../cop/lint/hash_compare_by_identity.rb | 3 +- .../cop/lint/heredoc_method_call_position.rb | 2 +- .../cop/lint/it_without_arguments_in_block.rb | 56 + .../lint/literal_assignment_in_condition.rb | 85 + .../cop/lint/literal_in_interpolation.rb | 2 +- lib/rubocop/cop/lint/missing_super.rb | 36 +- lib/rubocop/cop/lint/mixed_case_range.rb | 111 ++ .../cop/lint/next_without_accumulator.rb | 27 +- .../cop/lint/non_atomic_file_operation.rb | 17 +- .../lint/non_deterministic_require_order.rb | 8 +- lib/rubocop/cop/lint/number_conversion.rb | 13 +- .../cop/lint/redundant_regexp_quantifiers.rb | 130 ++ .../cop/lint/redundant_require_statement.rb | 15 +- .../cop/lint/redundant_safe_navigation.rb | 80 +- lib/rubocop/cop/lint/redundant_with_index.rb | 4 +- lib/rubocop/cop/lint/redundant_with_object.rb | 4 +- lib/rubocop/cop/lint/rescue_type.rb | 4 +- lib/rubocop/cop/lint/safe_navigation_chain.rb | 22 +- lib/rubocop/cop/lint/script_permission.rb | 6 +- lib/rubocop/cop/lint/self_assignment.rb | 38 + lib/rubocop/cop/lint/shadowed_argument.rb | 1 + .../lint/shadowing_outer_local_variable.rb | 8 +- lib/rubocop/cop/lint/struct_new_override.rb | 24 +- lib/rubocop/cop/lint/suppressed_exception.rb | 4 +- lib/rubocop/cop/lint/symbol_conversion.rb | 11 +- lib/rubocop/cop/lint/syntax.rb | 9 +- lib/rubocop/cop/lint/to_enum_arguments.rb | 8 +- ...trailing_comma_in_attribute_declaration.rb | 2 +- .../cop/lint/unmodified_reduce_accumulator.rb | 4 +- .../cop/lint/useless_access_modifier.rb | 4 +- lib/rubocop/cop/lint/useless_assignment.rb | 50 +- lib/rubocop/cop/lint/useless_times.rb | 2 +- lib/rubocop/cop/lint/void.rb | 74 +- lib/rubocop/cop/metrics/abc_size.rb | 6 +- lib/rubocop/cop/metrics/block_length.rb | 2 +- lib/rubocop/cop/metrics/class_length.rb | 11 +- lib/rubocop/cop/metrics/method_length.rb | 2 +- .../metrics/utils/code_length_calculator.rb | 36 +- lib/rubocop/cop/migration/department_name.rb | 4 +- lib/rubocop/cop/mixin/check_line_breakable.rb | 2 +- lib/rubocop/cop/mixin/comments_help.rb | 30 +- .../cop/mixin/configurable_formatting.rb | 1 + lib/rubocop/cop/mixin/def_node.rb | 2 +- .../cop/mixin/end_keyword_alignment.rb | 2 +- .../cop/mixin/hash_shorthand_syntax.rb | 25 +- lib/rubocop/cop/mixin/heredoc.rb | 8 +- .../mixin/multiline_expression_indentation.rb | 5 +- lib/rubocop/cop/mixin/percent_literal.rb | 2 +- .../mixin/preceding_following_alignment.rb | 14 +- .../cop/mixin/space_before_punctuation.rb | 2 +- lib/rubocop/cop/mixin/string_help.rb | 6 +- lib/rubocop/cop/mixin/trailing_comma.rb | 2 +- lib/rubocop/cop/naming/block_forwarding.rb | 18 +- lib/rubocop/cop/naming/constant_name.rb | 3 +- lib/rubocop/cop/naming/file_name.rb | 2 +- .../cop/naming/heredoc_delimiter_naming.rb | 4 +- .../naming/memoized_instance_variable_name.rb | 8 +- lib/rubocop/cop/naming/predicate_name.rb | 4 +- lib/rubocop/cop/registry.rb | 2 +- lib/rubocop/cop/security/open.rb | 4 +- .../cop/style/access_modifier_declarations.rb | 4 +- lib/rubocop/cop/style/accessor_grouping.rb | 2 +- lib/rubocop/cop/style/alias.rb | 17 +- lib/rubocop/cop/style/arguments_forwarding.rb | 453 ++++- lib/rubocop/cop/style/array_first_last.rb | 64 + lib/rubocop/cop/style/array_intersect.rb | 18 +- .../cop/style/auto_resource_cleanup.rb | 35 +- .../cop/style/bisected_attr_accessor.rb | 4 +- lib/rubocop/cop/style/block_comments.rb | 2 +- lib/rubocop/cop/style/block_delimiters.rb | 9 +- lib/rubocop/cop/style/case_like_if.rb | 10 +- lib/rubocop/cop/style/class_check.rb | 1 + .../cop/style/class_equality_comparison.rb | 7 + lib/rubocop/cop/style/collection_compact.rb | 26 +- lib/rubocop/cop/style/collection_methods.rb | 2 + lib/rubocop/cop/style/combinable_loops.rb | 26 +- .../cop/style/concat_array_literals.rb | 3 +- .../cop/style/conditional_assignment.rb | 15 +- lib/rubocop/cop/style/date_time.rb | 9 +- .../style/document_dynamic_eval_definition.rb | 2 +- lib/rubocop/cop/style/each_for_simple_loop.rb | 14 +- lib/rubocop/cop/style/each_with_object.rb | 4 +- lib/rubocop/cop/style/empty_case_condition.rb | 7 +- lib/rubocop/cop/style/empty_literal.rb | 2 +- lib/rubocop/cop/style/eval_with_location.rb | 17 +- lib/rubocop/cop/style/exact_regexp_match.rb | 3 +- .../cop/style/explicit_block_argument.rb | 4 +- lib/rubocop/cop/style/for.rb | 2 +- lib/rubocop/cop/style/format_string.rb | 27 +- .../style/frozen_string_literal_comment.rb | 4 +- lib/rubocop/cop/style/guard_clause.rb | 26 + lib/rubocop/cop/style/hash_conversion.rb | 10 + lib/rubocop/cop/style/hash_each_methods.rb | 116 +- lib/rubocop/cop/style/hash_except.rb | 3 +- lib/rubocop/cop/style/hash_syntax.rb | 8 +- .../style/identical_conditional_branches.rb | 39 +- lib/rubocop/cop/style/if_with_semicolon.rb | 4 +- lib/rubocop/cop/style/inverse_methods.rb | 27 +- .../cop/style/invertible_unless_condition.rb | 43 +- lib/rubocop/cop/style/lambda.rb | 6 +- lib/rubocop/cop/style/lambda_call.rb | 5 + .../map_compact_with_conditional_block.rb | 18 +- lib/rubocop/cop/style/map_to_hash.rb | 24 +- .../method_call_with_args_parentheses.rb | 6 +- .../omit_parentheses.rb | 32 +- .../method_call_without_args_parentheses.rb | 20 + .../cop/style/method_def_parentheses.rb | 2 +- .../cop/style/missing_respond_to_missing.rb | 4 +- lib/rubocop/cop/style/mixin_grouping.rb | 2 +- .../cop/style/multiline_block_chain.rb | 2 +- .../cop/style/multiline_ternary_operator.rb | 10 +- .../cop/style/nested_ternary_operator.rb | 14 +- lib/rubocop/cop/style/next.rb | 2 +- .../cop/style/numeric_literal_prefix.rb | 2 +- lib/rubocop/cop/style/object_then.rb | 8 +- lib/rubocop/cop/style/open_struct_use.rb | 2 +- lib/rubocop/cop/style/operator_method_call.rb | 10 +- lib/rubocop/cop/style/parallel_assignment.rb | 8 +- .../cop/style/parentheses_around_condition.rb | 8 + .../cop/style/preferred_hash_methods.rb | 2 +- lib/rubocop/cop/style/raise_args.rb | 3 + lib/rubocop/cop/style/redundant_argument.rb | 14 +- lib/rubocop/cop/style/redundant_begin.rb | 12 +- .../cop/style/redundant_conditional.rb | 12 +- .../redundant_current_directory_in_path.rb | 38 + .../redundant_double_splat_hash_braces.rb | 98 +- lib/rubocop/cop/style/redundant_each.rb | 11 +- lib/rubocop/cop/style/redundant_exception.rb | 44 +- .../cop/style/redundant_fetch_block.rb | 6 +- .../cop/style/redundant_filter_chain.rb | 27 +- .../cop/style/redundant_line_continuation.rb | 34 +- .../cop/style/redundant_parentheses.rb | 95 +- .../cop/style/redundant_regexp_argument.rb | 100 + lib/rubocop/cop/style/redundant_return.rb | 17 +- lib/rubocop/cop/style/redundant_self.rb | 19 +- .../style/redundant_self_assignment_branch.rb | 9 +- lib/rubocop/cop/style/redundant_sort.rb | 19 +- lib/rubocop/cop/style/redundant_sort_by.rb | 4 +- .../cop/style/redundant_string_escape.rb | 4 +- lib/rubocop/cop/style/return_nil.rb | 8 +- ...turn_nil_in_predicate_method_definition.rb | 95 + lib/rubocop/cop/style/sample.rb | 7 +- lib/rubocop/cop/style/select_by_regexp.rb | 13 +- lib/rubocop/cop/style/self_assignment.rb | 2 +- lib/rubocop/cop/style/semicolon.rb | 11 +- lib/rubocop/cop/style/signal_exception.rb | 2 +- lib/rubocop/cop/style/single_argument_dig.rb | 10 +- .../cop/style/single_line_do_end_block.rb | 67 + lib/rubocop/cop/style/slicing_with_range.rb | 86 +- .../cop/style/sole_nested_conditional.rb | 4 +- lib/rubocop/cop/style/string_chars.rb | 1 + .../style/string_literals_in_interpolation.rb | 35 +- lib/rubocop/cop/style/strip.rb | 11 +- .../cop/style/super_with_args_parentheses.rb | 35 + lib/rubocop/cop/style/symbol_array.rb | 50 +- lib/rubocop/cop/style/symbol_proc.rb | 36 + lib/rubocop/cop/style/unpack_first.rb | 25 +- lib/rubocop/cop/style/yaml_file_read.rb | 66 + lib/rubocop/cop/style/yoda_condition.rb | 6 +- lib/rubocop/cop/style/yoda_expression.rb | 15 +- lib/rubocop/cop/util.rb | 2 +- lib/rubocop/cop/utils/regexp_ranges.rb | 113 ++ lib/rubocop/cop/variable_force/assignment.rb | 19 +- lib/rubocop/cops_documentation_generator.rb | 20 +- lib/rubocop/ext/regexp_node.rb | 13 +- lib/rubocop/ext/regexp_parser.rb | 5 +- lib/rubocop/file_finder.rb | 11 +- lib/rubocop/formatter.rb | 2 +- .../formatter/disabled_config_formatter.rb | 23 +- ...rmatter.rb => github_actions_formatter.rb} | 0 lib/rubocop/formatter/html_formatter.rb | 9 +- lib/rubocop/formatter/json_formatter.rb | 1 - lib/rubocop/formatter/junit_formatter.rb | 2 +- .../formatter/offense_count_formatter.rb | 14 +- lib/rubocop/lsp.rb | 29 + lib/rubocop/lsp/logger.rb | 2 +- lib/rubocop/lsp/routes.rb | 63 +- lib/rubocop/lsp/runtime.rb | 26 +- lib/rubocop/lsp/server.rb | 21 +- lib/rubocop/lsp/severity.rb | 2 +- lib/rubocop/magic_comment.rb | 22 +- lib/rubocop/options.rb | 19 +- lib/rubocop/result_cache.rb | 5 +- lib/rubocop/rspec/shared_contexts.rb | 23 +- lib/rubocop/rspec/support.rb | 1 + lib/rubocop/runner.rb | 10 +- lib/rubocop/server/cache.rb | 2 +- lib/rubocop/server/client_command/exec.rb | 3 +- lib/rubocop/server/server_command/exec.rb | 1 - lib/rubocop/string_interpreter.rb | 6 +- lib/rubocop/target_finder.rb | 10 +- lib/rubocop/target_ruby.rb | 154 +- lib/rubocop/version.rb | 2 +- logo/rubo-logo-horizontal-white.png | Bin 0 -> 25643 bytes logo/rubo-logo-square-white.png | Bin 0 -> 32954 bytes logo/rubo-logo-symbol-white.png | Bin 0 -> 28568 bytes relnotes/v0.33.0.md | 4 +- relnotes/v0.37.0.md | 2 +- relnotes/v0.45.0.md | 2 +- relnotes/v0.51.0.md | 2 +- relnotes/v0.53.0.md | 4 +- relnotes/v0.71.0.md | 2 +- relnotes/v0.90.0.md | 2 +- relnotes/v1.14.0.md | 2 +- relnotes/v1.22.0.md | 2 +- relnotes/v1.53.0.md | 36 + relnotes/v1.53.1.md | 8 + relnotes/v1.54.0.md | 27 + relnotes/v1.54.1.md | 9 + relnotes/v1.54.2.md | 10 + relnotes/v1.55.0.md | 32 + relnotes/v1.55.1.md | 11 + relnotes/v1.56.0.md | 28 + relnotes/v1.56.1.md | 19 + relnotes/v1.56.2.md | 12 + relnotes/v1.56.3.md | 20 + relnotes/v1.56.4.md | 17 + relnotes/v1.57.0.md | 34 + relnotes/v1.57.1.md | 11 + relnotes/v1.57.2.md | 20 + relnotes/v1.58.0.md | 47 + relnotes/v1.59.0.md | 49 + relnotes/v1.60.0.md | 43 + relnotes/v1.60.1.md | 12 + relnotes/v1.60.2.md | 13 + rubocop.gemspec | 8 +- spec/fixtures/html_formatter/expected.html | 12 +- .../html_formatter/project/app/models/book.rb | 1 + spec/fixtures/markdown_formatter/expected.md | 10 +- spec/isolated_environment_spec.rb | 9 +- spec/project_spec.rb | 18 +- spec/rubocop/cli/auto_gen_config_spec.rb | 218 ++- spec/rubocop/cli/autocorrect_spec.rb | 288 ++- .../rubocop/cli/disable_uncorrectable_spec.rb | 35 + spec/rubocop/cli/options_spec.rb | 157 +- spec/rubocop/cli_spec.rb | 119 +- spec/rubocop/config_loader_spec.rb | 84 +- spec/rubocop/config_obsoletion_spec.rb | 39 + .../cop/bundler/duplicated_gem_spec.rb | 14 +- .../cop/bundler/duplicated_group_spec.rb | 330 ++++ spec/rubocop/cop/bundler/gem_comment_spec.rb | 70 +- spec/rubocop/cop/cop_spec.rb | 20 +- spec/rubocop/cop/force_spec.rb | 2 +- .../example_description_spec.rb | 86 +- .../location_line_equality_comparison_spec.rb | 15 + .../method_name_end_with_spec.rb | 51 +- .../method_name_equal_spec.rb | 15 +- .../node_first_or_last_argument_spec.rb | 41 + ...redundant_expect_offense_arguments_spec.rb | 73 + .../redundant_method_dispatch_node_spec.rb | 22 + .../useless_message_assertion_spec.rb | 4 + .../cop/layout/class_structure_spec.rb | 10 +- .../cop/layout/comment_indentation_spec.rb | 9 +- .../empty_line_after_guard_clause_spec.rb | 36 + .../layout/empty_line_between_defs_spec.rb | 76 + .../empty_lines_around_begin_body_spec.rb | 5 +- ...around_exception_handling_keywords_spec.rb | 144 ++ spec/rubocop/cop/layout/end_alignment_spec.rb | 23 +- spec/rubocop/cop/layout/extra_spacing_spec.rb | 42 + .../layout/first_argument_indentation_spec.rb | 2 +- .../cop/layout/heredoc_indentation_spec.rb | 14 +- .../cop/layout/initial_indentation_spec.rb | 12 +- .../cop/layout/leading_comment_space_spec.rb | 14 + .../line_continuation_leading_space_spec.rb | 37 + ...d_string_concatenation_indentation_spec.rb | 4 + .../multiline_method_call_indentation_spec.rb | 184 ++ .../cop/layout/redundant_line_break_spec.rb | 69 + .../layout/rescue_ensure_alignment_spec.rb | 58 +- .../layout/single_line_block_chain_spec.rb | 12 + .../cop/layout/space_after_not_spec.rb | 12 + .../space_around_method_call_operator_spec.rb | 186 +- .../cop/layout/space_around_operators_spec.rb | 65 +- .../cop/layout/space_before_semicolon_spec.rb | 4 + ...pace_inside_array_literal_brackets_spec.rb | 2 +- ...space_inside_array_percent_literal_spec.rb | 2 +- ..._inside_percent_literal_delimiters_spec.rb | 2 +- .../space_inside_reference_brackets_spec.rb | 4 +- .../cop/layout/trailing_empty_lines_spec.rb | 16 + spec/rubocop/cop/lint/debugger_spec.rb | 70 + .../cop/lint/duplicate_hash_key_spec.rb | 9 + .../cop/lint/duplicate_match_pattern_spec.rb | 4 +- .../cop/lint/duplicate_methods_spec.rb | 28 +- ...ate_regexp_character_class_element_spec.rb | 26 + .../cop/lint/empty_conditional_body_spec.rb | 47 +- .../rubocop/cop/lint/float_comparison_spec.rb | 12 + .../cop/lint/hash_compare_by_identity_spec.rb | 7 + .../it_without_arguments_in_block_spec.rb | 139 ++ .../cop/lint/literal_as_condition_spec.rb | 2 +- .../literal_assignment_in_condition_spec.rb | 246 +++ .../cop/lint/literal_in_interpolation_spec.rb | 8 +- spec/rubocop/cop/lint/missing_super_spec.rb | 13 + .../rubocop/cop/lint/mixed_case_range_spec.rb | 230 +++ .../lint/mixed_regexp_capture_types_spec.rb | 6 + .../cop/lint/next_without_accumulator_spec.rb | 20 + .../no_return_in_begin_end_blocks_spec.rb | 4 +- .../lint/non_atomic_file_operation_spec.rb | 23 +- .../cop/lint/number_conversion_spec.rb | 33 + .../cop/lint/ordered_magic_comments_spec.rb | 9 + .../cop/lint/percent_string_array_spec.rb | 6 +- .../lint/redundant_regexp_quantifiers_spec.rb | 192 ++ .../lint/redundant_require_statement_spec.rb | 20 +- .../lint/redundant_safe_navigation_spec.rb | 184 +- .../cop/lint/redundant_with_index_spec.rb | 22 + .../cop/lint/redundant_with_object_spec.rb | 22 + spec/rubocop/cop/lint/rescue_type_spec.rb | 8 +- .../cop/lint/safe_navigation_chain_spec.rb | 81 + spec/rubocop/cop/lint/self_assignment_spec.rb | 189 ++ .../cop/lint/shadowed_argument_spec.rb | 10 + .../shadowing_outer_local_variable_spec.rb | 18 + .../cop/lint/suppressed_exception_spec.rb | 28 +- .../cop/lint/symbol_conversion_spec.rb | 35 +- spec/rubocop/cop/lint/syntax_spec.rb | 8 +- .../cop/lint/to_enum_arguments_spec.rb | 24 + .../unmodified_reduce_accumulator_spec.rb | 30 +- .../cop/lint/useless_assignment_spec.rb | 85 + spec/rubocop/cop/lint/void_spec.rb | 202 +- spec/rubocop/cop/metrics/class_length_spec.rb | 16 + .../rubocop/cop/metrics/method_length_spec.rb | 12 + .../rubocop/cop/metrics/module_length_spec.rb | 37 + .../utils/code_length_calculator_spec.rb | 20 + .../cop/mixin/enforce_superclass_spec.rb | 2 - .../cop/naming/block_forwarding_spec.rb | 47 + .../cop/naming/heredoc_delimiter_case_spec.rb | 8 + .../naming/heredoc_delimiter_naming_spec.rb | 9 + .../cop/naming/inclusive_language_spec.rb | 2 +- spec/rubocop/cop/registry_spec.rb | 8 +- spec/rubocop/cop/security/open_spec.rb | 11 +- .../access_modifier_declarations_spec.rb | 4 +- spec/rubocop/cop/style/alias_spec.rb | 19 +- .../cop/style/arguments_forwarding_spec.rb | 1681 ++++++++++++++++- .../cop/style/array_first_last_spec.rb | 61 + .../rubocop/cop/style/array_intersect_spec.rb | 18 + .../cop/style/auto_resource_cleanup_spec.rb | 21 + spec/rubocop/cop/style/case_like_if_spec.rb | 20 + spec/rubocop/cop/style/class_check_spec.rb | 28 +- .../style/class_equality_comparison_spec.rb | 6 + .../cop/style/collection_compact_spec.rb | 87 + .../cop/style/combinable_loops_spec.rb | 80 + .../cop/style/concat_array_literals_spec.rb | 11 + ...nal_assignment_assign_to_condition_spec.rb | 4 +- spec/rubocop/cop/style/date_time_spec.rb | 26 +- .../cop/style/documentation_method_spec.rb | 19 +- .../cop/style/each_for_simple_loop_spec.rb | 97 +- .../cop/style/each_with_object_spec.rb | 28 + .../cop/style/empty_case_condition_spec.rb | 159 +- .../cop/style/empty_lambda_parameter_spec.rb | 4 +- .../cop/style/exact_regexp_match_spec.rb | 11 + spec/rubocop/cop/style/format_string_spec.rb | 158 ++ .../cop/style/format_string_token_spec.rb | 4 +- spec/rubocop/cop/style/guard_clause_spec.rb | 126 ++ .../cop/style/hash_each_methods_spec.rb | 230 +++ spec/rubocop/cop/style/hash_except_spec.rb | 11 + spec/rubocop/cop/style/hash_syntax_spec.rb | 21 +- .../identical_conditional_branches_spec.rb | 185 +- .../cop/style/if_unless_modifier_spec.rb | 2 +- .../cop/style/if_with_semicolon_spec.rb | 32 +- .../rubocop/cop/style/inverse_methods_spec.rb | 96 + .../style/invertible_unless_condition_spec.rb | 37 +- spec/rubocop/cop/style/lambda_call_spec.rb | 12 + spec/rubocop/cop/style/lambda_spec.rb | 17 + ...map_compact_with_conditional_block_spec.rb | 29 +- spec/rubocop/cop/style/map_to_hash_spec.rb | 67 +- spec/rubocop/cop/style/map_to_set_spec.rb | 2 +- .../method_call_with_args_parentheses_spec.rb | 149 +- ...thod_call_without_args_parentheses_spec.rb | 45 + spec/rubocop/cop/style/mixin_grouping_spec.rb | 24 + .../cop/style/multiline_block_chain_spec.rb | 11 + .../style/multiline_ternary_operator_spec.rb | 52 +- .../cop/style/nested_ternary_operator_spec.rb | 23 + spec/rubocop/cop/style/next_spec.rb | 18 + spec/rubocop/cop/style/object_then_spec.rb | 11 + .../cop/style/operator_method_call_spec.rb | 22 + .../parentheses_around_condition_spec.rb | 94 + .../cop/style/redundant_argument_spec.rb | 36 +- .../rubocop/cop/style/redundant_begin_spec.rb | 2 +- .../cop/style/redundant_conditional_spec.rb | 30 + ...edundant_current_directory_in_path_spec.rb | 66 + ...redundant_double_splat_hash_braces_spec.rb | 164 +- spec/rubocop/cop/style/redundant_each_spec.rb | 54 +- .../cop/style/redundant_exception_spec.rb | 94 +- .../cop/style/redundant_fetch_block_spec.rb | 11 + .../cop/style/redundant_filter_chain_spec.rb | 63 + ...redundant_heredoc_delimiter_quotes_spec.rb | 6 + .../style/redundant_line_continuation_spec.rb | 144 ++ .../cop/style/redundant_parentheses_spec.rb | 372 +++- .../style/redundant_regexp_argument_spec.rb | 171 ++ .../cop/style/redundant_return_spec.rb | 110 +- .../redundant_self_assignment_branch_spec.rb | 59 + spec/rubocop/cop/style/redundant_self_spec.rb | 47 +- .../cop/style/redundant_sort_by_spec.rb | 22 + spec/rubocop/cop/style/redundant_sort_spec.rb | 132 ++ .../cop/style/redundant_string_escape_spec.rb | 6 + ...nil_in_predicate_method_definition_spec.rb | 325 ++++ spec/rubocop/cop/style/return_nil_spec.rb | 2 +- spec/rubocop/cop/style/sample_spec.rb | 13 + .../cop/style/select_by_regexp_spec.rb | 43 + .../rubocop/cop/style/self_assignment_spec.rb | 2 +- spec/rubocop/cop/style/semicolon_spec.rb | 11 + .../cop/style/single_argument_dig_spec.rb | 40 + .../style/single_line_do_end_block_spec.rb | 112 ++ .../cop/style/slicing_with_range_spec.rb | 94 +- .../cop/style/sole_nested_conditional_spec.rb | 17 + spec/rubocop/cop/style/string_chars_spec.rb | 11 + .../cop/style/string_concatenation_spec.rb | 24 +- .../string_literals_in_interpolation_spec.rb | 38 +- spec/rubocop/cop/style/strip_spec.rb | 48 +- .../style/super_with_args_parentheses_spec.rb | 32 + spec/rubocop/cop/style/symbol_array_spec.rb | 124 +- spec/rubocop/cop/style/symbol_proc_spec.rb | 8 +- .../cop/style/ternary_parentheses_spec.rb | 2 +- spec/rubocop/cop/style/unpack_first_spec.rb | 54 +- spec/rubocop/cop/style/word_array_spec.rb | 8 +- spec/rubocop/cop/style/yaml_file_read_spec.rb | 109 ++ spec/rubocop/cop/style/yoda_condition_spec.rb | 4 + spec/rubocop/cop/team_spec.rb | 10 +- spec/rubocop/cop/util_spec.rb | 4 +- spec/rubocop/cop/utils/format_string_spec.rb | 2 +- .../cop/variable_force/assignment_spec.rb | 20 +- spec/rubocop/cop/variable_force/scope_spec.rb | 38 +- .../formatter/clang_style_formatter_spec.rb | 46 +- .../disabled_config_formatter_spec.rb | 17 +- .../formatter/emacs_style_formatter_spec.rb | 16 +- .../formatter/file_list_formatter_spec.rb | 18 +- ...ec.rb => github_actions_formatter_spec.rb} | 2 +- spec/rubocop/formatter/html_formatter_spec.rb | 17 +- .../formatter/offense_count_formatter_spec.rb | 24 +- spec/rubocop/formatter/tap_formatter_spec.rb | 8 +- spec/rubocop/formatter/text_util_spec.rb | 14 +- spec/rubocop/lsp/server_spec.rb | 945 ++++++++- spec/rubocop/lsp/severity_spec.rb | 2 +- spec/rubocop/lsp_spec.rb | 21 + spec/rubocop/options_spec.rb | 23 +- spec/rubocop/rake_task_spec.rb | 8 +- spec/rubocop/result_cache_spec.rb | 8 +- spec/rubocop/server/cache_spec.rb | 9 + spec/rubocop/server/rubocop_server_spec.rb | 3 +- spec/rubocop/target_finder_spec.rb | 78 +- spec/rubocop/target_ruby_spec.rb | 614 +++--- spec/support/alignment_examples.rb | 2 +- spec/support/file_helper.rb | 11 + spec/support/lsp_helper.rb | 4 +- spec/tasks/changelog_spec.rb | 12 +- tasks/changelog.rake | 4 +- tasks/changelog.rb | 6 +- tasks/prof.rake | 4 +- 582 files changed, 19141 insertions(+), 2653 deletions(-) create mode 100644 changelog/change_error_message_on_incorrect_namespace.md create mode 100644 changelog/change_mark_style_raise_args_as_unsafe.md create mode 100644 changelog/change_source_order_for_target_ruby.md delete mode 100644 changelog/fix_a_false_positive_for_layout_redundant_line_break.md delete mode 100644 changelog/fix_an_error_for_lint_number_conversion.md create mode 100644 changelog/fix_an_error_for_style_case_like_if.md create mode 100644 changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md create mode 100644 changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md create mode 100644 changelog/fix_an_incorrect_for_style_object_then.md create mode 100644 changelog/fix_error_for_layout_redundant_line_break.md delete mode 100644 changelog/fix_error_for_style_conditional_assignment.md create mode 100644 changelog/fix_error_for_style_multiline_ternary_operator.md create mode 100644 changelog/fix_false_negative_for_style_redundant_return.md create mode 100644 changelog/fix_false_negatives_for_lint_redundant_safe_navigation.md create mode 100644 changelog/fix_false_positive_for_lint_void.md create mode 100644 changelog/fix_false_positives_for_style_inverse_methods.md delete mode 100644 changelog/fix_fix_an_error_for_style_redundant_regexp_escape.md create mode 100644 changelog/fix_numblock_regressions_in_omit_parentheses.md create mode 100644 changelog/new_add_editor_mode_option.md create mode 100644 changelog/new_extend_autocorrect_option_for_lsp.md create mode 100644 changelog/new_make_offense_count_formatter_display_autocorrection_info.md create mode 100644 changelog/new_publish_lsp_enable_api.md delete mode 100644 changelog/new_support_built_in_lsp.md create mode 100644 changelog/new_support_dot_config.md create mode 100644 lib/rubocop/cop/bundler/duplicated_group.rb create mode 100644 lib/rubocop/cop/internal_affairs/node_first_or_last_argument.rb create mode 100644 lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb create mode 100644 lib/rubocop/cop/lint/it_without_arguments_in_block.rb create mode 100644 lib/rubocop/cop/lint/literal_assignment_in_condition.rb create mode 100644 lib/rubocop/cop/lint/mixed_case_range.rb create mode 100644 lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb create mode 100644 lib/rubocop/cop/style/array_first_last.rb create mode 100644 lib/rubocop/cop/style/redundant_current_directory_in_path.rb create mode 100644 lib/rubocop/cop/style/redundant_regexp_argument.rb create mode 100644 lib/rubocop/cop/style/return_nil_in_predicate_method_definition.rb create mode 100644 lib/rubocop/cop/style/single_line_do_end_block.rb create mode 100644 lib/rubocop/cop/style/super_with_args_parentheses.rb create mode 100644 lib/rubocop/cop/style/yaml_file_read.rb create mode 100644 lib/rubocop/cop/utils/regexp_ranges.rb rename lib/rubocop/formatter/{git_hub_actions_formatter.rb => github_actions_formatter.rb} (100%) create mode 100644 lib/rubocop/lsp.rb create mode 100644 logo/rubo-logo-horizontal-white.png create mode 100644 logo/rubo-logo-square-white.png create mode 100644 logo/rubo-logo-symbol-white.png create mode 100644 relnotes/v1.53.0.md create mode 100644 relnotes/v1.53.1.md create mode 100644 relnotes/v1.54.0.md create mode 100644 relnotes/v1.54.1.md create mode 100644 relnotes/v1.54.2.md create mode 100644 relnotes/v1.55.0.md create mode 100644 relnotes/v1.55.1.md create mode 100644 relnotes/v1.56.0.md create mode 100644 relnotes/v1.56.1.md create mode 100644 relnotes/v1.56.2.md create mode 100644 relnotes/v1.56.3.md create mode 100644 relnotes/v1.56.4.md create mode 100644 relnotes/v1.57.0.md create mode 100644 relnotes/v1.57.1.md create mode 100644 relnotes/v1.57.2.md create mode 100644 relnotes/v1.58.0.md create mode 100644 relnotes/v1.59.0.md create mode 100644 relnotes/v1.60.0.md create mode 100644 relnotes/v1.60.1.md create mode 100644 relnotes/v1.60.2.md create mode 100644 spec/rubocop/cop/bundler/duplicated_group_spec.rb create mode 100644 spec/rubocop/cop/internal_affairs/node_first_or_last_argument_spec.rb create mode 100644 spec/rubocop/cop/internal_affairs/redundant_expect_offense_arguments_spec.rb create mode 100644 spec/rubocop/cop/lint/it_without_arguments_in_block_spec.rb create mode 100644 spec/rubocop/cop/lint/literal_assignment_in_condition_spec.rb create mode 100644 spec/rubocop/cop/lint/mixed_case_range_spec.rb create mode 100644 spec/rubocop/cop/lint/redundant_regexp_quantifiers_spec.rb create mode 100644 spec/rubocop/cop/style/array_first_last_spec.rb create mode 100644 spec/rubocop/cop/style/redundant_current_directory_in_path_spec.rb create mode 100644 spec/rubocop/cop/style/redundant_regexp_argument_spec.rb create mode 100644 spec/rubocop/cop/style/return_nil_in_predicate_method_definition_spec.rb create mode 100644 spec/rubocop/cop/style/single_line_do_end_block_spec.rb create mode 100644 spec/rubocop/cop/style/super_with_args_parentheses_spec.rb create mode 100644 spec/rubocop/cop/style/yaml_file_read_spec.rb rename spec/rubocop/formatter/{git_hub_actions_formatter_spec.rb => github_actions_formatter_spec.rb} (98%) create mode 100644 spec/rubocop/lsp_spec.rb diff --git a/.circleci/config.yml b/.circleci/config.yml index 8bff89a8fbf..2b501c24034 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -132,6 +132,29 @@ jobs: steps: *rubocop_steps + # Ruby 3.3 + ruby-3.3-spec: + docker: + - image: cimg/ruby:3.3 + environment: + <<: *common_env + steps: + *spec_steps + ruby-3.3-ascii_spec: + docker: + - image: cimg/ruby:3.3 + environment: + <<: *common_env + steps: + *ascii_spec_steps + ruby-3.3-rubocop: + docker: + - image: cimg/ruby:3.3 + environment: + <<: *common_env + steps: + *rubocop_steps + # ruby-head (nightly snapshot build) ruby-head-spec: docker: @@ -159,7 +182,7 @@ jobs: cc-setup: docker: # Specify the latest version to prevent "cimg/ruby:latest not found: manifest unknown: manifest unknown" error. - - image: cimg/ruby:3.2 + - image: cimg/ruby:3.3 environment: <<: *common_env steps: @@ -178,7 +201,7 @@ jobs: cc-upload-coverage: docker: # Specify the latest version to prevent "cimg/ruby:latest not found: manifest unknown: manifest unknown" error. - - image: cimg/ruby:3.2 + - image: cimg/ruby:3.3 environment: CC_TEST_REPORTER_ID: a11b66bfbb1acdf220d5cb317b2e945a986fd85adebe29a76d411ad6d74ec31f environment: @@ -189,14 +212,14 @@ jobs: - run: name: Upload coverage results to Code Climate command: | - ./tmp/cc-test-reporter sum-coverage tmp/codeclimate.*.json --parts 4 --output tmp/codeclimate.total.json + ./tmp/cc-test-reporter sum-coverage tmp/codeclimate.*.json --parts 5 --output tmp/codeclimate.total.json ./tmp/cc-test-reporter upload-coverage --input tmp/codeclimate.total.json # Miscellaneous tasks documentation-checks: docker: # Specify the latest version to prevent "cimg/ruby:latest not found: manifest unknown: manifest unknown" error. - - image: cimg/ruby:3.2 + - image: cimg/ruby:3.3 environment: <<: *common_env steps: @@ -232,6 +255,11 @@ workflows: - cc-setup - ruby-3.2-ascii_spec - ruby-3.2-rubocop + - ruby-3.3-spec: + requires: + - cc-setup + - ruby-3.3-ascii_spec + - ruby-3.3-rubocop - ruby-head-spec: requires: - cc-setup @@ -244,3 +272,4 @@ workflows: - ruby-3.0-spec - ruby-3.1-spec - ruby-3.2-spec + - ruby-3.3-spec diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index e8acecbdbed..21810f1c9c4 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -38,7 +38,7 @@ output by `rubocop -V`, include them as well. Here's an example: ``` $ [bundle exec] rubocop -V -1.52.1 (using Parser 2.7.2.0, rubocop-ast 1.1.1, running on ruby 2.7.2) [x86_64-linux] - - rubocop-performance 1.9.1 - - rubocop-rspec 2.0.0 +1.60.2 (using Parser 3.2.2.3, rubocop-ast 1.29.0, running on ruby 3.2.2) [x86_64-linux] + - rubocop-performance 1.18.0 + - rubocop-rspec 2.23.2 ``` diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index cccbb432bf3..f3f2f11d877 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -16,7 +16,7 @@ jobs: name: Yamllint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Yamllint uses: karancode/yamllint-github-action@v2.1.1 with: diff --git a/.github/workflows/rubocop.yml b/.github/workflows/rubocop.yml index 047037ea6b4..f21ae36e9a8 100644 --- a/.github/workflows/rubocop.yml +++ b/.github/workflows/rubocop.yml @@ -29,7 +29,7 @@ jobs: matrix: # [ubuntu, macos, windows] os: [windows] - ruby: ['2.7', '3.0', '3.1', '3.2', 'head'] + ruby: ['2.7', '3.0', '3.1', '3.2', '3.3', 'head'] include: - os: windows ruby: mingw @@ -45,7 +45,7 @@ jobs: echo "TMPDIR=$env:RUNNER_TEMP" >> $GITHUB_ENV git config --system core.autocrlf false - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: set up Ruby uses: ruby/setup-ruby@v1 with: @@ -63,7 +63,7 @@ jobs: runs-on: ubuntu-latest steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: set up Ruby uses: ruby/setup-ruby@v1 with: @@ -80,7 +80,7 @@ jobs: runs-on: ubuntu-latest name: RSpec 4 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Use latest RSpec 4 from `4-0-dev` branch run: | sed -e "/'rspec', '~> 3/d" -i Gemfile diff --git a/.github/workflows/spell_checking.yml b/.github/workflows/spell_checking.yml index 502e564ba01..cbfbc09d60b 100644 --- a/.github/workflows/spell_checking.yml +++ b/.github/workflows/spell_checking.yml @@ -14,7 +14,7 @@ jobs: name: Check spelling of all files with codespell runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: codespell-project/actions-codespell@v2 with: check_filenames: true @@ -24,7 +24,7 @@ jobs: name: Check spelling of all files in commit with misspell runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install run: wget -O - -q https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh | sh -s -- -b . - name: Misspell diff --git a/.rubocop.yml b/.rubocop.yml index e18416ca0e9..bdae9cc7ebd 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -139,14 +139,20 @@ RSpec: - expect_no_offenses - expect_offense -RSpec/FilePath: - Exclude: - - spec/rubocop/cop/internal_affairs/redundant_let_rubocop_config_new_spec.rb - - spec/rubocop/formatter/junit_formatter_spec.rb - RSpec/PredicateMatcher: EnforcedStyle: explicit +RSpec/FilePath: + Enabled: false + +RSpec/SpecFilePathFormat: + CustomTransform: + GitHubActionsFormatter: github_actions_formatter + JUnitFormatter: junit_formatter + RedundantLetRuboCopConfigNew: redundant_let_rubocop_config_new + Exclude: + - spec/rubocop/cop/mixin/enforce_superclass_spec.rb + RSpec/MessageSpies: EnforcedStyle: receive diff --git a/CHANGELOG.md b/CHANGELOG.md index 093ff95085a..ec46fadbc63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,431 @@ ## master (unreleased) +## 1.60.2 (2024-01-24) + +### Bug fixes + +* [#12627](https://github.com/rubocop/rubocop/issues/12627): Fix a false positive for `Layout/RedundantLineBreak` when using index access call chained on multiple lines with backslash. ([@koic][]) +* [#12626](https://github.com/rubocop/rubocop/pull/12626): Fix a false positive for `Style/ArgumentsForwarding` when naming a block argument `&`. ([@koic][]) +* [#12635](https://github.com/rubocop/rubocop/pull/12635): Fix a false positive for `Style/HashEachMethods` when both arguments are unused. ([@earlopain][]) +* [#12636](https://github.com/rubocop/rubocop/pull/12636): Fix an error for `Style/HashEachMethods` when a block with both parameters has no body. ([@earlopain][]) +* [#12638](https://github.com/rubocop/rubocop/issues/12638): Fix an `Errno::ENOENT` error when using server mode. ([@koic][]) +* [#12628](https://github.com/rubocop/rubocop/pull/12628): Fix a false positive for `Style/ArgumentsForwarding` when using block arg forwarding with positional arguments forwarding to within block. ([@koic][]) +* [#12642](https://github.com/rubocop/rubocop/pull/12642): Fix false positives for `Style/HashEachMethods` when using array converter method. ([@koic][]) +* [#12632](https://github.com/rubocop/rubocop/issues/12632): Fix an infinite loop error when `EnforcedStyle: explicit` of `Naming/BlockForwarding` with `Style/ArgumentsForwarding`. ([@koic][]) + +## 1.60.1 (2024-01-17) + +### Bug fixes + +* [#12625](https://github.com/rubocop/rubocop/pull/12625): Fix an error when server cache dir has read-only file system. ([@Strzesia][]) +* [#12618](https://github.com/rubocop/rubocop/issues/12618): Fix false positives for `Style/ArgumentsForwarding` when using block argument forwarding with other arguments. ([@koic][]) +* [#12614](https://github.com/rubocop/rubocop/issues/12614): Fix false positiveis for `Style/RedundantParentheses` when parentheses in control flow keyword with multiline style argument. ([@koic][]) + +### Changes + +* [#12617](https://github.com/rubocop/rubocop/issues/12617): Make `Style/CollectionCompact` aware of `grep_v` with nil. ([@koic][]) + +## 1.60.0 (2024-01-15) + +### Bug fixes + +* [#12603](https://github.com/rubocop/rubocop/issues/12603): Fix an infinite loop error for `Style/MultilineTernaryOperator` when using a method call as a ternary operator condition with a line break between receiver and method. ([@koic][]) +* [#12549](https://github.com/rubocop/rubocop/issues/12549): Fix a false positive for `Style/RedundantLineContinuation` when line continuations for multiline leading dot method chain with a blank line. ([@koic][]) +* [#12610](https://github.com/rubocop/rubocop/pull/12610): Accept parentheses in argument calls with blocks for `Style/MethodCallWithArgsParentheses` `omit_parentheses` style. ([@gsamokovarov][]) +* [#12580](https://github.com/rubocop/rubocop/pull/12580): Fix an infinite loop error for `Layout/EndAlignment` when misaligned in singleton class assignments with `EnforcedStyleAlignWith: variable`. ([@koic][]) +* [#12548](https://github.com/rubocop/rubocop/issues/12548): Fix an infinite loop error for `Layout/FirstArgumentIndentation` when specifying `EnforcedStyle: with_fixed_indentation` of `Layout/ArrayAlignment`. ([@koic][]) +* [#12236](https://github.com/rubocop/rubocop/issues/12236): Fix an error for `Lint/ShadowedArgument` when self assigning to a block argument in `for`. ([@koic][]) +* [#12569](https://github.com/rubocop/rubocop/issues/12569): Fix an error for `Style/IdenticalConditionalBranches` when using `if`...`else` with identical leading lines that assign to `self.foo`. ([@koic][]) +* [#12437](https://github.com/rubocop/rubocop/issues/12437): Fix an infinite loop error for `EnforcedStyle: omit_parentheses` of `Style/MethodCallWithArgsParentheses` with `Style/SuperWithArgsParentheses`. ([@koic][]) +* [#12558](https://github.com/rubocop/rubocop/issues/12558): Fix an incorrect autocorrect for `Style/MapToHash` when using `map.to_h` without receiver. ([@koic][]) +* [#12179](https://github.com/rubocop/rubocop/issues/12179): Let `--auto-gen-config` generate `Exclude` when `Max` is overridden. ([@jonas054][]) +* [#12574](https://github.com/rubocop/rubocop/issues/12574): Fix bug for unrecognized style in --auto-gen-config. ([@jonas054][]) +* [#12542](https://github.com/rubocop/rubocop/issues/12542): Fix false positive for `Lint/MixedRegexpCaptureTypes` when using look-ahead matcher. ([@marocchino][]) +* [#12607](https://github.com/rubocop/rubocop/pull/12607): Fix a false positive for `Style/RedundantParentheses` when regexp literal attempts to match against a parenthesized condition. ([@koic][]) +* [#12539](https://github.com/rubocop/rubocop/pull/12539): Fix false positives for `Lint/LiteralAssignmentInCondition` when a collection literal contains non-literal elements. ([@koic][]) +* [#12571](https://github.com/rubocop/rubocop/issues/12571): Fix false positives for `Naming/BlockForwarding` when using explicit block forwarding in block method. ([@koic][]) +* [#12537](https://github.com/rubocop/rubocop/issues/12537): Fix false positives for `Style/RedundantParentheses` when `AllowInMultilineConditions: true` of `Style/ParenthesesAroundCondition`. ([@koic][]) +* [#12578](https://github.com/rubocop/rubocop/pull/12578): Fix false positives for `Style/ArgumentsForwarding` when rest arguments forwarding to a method in block. ([@koic][]) +* [#12540](https://github.com/rubocop/rubocop/issues/12540): Fix false positives for `Style/HashEachMethods` when rest block argument of `Enumerable#each` method is used. ([@koic][]) +* [#12529](https://github.com/rubocop/rubocop/issues/12529): Fix false positives for `Style/ParenthesesAroundCondition`. ([@koic][]) +* [#12556](https://github.com/rubocop/rubocop/issues/12556): Fix false positives for `Style/RedundantParentheses` when parentheses are used around a semantic operator in expressions within assignments. ([@koic][]) +* [#12541](https://github.com/rubocop/rubocop/pull/12541): Fix false negative in `Style/ArgumentsForwarding` when a block is forwarded but other args aren't. ([@dvandersluis][]) +* [#12581](https://github.com/rubocop/rubocop/pull/12581): Handle trailing line continuation in `Layout/LineContinuationLeadingSpace`. ([@eugeneius][]) +* [#12601](https://github.com/rubocop/rubocop/issues/12601): Make `Style/EachForSimpleLoop` accept block with no parameters. ([@koic][]) + +### Changes + +* [#12535](https://github.com/rubocop/rubocop/pull/12535): Allow --autocorrect with --display-only-fail-level-offenses. ([@naveg][]) +* [#12572](https://github.com/rubocop/rubocop/pull/12572): Follow a Ruby 3.3 warning for `Security/Open` when `open` with a literal string starting with a pipe. ([@koic][]) +* [#12453](https://github.com/rubocop/rubocop/issues/12453): Make `Style/RedundantEach` aware of safe navigation operator. ([@koic][]) +* [#12233](https://github.com/rubocop/rubocop/issues/12233): Make `Style/SlicingWithRange` aware of redundant and beginless range. ([@koic][]) +* [#12388](https://github.com/rubocop/rubocop/pull/12388): Reject additional 'expanded' `EnforcedStyle` options when `--no-auto-gen-enforced-style` is given. ([@kpost][]) +* [#12593](https://github.com/rubocop/rubocop/pull/12593): Require Parser 3.3.0.2 or higher. ([@koic][]) + +## 1.59.0 (2023-12-11) + +### New features + +* [#12518](https://github.com/rubocop/rubocop/pull/12518): Add new `Lint/ItWithoutArgumentsInBlock` cop. ([@koic][]) + +### Bug fixes + +* [#12434](https://github.com/rubocop/rubocop/issues/12434): Fix a false positive for `Lint/LiteralAssignmentInCondition` when using interpolated string or xstring literals. ([@koic][]) +* [#12435](https://github.com/rubocop/rubocop/issues/12435): Fix a false positive for `Lint/SelfAssignment` when using attribute assignment with method call with arguments. ([@koic][]) +* [#12444](https://github.com/rubocop/rubocop/issues/12444): Fix false positive for `Style/HashEachMethods` when receiver literal is not a hash literal. ([@koic][]) +* [#12524](https://github.com/rubocop/rubocop/issues/12524): Fix a false positive for `Style/MethodCallWithArgsParentheses` when `EnforcedStyle: omit_parentheses` and parens in `when` clause is used to pass an argument. ([@koic][]) +* [#12505](https://github.com/rubocop/rubocop/pull/12505): Fix a false positive for `Style/RedundantParentheses` when using parenthesized `lambda` or `proc` with `do`...`end` block. ([@koic][]) +* [#12442](https://github.com/rubocop/rubocop/issues/12442): Fix an incorrect autocorrect for `Style/CombinableLoops` when looping over the same data as previous loop in `do`...`end` and `{`...`}` blocks. ([@koic][]) +* [#12432](https://github.com/rubocop/rubocop/pull/12432): Fix a false positive for `Lint/LiteralAssignmentInCondition` when using parallel assignment with splat operator in block of guard condition. ([@koic][]) +* [#12441](https://github.com/rubocop/rubocop/issues/12441): Fix false positives for `Style/HashEachMethods` when using destructed block arguments. ([@koic][]) +* [#12436](https://github.com/rubocop/rubocop/issues/12436): Fix false positives for `Style/RedundantParentheses` when a part of range is a parenthesized condition. ([@koic][]) +* [#12429](https://github.com/rubocop/rubocop/issues/12429): Fix incorrect autocorrect for `Style/MapToHash` when using dot method calls for `to_h`. ([@koic][]) +* [#12488](https://github.com/rubocop/rubocop/issues/12488): Make `Lint/HashCompareByIdentity` aware of safe navigation operator. ([@koic][]) +* [#12489](https://github.com/rubocop/rubocop/issues/12489): Make `Lint/NextWithoutAccumulator` aware of safe navigation operator. ([@koic][]) +* [#12490](https://github.com/rubocop/rubocop/issues/12490): Make `Lint/NumberConversion` aware of safe navigation operator. ([@koic][]) +* [#12491](https://github.com/rubocop/rubocop/issues/12491): Make `Lint/RedundantWithIndex` aware of safe navigation operator. ([@koic][]) +* [#12492](https://github.com/rubocop/rubocop/issues/12492): Make `Lint/RedundantWithObject` aware of safe navigation operator. ([@koic][]) +* [#12493](https://github.com/rubocop/rubocop/issues/12493): Make `Lint/UnmodifiedReduceAccumulator` aware of safe navigation operator. ([@koic][]) +* [#12473](https://github.com/rubocop/rubocop/issues/12473): Make `Style/ClassCheck` aware of safe navigation operator. ([@koic][]) +* [#12445](https://github.com/rubocop/rubocop/issues/12445): Make `Style/CollectionCompact` aware of safe navigation operator. ([@koic][]) +* [#12474](https://github.com/rubocop/rubocop/issues/12474): Make `Style/ConcatArrayLiterals` aware of safe navigation operator. ([@koic][]) +* [#12476](https://github.com/rubocop/rubocop/issues/12476): Make `Style/DateTime` aware of safe navigation operator. ([@koic][]) +* [#12479](https://github.com/rubocop/rubocop/issues/12479): Make `Style/EachWithObject` aware of safe navigation operator. ([@koic][]) +* [#12446](https://github.com/rubocop/rubocop/issues/12446): Make `Style/HashExcept` aware of safe navigation operator. ([@koic][]) +* [#12447](https://github.com/rubocop/rubocop/issues/12447): Make `Style/MapCompactWithConditionalBlock` aware of safe navigation operator. ([@koic][]) +* [#12484](https://github.com/rubocop/rubocop/issues/12484): Make `Style/Next` aware of safe navigation operator. ([@koic][]) +* [#12486](https://github.com/rubocop/rubocop/issues/12486): Make `Style/RedundantArgument` aware of safe navigation operator. ([@koic][]) +* [#12454](https://github.com/rubocop/rubocop/issues/12454): Make `Style/RedundantFetchBlock` aware of safe navigation operator. ([@koic][]) +* [#12495](https://github.com/rubocop/rubocop/issues/12495): Make `Layout/RedundantLineBreak` aware of safe navigation operator. ([@koic][]) +* [#12455](https://github.com/rubocop/rubocop/issues/12455): Make `Style/RedundantSortBy` aware of safe navigation operator. ([@koic][]) +* [#12456](https://github.com/rubocop/rubocop/issues/12456): Make `Style/RedundantSortBy` aware of safe navigation operator. ([@koic][]) +* [#12480](https://github.com/rubocop/rubocop/issues/12480): Make `Style/ExactRegexpMatch` aware of safe navigation operator. ([@koic][]) +* [#12457](https://github.com/rubocop/rubocop/issues/12457): Make `Style/Sample` aware of safe navigation operator. ([@koic][]) +* [#12458](https://github.com/rubocop/rubocop/issues/12458): Make `Style/SelectByRegexp` cops aware of safe navigation operator. ([@koic][]) +* [#12494](https://github.com/rubocop/rubocop/issues/12494): Make `Layout/SingleLineBlockChain` aware of safe navigation operator. ([@koic][]) +* [#12461](https://github.com/rubocop/rubocop/issues/12461): Make `Style/StringChars` aware of safe navigation operator. ([@koic][]) +* [#12468](https://github.com/rubocop/rubocop/issues/12468): Make `Style/Strip` aware of safe navigation operator. ([@koic][]) +* [#12469](https://github.com/rubocop/rubocop/issues/12469): Make `Style/UnpackFirst` aware of safe navigation operator. ([@koic][]) + +### Changes + +* [#12522](https://github.com/rubocop/rubocop/pull/12522): Make `Style/MethodCallWithoutArgsParentheses` allow the parenthesized `it` method in a block. ([@koic][]) +* [#12523](https://github.com/rubocop/rubocop/pull/12523): Make `Style/RedundantSelf` allow the `self.it` method in a block. ([@koic][]) + +## 1.58.0 (2023-12-01) + +### New features + +* [#12420](https://github.com/rubocop/rubocop/pull/12420): Add new `Lint/LiteralAssignmentInCondition` cop. ([@koic][]) +* [#12353](https://github.com/rubocop/rubocop/issues/12353): Add new `Style/SuperWithArgsParentheses` cop. ([@koic][]) +* [#12406](https://github.com/rubocop/rubocop/issues/12406): Add new `Style/ArrayFirstLast` cop. ([@fatkodima][]) + +### Bug fixes + +* [#12372](https://github.com/rubocop/rubocop/issues/12372): Fix a false negative for `Lint/Debugger` when used within method arguments a `begin`...`end` block. ([@koic][]) +* [#12378](https://github.com/rubocop/rubocop/pull/12378): Fix a false negative for `Style/Semicolon` when a semicolon at the beginning of a lambda block. ([@koic][]) +* [#12146](https://github.com/rubocop/rubocop/issues/12146): Fix a false positive for `Lint/FloatComparison` when comparing against zero. ([@earlopain][]) +* [#12404](https://github.com/rubocop/rubocop/issues/12404): Fix a false positive for `Layout/RescueEnsureAlignment` when aligned `rescue` in `do`-`end` numbered block in a method. ([@koic][]) +* [#12374](https://github.com/rubocop/rubocop/issues/12374): Fix a false positive for `Layout/SpaceBeforeSemicolon` when a space between an opening lambda brace and a semicolon. ([@koic][]) +* [#12326](https://github.com/rubocop/rubocop/pull/12326): Fix an error for `Style/RedundantDoubleSplatHashBraces` when method call for parenthesized no hash double double splat. ([@koic][]) +* [#12361](https://github.com/rubocop/rubocop/issues/12361): Fix an incorrect autocorrect for `Naming/BlockForwarding` and `Style/ArgumentsForwarding` when autocorrection conflicts for anonymous arguments. ([@koic][]) +* [#12324](https://github.com/rubocop/rubocop/issues/12324): Fix an error for `Layout/RescueEnsureAlignment` when using `rescue` in `do`...`end` block assigned to object attribute. ([@koic][]) +* [#12322](https://github.com/rubocop/rubocop/issues/12322): Fix an error for `Style/CombinableLoops` when looping over the same data for the third consecutive time or more. ([@koic][]) +* [#12366](https://github.com/rubocop/rubocop/pull/12366): Fix a false negative for `Layout/ExtraSpacing` when a file has exactly two comments. ([@eugeneius][]) +* [#12373](https://github.com/rubocop/rubocop/issues/12373): Fix a false negative for `Lint/SymbolConversion` when using string interpolation. ([@earlopain][]) +* [#12402](https://github.com/rubocop/rubocop/issues/12402): Fix false negatives for `Style/RedundantLineContinuation` when redundant line continuations for a block are used, especially without parentheses around first argument. ([@koic][]) +* [#12311](https://github.com/rubocop/rubocop/issues/12311): Fix false negatives for `Style/RedundantParentheses` when parentheses around logical operator keywords in method definition. ([@koic][]) +* [#12394](https://github.com/rubocop/rubocop/issues/12394): Fix false negatives for `Style/RedundantReturn` when `lambda` (`->`) ending with `return`. ([@koic][]) +* [#12377](https://github.com/rubocop/rubocop/issues/12377): Fix false positives for `Lint/Void` when a collection literal that includes non-literal elements in a method definition. ([@koic][]) +* [#12407](https://github.com/rubocop/rubocop/pull/12407): Fix an incorrect autocorrect for `Style/MapToHash` with `Layout/SingleLineBlockChain`. ([@koic][]) +* [#12409](https://github.com/rubocop/rubocop/issues/12409): Fix an incorrect autocorrect for `Lint/SafeNavigationChain` when ordinary method chain exists after safe navigation leading dot method call. ([@koic][]) +* [#12363](https://github.com/rubocop/rubocop/issues/12363): Fix incorrect rendering of HTML character entities in `HTMLFormatter` formatter. ([@koic][]) +* [#12424](https://github.com/rubocop/rubocop/issues/12424): Make `Style/HashEachMethods` aware of safe navigation operator. ([@koic][]) +* [#12413](https://github.com/rubocop/rubocop/issues/12413): Make `Style/InverseMethods` aware of safe navigation operator. ([@koic][]) +* [#12408](https://github.com/rubocop/rubocop/pull/12408): Make `Style/MapToHash` aware of safe navigation operator. ([@koic][]) + +### Changes + +* [#12328](https://github.com/rubocop/rubocop/issues/12328): Make `Style/AutoResourceCleanup` aware of `Tempfile.open`. ([@koic][]) +* [#12412](https://github.com/rubocop/rubocop/issues/12412): Enhance `Lint/RedundantSafeNavigation` to handle conversion methods with defaults. ([@fatkodima][]) +* [#12410](https://github.com/rubocop/rubocop/issues/12410): Enhance `Lint/SelfAssignment` to check attribute assignment and key assignment. ([@fatkodima][]) +* [#12370](https://github.com/rubocop/rubocop/issues/12370): Make `Style/HashEachMethods` aware of unused block value. ([@koic][]) +* [#12380](https://github.com/rubocop/rubocop/issues/12380): Make `Style/RedundantParentheses` aware of lambda or proc. ([@koic][]) +* [#12421](https://github.com/rubocop/rubocop/pull/12421): Make `Style/SelfAssignment` aware of `%`, `^`, `<<`, and `>>` operators. ([@koic][]) +* [#12305](https://github.com/rubocop/rubocop/pull/12305): Require `rubocop-ast` version 1.30 or greater. ([@sambostock][]) +* [#12337](https://github.com/rubocop/rubocop/issues/12337): Supports `EnforcedStyleForRationalLiterals` option for `Layout/SpaceAroundOperators`. ([@koic][]) +* [#12296](https://github.com/rubocop/rubocop/issues/12296): Support `RedundantRestArgumentNames`, `RedundantKeywordRestArgumentNames`, and `RedundantBlockArgumentNames` options for `Style/ArgumentsForwarding`. ([@koic][]) + +## 1.57.2 (2023-10-26) + +### Bug fixes + +* [#12274](https://github.com/rubocop/rubocop/issues/12274): Fix a false positive for `Lint/Void` when `each`'s receiver is an object of `Enumerator` to which `filter` has been applied. ([@koic][]) +* [#12291](https://github.com/rubocop/rubocop/issues/12291): Fix a false positive for `Metrics/ClassLength` when a class with a singleton class definition. ([@koic][]) +* [#12293](https://github.com/rubocop/rubocop/issues/12293): Fix a false positive for `Style/RedundantDoubleSplatHashBraces` when using double splat hash braces with `merge` and method chain. ([@koic][]) +* [#12298](https://github.com/rubocop/rubocop/issues/12298): Fix a false positive for `Style/RedundantParentheses` when using a parenthesized hash literal as the first argument in a method call without parentheses. ([@koic][]) +* [#12283](https://github.com/rubocop/rubocop/pull/12283): Fix an error for `Style/SingleLineDoEndBlock` when using single line `do`...`end` with no body. ([@koic][]) +* [#12312](https://github.com/rubocop/rubocop/issues/12312): Fix an incorrect autocorrect for `Style/HashSyntax` when braced hash key and value are the same and it is used in `if`...`else`. ([@koic][]) +* [#12307](https://github.com/rubocop/rubocop/issues/12307): Fix an infinite loop error for `Layout/EndAlignment` when `EnforcedStyleAlignWith: variable` and using a conditional statement in a method argument on the same line and `end` with method call is not aligned. ([@koic][]) +* [#11652](https://github.com/rubocop/rubocop/issues/11652): Make `--auto-gen-config` generate `inherit_from` correctly inside ERB `if`. ([@jonas054][]) +* [#12310](https://github.com/rubocop/rubocop/issues/12310): Drop `base64` gem from runtime dependency. ([@koic][]) +* [#12300](https://github.com/rubocop/rubocop/issues/12300): Fix an error for `Style/IdenticalConditionalBranches` when `if`...`else` with identical leading lines and using index assign. ([@koic][]) +* [#12286](https://github.com/rubocop/rubocop/issues/12286): Fix false positives for `Style/RedundantDoubleSplatHashBraces` when using double splat with a hash literal enclosed in parenthesized ternary operator. ([@koic][]) +* [#12279](https://github.com/rubocop/rubocop/issues/12279): Fix false positives for `Lint/EmptyConditionalBody` when missing 2nd `if` body with a comment. ([@koic][]) +* [#12275](https://github.com/rubocop/rubocop/issues/12275): Fix a false positive for `Style/RedundantDoubleSplatHashBraces` when using double splat within block argument containing a hash literal in an array literal. ([@koic][]) +* [#12284](https://github.com/rubocop/rubocop/issues/12284): Fix false positives for `Style/SingleArgumentDig` when using some anonymous argument syntax. ([@koic][]) +* [#12301](https://github.com/rubocop/rubocop/issues/12301): Make `Style/RedundantFilterChain` aware of safe navigation operator. ([@koic][]) + +## 1.57.1 (2023-10-13) + +### Bug fixes + +* [#12271](https://github.com/rubocop/rubocop/issues/12271): Fix a false positive for `Lint/RedundantSafeNavigation` when using snake case constant receiver. ([@koic][]) +* [#12265](https://github.com/rubocop/rubocop/issues/12265): Fix an error for `Layout/MultilineMethodCallIndentation` when usingarithmetic operation with block inside a grouped expression. ([@koic][]) +* [#12177](https://github.com/rubocop/rubocop/pull/12177): Fix an incorrect autocorrect for `Style/RedundantException`. ([@ydah][]) +* [#12261](https://github.com/rubocop/rubocop/issues/12261): Fix an infinite loop for `Layout/MultilineMethodCallIndentation` when multiline method chain with a block argument and method chain. ([@ydah][]) +* [#12263](https://github.com/rubocop/rubocop/issues/12263): Fix false positives for `Style/RedundantDoubleSplatHashBraces` when method call for no hash braced double splat receiver. ([@koic][]) +* [#12262](https://github.com/rubocop/rubocop/pull/12262): Fix an incorrect autocorrect for `Style/RedundantDoubleSplatHashBraces` when using double splat hash braces with `merge` method call twice. ([@koic][]) + +## 1.57.0 (2023-10-11) + +### New features + +* [#12227](https://github.com/rubocop/rubocop/pull/12227): Add new `Style/SingleLineDoEndBlock` cop. ([@koic][]) +* [#12246](https://github.com/rubocop/rubocop/pull/12246): Make `Lint/RedundantSafeNavigation` aware of constant receiver. ([@koic][]) +* [#12257](https://github.com/rubocop/rubocop/issues/12257): Make `Style/RedundantDoubleSplatHashBraces` aware of `merge` methods. ([@koic][]) + +### Bug fixes + +* [#12244](https://github.com/rubocop/rubocop/issues/12244): Fix a false negative for `Lint/Debugger` when using debugger method inside block. ([@koic][]) +* [#12231](https://github.com/rubocop/rubocop/issues/12231): Fix a false negative for `Metrics/ModuleLength` when defining a singleton class in a module. ([@koic][]) +* [#12249](https://github.com/rubocop/rubocop/issues/12249): Fix a false positive `Style/IdenticalConditionalBranches` when `if`..`else` with identical leading lines and assign to condition value. ([@koic][]) +* [#12253](https://github.com/rubocop/rubocop/pull/12253): Fix `Lint/LiteralInInterpolation` to accept an empty string literal interpolated in words literal. ([@knu][]) +* [#12198](https://github.com/rubocop/rubocop/issues/12198): Fix an error for flip-flop with beginless or endless ranges. ([@koic][]) +* [#12259](https://github.com/rubocop/rubocop/issues/12259): Fix an error for `Lint/MixedCaseRange` when using nested character class in regexp. ([@koic][]) +* [#12237](https://github.com/rubocop/rubocop/issues/12237): Fix an error for `Style/NestedTernaryOperator` when a ternary operator has a nested ternary operator within an `if`. ([@koic][]) +* [#12228](https://github.com/rubocop/rubocop/pull/12228): Fix false negatives for `Style/MultilineBlockChain` when using multiline block chain with safe navigation operator. ([@koic][]) +* [#12247](https://github.com/rubocop/rubocop/pull/12247): Fix false negatives for `Style/RedundantParentheses` when using logical or comparison expressions with redundant parentheses. ([@koic][]) +* [#12226](https://github.com/rubocop/rubocop/issues/12226): Fix false positives for `Layout/MultilineMethodCallIndentation` when aligning methods in multiline block chain. ([@koic][]) +* [#12076](https://github.com/rubocop/rubocop/issues/12076): Fixed an issue where the top-level cache folder was named differently during two consecutive rubocop runs. ([@K-S-A][]) + +### Changes + +* [#12235](https://github.com/rubocop/rubocop/pull/12235): Enable auto parallel inspection when config file is specified. ([@aboutNisblee][]) +* [#12234](https://github.com/rubocop/rubocop/pull/12234): Enhance `Style/FormatString`'s autocorrection when using known conversion methods whose return value is not an array. ([@koic][]) +* [#12128](https://github.com/rubocop/rubocop/issues/12128): Make `Style/GuardClause` aware of `define_method`. ([@koic][]) +* [#12126](https://github.com/rubocop/rubocop/pull/12126): Make `Style/RedundantFilterChain` aware of `select.present?` when `ActiveSupportExtensionsEnabled` config is `true`. ([@koic][]) +* [#12250](https://github.com/rubocop/rubocop/pull/12250): Mark `Lint/RedundantRequireStatement` as unsafe autocorrect. ([@koic][]) +* [#12097](https://github.com/rubocop/rubocop/issues/12097): Mark unsafe autocorrect for `Style/ClassEqualityComparison`. ([@koic][]) +* [#12210](https://github.com/rubocop/rubocop/issues/12210): Mark `Style/RedundantFilterChain` as unsafe autocorrect. ([@koic][]) + +## 1.56.4 (2023-09-28) + +### Bug fixes + +* [#12221](https://github.com/rubocop/rubocop/issues/12221): Fix a false positive for `Layout/EmptyLineAfterGuardClause` when using `return` before guard condition with heredoc. ([@koic][]) +* [#12213](https://github.com/rubocop/rubocop/issues/12213): Fix a false positive for `Lint/OrderedMagicComments` when comment text `# encoding: ISO-8859-1` is embedded within example code as source code comment. ([@koic][]) +* [#12205](https://github.com/rubocop/rubocop/issues/12205): Fix an error for `Style/OperatorMethodCall` when using `foo bar./ baz`. ([@koic][]) +* [#12208](https://github.com/rubocop/rubocop/issues/12208): Fix an incorrect autocorrect for the `--disable-uncorrectable` command line option when registering an offense is outside a percent array. ([@koic][]) +* [#12203](https://github.com/rubocop/rubocop/pull/12203): Fix an incorrect autocorrect for `Lint/SafeNavigationChain` when using safe navigation with comparison operator as an expression of logical operator or comparison operator's operand. ([@koic][]) +* [#12206](https://github.com/rubocop/rubocop/pull/12206): Fix an incorrect autocorrect for `Style/OperatorMethodCall` when using `foo./bar`. ([@koic][]) +* [#12202](https://github.com/rubocop/rubocop/pull/12202): Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results. ([@ydah][]) +* [#12199](https://github.com/rubocop/rubocop/issues/12199): Fix false negatives for `Layout/MultilineMethodCallIndentation` when using safe navigation operator. ([@koic][]) + +### Changes + +* [#12197](https://github.com/rubocop/rubocop/pull/12197): Make `Style/CollectionMethods` aware of `collect_concat`. ([@koic][]) + +## 1.56.3 (2023-09-11) + +### Bug fixes + +* [#12151](https://github.com/rubocop/rubocop/issues/12151): Make `Layout/EmptyLineAfterGuardClause` allow `:nocov:` directive after guard clause. ([@koic][]) +* [#12195](https://github.com/rubocop/rubocop/issues/12195): Fix a false negative for `Layout/SpaceAfterNot` when a newline is present after `!`. ([@ymap][]) +* [#12192](https://github.com/rubocop/rubocop/issues/12192): Fix a false positive for `Layout/RedundantLineBreak` when using quoted symbols with a single newline. ([@ymap][]) +* [#12190](https://github.com/rubocop/rubocop/issues/12190): Fix a false positive for `Layout/SpaceAroundOperators` when aligning operators vertically. ([@koic][]) +* [#12171](https://github.com/rubocop/rubocop/issues/12171): Fix a false positive for `Style/ArrayIntersect` when using block argument for `Enumerable#any?`. ([@koic][]) +* [#12172](https://github.com/rubocop/rubocop/issues/12172): Fix a false positive for `Style/EmptyCaseCondition` when using `return`, `break`, `next` or method call before empty case condition. ([@koic][]) +* [#12162](https://github.com/rubocop/rubocop/issues/12162): Fix an error for `Bundler/DuplicatedGroup` when there's a duplicate set of groups and the `group` value contains a splat. ([@koic][]) +* [#12182](https://github.com/rubocop/rubocop/issues/12182): Fix an error for `Lint/UselessAssignment` when variables are assigned using chained assignment and remain unreferenced. ([@koic][]) +* [#12181](https://github.com/rubocop/rubocop/issues/12181): Fix an incorrect autocorrect for `Lint/UselessAssignment` when variables are assigned with sequential assignment using the comma operator and unreferenced. ([@koic][]) +* [#12187](https://github.com/rubocop/rubocop/issues/12187): Fix an incorrect autocorrect for `Style/SoleNestedConditional` when comment is in an empty nested `if` body. ([@ymap][]) +* [#12183](https://github.com/rubocop/rubocop/pull/12183): Fix an incorrect autocorrect for `Style/MultilineTernaryOperator` when returning a multiline ternary operator expression with safe navigation method call. ([@koic][]) +* [#12168](https://github.com/rubocop/rubocop/issues/12168): Fix bug in `Style/ArgumentsForwarding` when there are repeated send nodes. ([@owst][]) +* [#12185](https://github.com/rubocop/rubocop/pull/12185): Set target version for `Layout/HeredocIndentation`. ([@tagliala][]) + +## 1.56.2 (2023-08-29) + +### Bug fixes + +* [#12138](https://github.com/rubocop/rubocop/issues/12138): Fix a false positive for `Layout/LineContinuationLeadingSpace` when a backslash is part of a multiline string literal. ([@ymap][]) +* [#12155](https://github.com/rubocop/rubocop/pull/12155): Fix false positive for `Layout/RedundantLineBreak` when using a modified singleton method definition. ([@koic][]) +* [#12143](https://github.com/rubocop/rubocop/issues/12143): Fix a false positive for `Lint/ToEnumArguments` when using anonymous keyword arguments forwarding. ([@koic][]) +* [#12148](https://github.com/rubocop/rubocop/pull/12148): Fix an incorrect autocorrect for `Lint/NonAtomicFileOperation` when using `FileUtils.remove_dir`, `FileUtils.remove_entry`, or `FileUtils.remove_entry_secure`. ([@koic][]) +* [#12141](https://github.com/rubocop/rubocop/issues/12141): Fix false positive for `Style/ArgumentsForwarding` when method def includes additional kwargs. ([@owst][]) +* [#12154](https://github.com/rubocop/rubocop/issues/12154): Fix incorrect `diagnosticProvider` value of LSP. ([@koic][]) + +## 1.56.1 (2023-08-21) + +### Bug fixes + +* [#12136](https://github.com/rubocop/rubocop/pull/12136): Fix a false negative for `Layout/LeadingCommentSpace` when using `#+` or `#-` as they are not RDoc comments. ([@koic][]) +* [#12113](https://github.com/rubocop/rubocop/issues/12113): Fix a false positive for `Bundler/DuplicatedGroup` when groups are duplicated but `source`, `git`, `platforms`, or `path` values are different. ([@koic][]) +* [#12134](https://github.com/rubocop/rubocop/issues/12134): Fix a false positive for `Style/MethodCallWithArgsParentheses` when parentheses are used in one-line `in` pattern matching. ([@koic][]) +* [#12111](https://github.com/rubocop/rubocop/issues/12111): Fix an error for `Bundler/DuplicatedGroup` group declaration has keyword option. ([@koic][]) +* [#12109](https://github.com/rubocop/rubocop/issues/12109): Fix an error for `Style/ArgumentsForwarding` cop when forwarding kwargs/block arg and an additional arg. ([@ydah][]) +* [#12117](https://github.com/rubocop/rubocop/issues/12117): Fix a false positive for `Style/ArgumentsForwarding` cop when not always forwarding block. ([@owst][]) +* [#12115](https://github.com/rubocop/rubocop/pull/12115): Fix an error for `Style/Lambda` when using numbered parameter with a multiline `->` call. ([@koic][]) +* [#12124](https://github.com/rubocop/rubocop/issues/12124): Fix false positives for `Style/RedundantParentheses` when parentheses in `super` or `yield` call with multiline style argument. ([@koic][]) +* [#12120](https://github.com/rubocop/rubocop/pull/12120): Fix false positives for `Style/SymbolArray` when `%i` array containing unescaped `[`, `]`, `(`, or `)`. ([@koic][]) +* [#12133](https://github.com/rubocop/rubocop/pull/12133): Fix `Style/RedundantSelfAssignmentBranch` to handle heredocs. ([@r7kamura][]) +* [#12105](https://github.com/rubocop/rubocop/issues/12105): Fix target ruby `Gem::Requirement` matcher and version parsing to support multiple version constraints. ([@ItsEcholot][]) + +## 1.56.0 (2023-08-09) + +### New features + +* [#12074](https://github.com/rubocop/rubocop/pull/12074): Add new `Bundler/DuplicatedGroup` cop. ([@OwlKing][]) +* [#12078](https://github.com/rubocop/rubocop/pull/12078): Make LSP server support `rubocop.formatAutocorrectsAll` execute command. ([@koic][]) + +### Bug fixes + +* [#12106](https://github.com/rubocop/rubocop/issues/12106): Fix a false negative for `Style/RedundantReturn` when returning value with guard clause and `return` is used. ([@koic][]) +* [#12095](https://github.com/rubocop/rubocop/pull/12095): Fix a false positive for `Style/Alias` when `EncforcedStyle: prefer_alias` and using `alias` with interpolated symbol argument. ([@koic][]) +* [#12098](https://github.com/rubocop/rubocop/pull/12098): Fix a false positive for `Style/ClassEqualityComparison` when comparing interpolated string class name for equality. ([@koic][]) +* [#12102](https://github.com/rubocop/rubocop/pull/12102): Fix an error for `Style/LambdaCall` when using nested lambda call `x.().()`. ([@koic][]) +* [#12099](https://github.com/rubocop/rubocop/pull/12099): Fix an incorrect autocorrect for `Style/Alias` when `EncforcedStyle: prefer_alias_method` and using `alias` with interpolated symbol argument. ([@koic][]) +* [#12085](https://github.com/rubocop/rubocop/issues/12085): Fix an error for `Lint/SuppressedException` when `AllowNil: true` is set and endless method definition is used. ([@koic][]) +* [#12087](https://github.com/rubocop/rubocop/issues/12087): Fix false positives for `Style/ArgumentsForwarding` with additional args/kwargs in def/send nodes. ([@owst][]) +* [#12071](https://github.com/rubocop/rubocop/issues/12071): Fix `Style/SymbolArray` false positives when using square brackets or interpolation in a symbol literal in a percent style array. ([@jasondoc3][]) +* [#12061](https://github.com/rubocop/rubocop/issues/12061): Support regex in StringLiteralsInInterpolation. ([@jonas054][]) +* [#12091](https://github.com/rubocop/rubocop/pull/12091): With `--fail-level A` ignore non-correctable offenses at :info severity. ([@naveg][]) + +### Changes + +* [#12094](https://github.com/rubocop/rubocop/pull/12094): Add `base64` gem to runtime dependency to suppress Ruby 3.3's warning. ([@koic][]) + +## 1.55.1 (2023-07-31) + +### Bug fixes + +* [#12068](https://github.com/rubocop/rubocop/pull/12068): Fix a false positive for `Style/ReturnNilInPredicateMethodDefinition` when the last method argument in method definition is `nil`. ([@koic][]) +* [#12082](https://github.com/rubocop/rubocop/issues/12082): Fix an error for `Lint/UselessAssignment` when a variable is assigned and unreferenced in `for` with multiple variables. ([@koic][]) +* [#12079](https://github.com/rubocop/rubocop/issues/12079): Fix an error for `Style/MixinGrouping` when mixin method has no arguments. ([@koic][]) +* [#11637](https://github.com/rubocop/rubocop/pull/11637): Correct Rubocop for `private_class_method` method documentation. ([@bigzed][]) +* [#12070](https://github.com/rubocop/rubocop/pull/12070): Fix false positive in `Style/ArgumentsForwarding` when receiver forwards args/kwargs. ([@owst][]) + +## 1.55.0 (2023-07-25) + +### New features + +* [#11794](https://github.com/rubocop/rubocop/pull/11794): Add support to `Style/ArgumentsForwarding` for anonymous arg/kwarg forwarding in Ruby 3.2. ([@owst][]) +* [#12044](https://github.com/rubocop/rubocop/issues/12044): Make LSP server support `layoutMode` option to run layout cops. ([@koic][]) +* [#12056](https://github.com/rubocop/rubocop/pull/12056): Make LSP server support `lintMode` option to run lint cops. ([@koic][]) +* [#12046](https://github.com/rubocop/rubocop/issues/12046): Make `ReturnNilInPredicateMethodDefinition` aware of `nil` at the end of predicate method definition. ([@koic][]) + +### Bug fixes + +* [#12055](https://github.com/rubocop/rubocop/pull/12055): Allow parentheses in single-line match patterns when using the `omit_parentheses` style of `Style/MethodCallWithArgsParentheses`. ([@gsamokovarov][]) +* [#12050](https://github.com/rubocop/rubocop/pull/12050): Fix a false positive for `Layout/RedundantLineBreak` when inspecting the `%` form string `%\n\n`. ([@koic][]) +* [#12063](https://github.com/rubocop/rubocop/pull/12063): Fix `Style/CombinableLoops` when one of the loops is empty. ([@fatkodima][]) +* [#12059](https://github.com/rubocop/rubocop/issues/12059): Fix a false negative for `Style/StringLiteralsInInterpolation` for symbols with interpolation. ([@fatkodima][]) +* [#11834](https://github.com/rubocop/rubocop/issues/11834): Fix false positive for when variable in inside conditional branch in nested node. ([@alexeyschepin][]) +* [#11802](https://github.com/rubocop/rubocop/issues/11802): Improve handling of `[]` and `()` with percent symbol arrays. ([@jasondoc3][]) +* [#12052](https://github.com/rubocop/rubocop/issues/12052): Fix "Subfolders can't include glob special characters". ([@meric426][], [@loveo][]) +* [#12062](https://github.com/rubocop/rubocop/pull/12062): Fix `LoadError` when loading RuboCop from a symlinked location on Windows. ([@p0deje][]) + +### Changes + +* [#12064](https://github.com/rubocop/rubocop/pull/12064): Make `Style/RedundantArgument` aware of `exit` and `exit!`. ([@koic][]) +* [#12015](https://github.com/rubocop/rubocop/issues/12015): Mark `Style/HashConversion` as unsafe autocorrection. ([@koic][]) + +## 1.54.2 (2023-07-13) + +### Bug fixes + +* [#12043](https://github.com/rubocop/rubocop/pull/12043): Fix a false negative for `Layout/ExtraSpacing` when some characters are vertically aligned. ([@koic][]) +* [#12040](https://github.com/rubocop/rubocop/pull/12040): Fix a false positive for `Layout/TrailingEmptyLines` to prevent the following incorrect autocorrection when inspecting the `%` form string `%\n\n`. ([@koic][]) +* [#1867](https://github.com/rubocop/rubocop/issues/1867): Fix an error when `AllCops:Exclude` is empty in .rubocop.yml. ([@koic][]) +* [#12034](https://github.com/rubocop/rubocop/issues/12034): Fix invalid byte sequence in UTF-8 error when using an invalid encoding string. ([@koic][]) +* [#12038](https://github.com/rubocop/rubocop/pull/12038): Output the "server restarting" message to stderr. ([@knu][]) + +## 1.54.1 (2023-07-04) + +### Bug fixes + +* [#12024](https://github.com/rubocop/rubocop/issues/12024): Fix a false positive for `Lint/RedundantRegexpQuantifiers` when interpolation is used in a regexp literal. ([@koic][]) +* [#12020](https://github.com/rubocop/rubocop/issues/12020): This PR fixes an infinite loop error for `Layout/SpaceAfterComma` with `Layout/SpaceBeforeSemicolon` when autocorrection conflicts. ([@koic][]) +* [#12014](https://github.com/rubocop/rubocop/pull/12014): Fix an error for `Lint/UselessAssignment` when part of a multiple assignment is enclosed in parentheses. ([@koic][]) +* [#12011](https://github.com/rubocop/rubocop/pull/12011): Fix an error for `Metrics/MethodLength` when using a heredoc in a block without block arguments. ([@koic][]) +* [#12010](https://github.com/rubocop/rubocop/pull/12010): Fix false negatives for `Style/RedundantRegexpArgument` when using safe navigation operator. ([@koic][]) + +## 1.54.0 (2023-07-01) + +### New features + +* [#12000](https://github.com/rubocop/rubocop/pull/12000): Support safe or unsafe autocorrect config for LSP. ([@koic][]) + +### Bug fixes + +* [#12005](https://github.com/rubocop/rubocop/issues/12005): Fix a false negative for `Lint/Debugger` when using debugger method inside lambda. ([@koic][]) +* [#11986](https://github.com/rubocop/rubocop/issues/11986): Fix a false positive for `Lint/MixedCaseRange` when the number of characters at the start or end of range is other than 1. ([@koic][]) +* [#11992](https://github.com/rubocop/rubocop/issues/11992): Fix an unexpected `NoMethodError` for built-in language server when an internal error occurs. ([@koic][]) +* [#11994](https://github.com/rubocop/rubocop/issues/11994): Fix an error for `Layout/LineEndStringConcatenationIndentation` when inspecting the `%` from string `%\n\n`. ([@koic][]) +* [#12007](https://github.com/rubocop/rubocop/issues/12007): Fix an error for `Layout/SpaceAroundOperators` when using unary operator with double colon. ([@koic][]) +* [#11996](https://github.com/rubocop/rubocop/issues/11996): Fix an error for `Style/IfWithSemicolon` when without branch bodies. ([@koic][]) +* [#12009](https://github.com/rubocop/rubocop/pull/12009): Fix an error for `Style/YodaCondition` when equality check method is used without the first argument. ([@koic][]) +* [#11998](https://github.com/rubocop/rubocop/issues/11998): Fix an error when inspecting blank heredoc delimiter. ([@koic][]) +* [#11989](https://github.com/rubocop/rubocop/issues/11989): Fix an incorrect autocorrect for `Style/RedundantRegexpArgument` when using unicode chars. ([@koic][]) +* [#12001](https://github.com/rubocop/rubocop/issues/12001): Fix code length calculator for method calls with heredoc. ([@fatkodima][]) +* [#12002](https://github.com/rubocop/rubocop/pull/12002): Fix `Lint/Void` cop for `__ENCODING__` constant. ([@fatkodima][]) + +### Changes + +* [#11983](https://github.com/rubocop/rubocop/pull/11983): Add Ridgepole files to default `Include` list. ([@ydah][]) +* [#11738](https://github.com/rubocop/rubocop/issues/11738): Enhances empty_line_between_defs to treat configured macros like defs. ([@catwomey][]) + +## 1.53.1 (2023-06-26) + +### Bug fixes + +* [#11974](https://github.com/rubocop/rubocop/issues/11974): Fix an error for `Style/RedundantCurrentDirectoryInPath` when using string interpolation in `require_relative`. ([@koic][]) +* [#11981](https://github.com/rubocop/rubocop/issues/11981): Fix an incorrect autocorrect for `Style/RedundantRegexpArgument` when using double quote and single quote characters. ([@koic][]) +* [#11836](https://github.com/rubocop/rubocop/issues/11836): Should not offense single-quoted symbol containing double quotes in `Lint/SymbolConversion` . ([@KessaPassa][]) + +## 1.53.0 (2023-06-23) + +### New features + +* [#11561](https://github.com/rubocop/rubocop/pull/11561): Add new `Lint/MixedCaseRange` cop. ([@rwstauner][]) +* [#11565](https://github.com/rubocop/rubocop/pull/11565): Add new `Lint/RedundantRegexpQuantifiers` cop. ([@jaynetics][]) +* [#11925](https://github.com/rubocop/rubocop/issues/11925): Add new `Style/RedundantCurrentDirectoryInPath` cop. ([@koic][]) +* [#11595](https://github.com/rubocop/rubocop/pull/11595): Add new `Style/RedundantRegexpArgument` cop. ([@koic][]) +* [#11967](https://github.com/rubocop/rubocop/pull/11967): Add new `Style/ReturnNilInPredicateMethodDefinition` cop. ([@koic][]) +* [#11745](https://github.com/rubocop/rubocop/pull/11745): Add new `Style/YAMLFileRead` cop. ([@koic][]) +* [#11926](https://github.com/rubocop/rubocop/pull/11926): Support built-in LSP server. ([@koic][]) + +### Bug fixes + +* [#11953](https://github.com/rubocop/rubocop/issues/11953): Fix a false negative for `Lint/DuplicateHashKey` when there is a duplicated constant key in the hash literal. ([@koic][]) +* [#11945](https://github.com/rubocop/rubocop/issues/11945): Fix a false negative for `Style/RedundantSelfAssignmentBranch` when using method chaining or arguments in ternary branch. ([@koic][]) +* [#11949](https://github.com/rubocop/rubocop/issues/11949): Fix a false positive for `Layout/RedundantLineBreak` when using a line broken string. ([@koic][]) +* [#11931](https://github.com/rubocop/rubocop/pull/11931): Fix a false positive for `Lint/RedundantRequireStatement` when using `PP.pp`. ([@koic][]) +* [#11946](https://github.com/rubocop/rubocop/pull/11946): Fix an error for `Lint/NumberConversion` when using multiple number conversion methods. ([@koic][]) +* [#11972](https://github.com/rubocop/rubocop/issues/11972): Fix an error for `Lint/Void` when `CheckForMethodsWithNoSideEffects: true` and using a method definition. ([@koic][]) +* [#11958](https://github.com/rubocop/rubocop/pull/11958): Fix error for `Style/IdenticalConditionalBranches` when using empty parentheses in the `if` branch. ([@koic][]) +* [#11962](https://github.com/rubocop/rubocop/issues/11962): Fix an error for `Style/RedundantStringEscape` when an escaped double quote precedes interpolation in a symbol literal. ([@koic][]) +* [#11947](https://github.com/rubocop/rubocop/issues/11947): Fix an error for `Style/ConditionalAssignment` with an assignment that uses `if` branch bodies, which include a block. ([@koic][]) +* [#11959](https://github.com/rubocop/rubocop/pull/11959): Fix false negatives for `Layout/EmptyLinesAroundExceptionHandlingKeywords` when using Ruby 2.5's `rescue` inside block and Ruby 2.7's numbered block. ([@koic][]) +* [#10902](https://github.com/rubocop/rubocop/issues/10902): Fix an error for `Style/RedundantRegexpEscape` string with invalid byte sequence in UTF-8. ([@ydah][]) +* [#11562](https://github.com/rubocop/rubocop/pull/11562): Fixed escaped octal handling and detection in `Lint/DuplicateRegexpCharacterClassElement`. ([@rwstauner][]) + +### Changes + +* [#11904](https://github.com/rubocop/rubocop/pull/11904): Mark `Layout/ClassStructure` as unsafe to autocorrect. ([@nevans][]) +* [#8506](https://github.com/rubocop/rubocop/issues/8506): Add `AllowedParentClasses` config to `Lint/MissingSuper`. ([@iMacTia][]) + ## 1.52.1 (2023-06-12) ### Bug fixes @@ -89,7 +514,7 @@ ### Changes * [#11859](https://github.com/rubocop/rubocop/pull/11859): Add rubocop-factory_bot to suggested extensions. ([@ydah][]) -* [#10791](https://github.com/rubocop/rubocop/pull/10791): **(Breaking)** Drop runtime support for Ruby 2.6 and JRuby 9.3 (CRuby 2.6 compatible). ([@koic][]) +* [#11791](https://github.com/rubocop/rubocop/pull/11791): **(Breaking)** Drop runtime support for Ruby 2.6 and JRuby 9.3 (CRuby 2.6 compatible). ([@koic][]) * [#11826](https://github.com/rubocop/rubocop/pull/11826): Exclude `**/*.jb` from `Lint/TopLevelReturnWithArgument`. ([@r7kamura][]) * [#11871](https://github.com/rubocop/rubocop/pull/11871): Mark `Style/DataInheritance` as unsafe autocorrect, `Style/OpenStructUse` as unsafe, and `Security/CompoundHash` as unsafe. ([@koic][]) @@ -1474,7 +1899,7 @@ * [#9748](https://github.com/rubocop/rubocop/pull/9748): Prevent infinite loops during symlink traversal. ([@Tonkpils][]) * [#9762](https://github.com/rubocop/rubocop/issues/9762): Update `VariableForce` to be able to handle `case-match` nodes. ([@dvandersluis][]) * [#9729](https://github.com/rubocop/rubocop/issues/9729): Fix an error for `Style/IfUnlessModifier` when variable assignment is used in the branch body of if modifier. ([@koic][]) -* [#9750](https://github.com/rubocop/rubocop/issues/9750): Fix an incorrect auto-correct for `Style/SoleNestedConditional` when when using nested `if` within `unless foo == bar`. ([@koic][]) +* [#9750](https://github.com/rubocop/rubocop/issues/9750): Fix an incorrect auto-correct for `Style/SoleNestedConditional` when using nested `if` within `unless foo == bar`. ([@koic][]) * [#9751](https://github.com/rubocop/rubocop/pull/9751): `Style/StringLiterals` autocorrects `'\\'` into `"\\"`. ([@etiennebarrie][]) * [#9732](https://github.com/rubocop/rubocop/pull/9732): Support deprecated Socket.gethostbyaddr and Socket.gethostbyname. ([@AndreiEres][]) * [#9713](https://github.com/rubocop/rubocop/issues/9713): Fix autocorrection for block local variables in `Lint/UnusedBlockArgument`. ([@tejasbubane][]) @@ -2204,7 +2629,7 @@ * [#8531](https://github.com/rubocop/rubocop/issues/8531): Add new `Lint/EmptyFile` cop. ([@fatkodima][]) * Add new `Lint/TrailingCommaInAttributeDeclaration` cop. ([@drenmi][]) * [#8578](https://github.com/rubocop/rubocop/pull/8578): Add `:restore_registry` context and `stub_cop_class` helper class. ([@marcandre][]) -* [#8579](https://github.com/rubocop/rubocop/pull/8579): Add `Cop.documentation_url`. ([@marcandre][]) +* [#8579](https://github.com/rubocop/rubocop/pull/8579): Add `Cop.documentation_url`. ([@marcandre][]) * [#8510](https://github.com/rubocop/rubocop/pull/8510): Add `RegexpNode#each_capture` and `parsed_tree`. ([@marcandre][]) * [#8365](https://github.com/rubocop/rubocop/pull/8365): Cops defining `on_send` can be optimized by defining the constant `RESTRICT_ON_SEND` with a list of acceptable method names. ([@marcandre][]) @@ -2884,7 +3309,7 @@ ### New features * [#7084](https://github.com/rubocop/rubocop/pull/7084): Permit to specify TargetRubyVersion 2.7. ([@koic][]) -* [#7092](https://github.com/rubocop/rubocop/pull/7092): Node patterns can now use `*`, `+` and `?` for repetitions. ([@marcandre][]) +* [#7092](https://github.com/rubocop/rubocop/pull/7092): Node patterns can now use `*`, `+` and `?` for repetitions. ([@marcandre][]) ### Bug fixes @@ -3629,7 +4054,7 @@ * [#3394](https://github.com/rubocop/rubocop/issues/3394): Add new `Style/TrailingCommaInArrayLiteral` cop. ([@garettarrowood][]) * [#3394](https://github.com/rubocop/rubocop/issues/3394): Add new `Style/TrailingCommaInHashLiteral` cop. ([@garettarrowood][]) * [#5319](https://github.com/rubocop/rubocop/pull/5319): Add new `Security/Open` cop. ([@mame][]) -* Add `EnforcedStyleForEmptyBrackets` configuration to `Layout/SpaceInsideReferenceBrackets`.([@garettarrowood][]) +* Add `EnforcedStyleForEmptyBrackets` configuration to `Layout/SpaceInsideReferenceBrackets`. ([@garettarrowood][]) * [#5050](https://github.com/rubocop/rubocop/issues/5050): Add auto-correction to `Style/ModuleFunction`. ([@garettarrowood][]) * [#5358](https://github.com/rubocop/rubocop/pull/5358): `--no-auto-gen-timestamp` CLI option suppresses the inclusion of the date and time it was generated in auto-generated config. ([@dominicsayers][]) * [#4274](https://github.com/rubocop/rubocop/issues/4274): Add new `Layout/EmptyComment` cop. ([@koic][]) @@ -3681,7 +4106,7 @@ * [#5582](https://github.com/rubocop/rubocop/issues/5582): Fix `end` alignment for variable assignment with line break after `=` in `Layout/EndAlignment`. ([@jonas054][]) * [#5602](https://github.com/rubocop/rubocop/pull/5602): Fix false positive for `Style/ColonMethodCall` when using Java package namespace. ([@koic][]) * [#5603](https://github.com/rubocop/rubocop/pull/5603): Fix falsey offense for `Style/RedundantSelf` with pseudo variables. ([@pocke][]) -* [#5547](https://github.com/rubocop/rubocop/issues/5547): Fix auto-correction of of `Layout/BlockEndNewline` when there is top level code outside of a class. ([@rrosenblum][]) +* [#5547](https://github.com/rubocop/rubocop/issues/5547): Fix auto-correction of `Layout/BlockEndNewline` when there is top level code outside of a class. ([@rrosenblum][]) * [#5599](https://github.com/rubocop/rubocop/issues/5599): Fix the suggestion being used by `Lint/NumberConversion` to use base 10 with Integer. ([@rrosenblum][]) * [#5534](https://github.com/rubocop/rubocop/issues/5534): Fix `Style/EachWithObject` auto-correction leaves an empty line. ([@flyerhzm][]) * Fix `Layout/EmptyLinesAroundAccessModifier` false-negative when next string after access modifier started with end. ([@unkmas][]) @@ -3849,7 +4274,7 @@ ### Bug fixes -* [#3312](https://github.com/rubocop/rubocop/issues/3312): Make `Rails/Date` Correct false positive on `#to_time` for strings ending in UTC-"Z".([@erikdstock][]) +* [#3312](https://github.com/rubocop/rubocop/issues/3312): Make `Rails/Date` Correct false positive on `#to_time` for strings ending in UTC-"Z". ([@erikdstock][]) * [#4741](https://github.com/rubocop/rubocop/issues/4741): Make `Style/SafeNavigation` correctly exclude methods called without dot. ([@drenmi][]) * [#4740](https://github.com/rubocop/rubocop/issues/4740): Make `Lint/RescueWithoutErrorClass` aware of modifier form `rescue`. ([@drenmi][]) * [#4745](https://github.com/rubocop/rubocop/issues/4745): Make `Style/SafeNavigation` ignore negated continuations. ([@drenmi][]) @@ -4294,7 +4719,7 @@ ### Changes -* [#3601](https://github.com/rubocop/rubocop/pull/3601): Change default args for `Style/SingleLineBlockParams`. This cop checks that `reduce` and `inject` use the variable names `a` and `e` for block arguments. These defaults are uncommunicative variable names and thus conflict with the ["Uncommunicative Variable Name" check in Reek](https://github.com/troessner/reek/blob/master/docs/Uncommunicative-Variable-Name.md). Default args changed to `acc` and `elem`.([@jessieay][]) +* [#3601](https://github.com/rubocop/rubocop/pull/3601): Change default args for `Style/SingleLineBlockParams`. This cop checks that `reduce` and `inject` use the variable names `a` and `e` for block arguments. These defaults are uncommunicative variable names and thus conflict with the ["Uncommunicative Variable Name" check in Reek](https://github.com/troessner/reek/blob/master/docs/Uncommunicative-Variable-Name.md). Default args changed to `acc` and `elem`. ([@jessieay][]) * [#3645](https://github.com/rubocop/rubocop/pull/3645): Fix bug with empty case when nodes in `Style/RedundantReturn`. ([@tiagocasanovapt][]) * [#3263](https://github.com/rubocop/rubocop/issues/3263): Fix auto-correct of if statements inside of unless else statements in `Style/ConditionalAssignment`. ([@rrosenblum][]) * Bump default Ruby version to 2.1. ([@drenmi][]) @@ -4775,7 +5200,7 @@ * [#2721](https://github.com/rubocop/rubocop/issues/2721): Do not register an offense for constants wrapped in parentheses passed to `rescue` in `Style/RedundantParentheses`. ([@rrosenblum][]) * [#2742](https://github.com/rubocop/rubocop/issues/2742): Fix `Style/TrailingCommaInArguments` & `Style/TrailingCommaInLiteral` for inline single element arrays. ([@annih][]) * [#2768](https://github.com/rubocop/rubocop/issues/2768): Allow parentheses after keyword `not` in `Style/MethodCallParentheses`. ([@lumeet][]) -* [#2758](https://github.com/rubocop/rubocop/issues/2758): Allow leading underscores in camel case variable names.([@mmcguinn][]) +* [#2758](https://github.com/rubocop/rubocop/issues/2758): Allow leading underscores in camel case variable names. ([@mmcguinn][]) ### Changes @@ -5141,7 +5566,7 @@ * [#1973](https://github.com/rubocop/rubocop/issues/1973): Do not register an offense in `Performance/Detect` when `select` is called on `Enumerable::Lazy`. ([@palkan][]) * [#2015](https://github.com/rubocop/rubocop/issues/2015): Fix bug occurring for auto-correction of a misaligned `end` in a file with only one method. ([@jonas054][]) * Allow string interpolation segments inside single quoted string literals when double quotes are preferred. ([@segiddins][]) -* [#2026](https://github.com/rubocop/rubocop/issues/2026): Allow `Time.current` when style is "acceptable".([@palkan][]) +* [#2026](https://github.com/rubocop/rubocop/issues/2026): Allow `Time.current` when style is "acceptable". ([@palkan][]) * [#2029](https://github.com/rubocop/rubocop/issues/2029): Fix bug where `Style/RedundantReturn` auto-corrects returning implicit hashes to invalid syntax. ([@rrosenblum][]) * [#2021](https://github.com/rubocop/rubocop/issues/2021): Fix bug in `Style/BlockDelimiters` when a `semantic` expression is used in an array or a range. ([@lumeet][]) * [#1992](https://github.com/rubocop/rubocop/issues/1992): Allow parentheses in assignment to a variable with the same name as the method's in `Style/MethodCallParentheses`. ([@lumeet][]) @@ -5149,7 +5574,7 @@ * [#2006](https://github.com/rubocop/rubocop/issues/2006): Fix crash in `Style/FirstParameterIndentation` in case of nested offenses. ([@unmanbearpig][]) * [#2059](https://github.com/rubocop/rubocop/issues/2059): Don't check for trivial accessors in modules. ([@bbatsov][]) * Add proper punctuation to the end of offense messages, where it is missing. ([@lumeet][]) -* [#2071](https://github.com/rubocop/rubocop/pull/2071): Keep line breaks in place on WordArray auto-correct.([@unmanbearpig][]) +* [#2071](https://github.com/rubocop/rubocop/pull/2071): Keep line breaks in place on WordArray auto-correct. ([@unmanbearpig][]) * [#2075](https://github.com/rubocop/rubocop/pull/2075): Properly correct `Style/PercentLiteralDelimiters` with escape characters in them. ([@rrosenblum][]) * [#2023](https://github.com/rubocop/rubocop/issues/2023): Avoid auto-correction corruption in `IndentationWidth`. ([@jonas054][]) * [#2080](https://github.com/rubocop/rubocop/issues/2080): Properly parse code in `Performance/Count` when calling `select..count` in a class that extends an enumerable. ([@rrosenblum][]) @@ -5943,7 +6368,7 @@ * [#661](https://github.com/rubocop/rubocop/issues/661): `EndAlignment` cop is now configurable for alignment with `keyword` (default) or `variable`. ([@jonas054][]) * Allow to overwrite the severity of a cop with the new `Severity` param. ([@codez][]) * New cop `FlipFlop` checks for flip flops. ([@agrimm][]) -* [#577](https://github.com/rubocop/rubocop/issues/577): Introduced `MethodDefParentheses` to allow for for requiring either parentheses or no parentheses in method definitions. Replaces `DefWithoutParentheses`. ([@skanev][]) +* [#577](https://github.com/rubocop/rubocop/issues/577): Introduced `MethodDefParentheses` to allow for requiring either parentheses or no parentheses in method definitions. Replaces `DefWithoutParentheses`. ([@skanev][]) * [#693](https://github.com/rubocop/rubocop/pull/693): Generation of parameter values (i.e., not only `Enabled: false`) in `rubocop-todo.yml` by the `--auto-gen-config` option is now supported for some cops. ([@jonas054][]) * New cop `AccessorMethodName` checks accessor method names for non-idiomatic names like `get_attribute` and `set_attribute`. ([@bbatsov][]) * New cop `PredicateName` checks the names of predicate methods for non-idiomatic names like `is_something`, `has_something`, etc. ([@bbatsov][]) @@ -6000,7 +6425,7 @@ ### Changes * [#557](https://github.com/rubocop/rubocop/pull/557): Configuration files for excluded files are no longer loaded. ([@jonas054][]) -* [#571](https://github.com/rubocop/rubocop/pull/571): The default rake task now runs RuboCop over itself! ([@nevir][]) +* [#571](https://github.com/rubocop/rubocop/pull/571): The default rake task now runs RuboCop over itself!. ([@nevir][]) * Encoding errors are reported as fatal offences rather than printed with red text. ([@jonas054][]) * `AccessControl` cop is now configurable with the `EnforcedStyle` option. ([@sds][]) * Split `AccessControl` cop to `AccessModifierIndentation` and `EmptyLinesAroundAccessModifier`. ([@bbatsov][]) @@ -7136,3 +7561,21 @@ [@Bhacaz]: https://github.com/Bhacaz [@naveg]: https://github.com/naveg [@lucthev]: https://github.com/lucthev +[@nevans]: https://github.com/nevans +[@iMacTia]: https://github.com/iMacTia +[@rwstauner]: https://github.com/rwstauner +[@catwomey]: https://github.com/catwomey +[@alexeyschepin]: https://github.com/alexeyschepin +[@meric426]: https://github.com/meric426 +[@loveo]: https://github.com/loveo +[@p0deje]: https://github.com/p0deje +[@bigzed]: https://github.com/bigzed +[@OwlKing]: https://github.com/OwlKing +[@ItsEcholot]: https://github.com/ItsEcholot +[@ymap]: https://github.com/ymap +[@aboutNisblee]: https://github.com/aboutNisblee +[@K-S-A]: https://github.com/K-S-A +[@earlopain]: https://github.com/earlopain +[@kpost]: https://github.com/kpost +[@marocchino]: https://github.com/marocchino +[@Strzesia]: https://github.com/Strzesia diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a0093d18b40..5bc61d3d677 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,9 +17,9 @@ do so. ```console $ rubocop -V -1.52.1 (using Parser 2.7.2.0, rubocop-ast 1.1.1, running on ruby 2.7.2) [x86_64-linux] - - rubocop-performance 1.9.1 - - rubocop-rspec 2.0.0 +1.60.2 (using Parser 3.2.2.3, rubocop-ast 1.29.0, running on ruby 3.2.2) [x86_64-linux] + - rubocop-performance 1.18.0 + - rubocop-rspec 2.23.2 ``` * Include any relevant code to the issue summary. diff --git a/Gemfile b/Gemfile index eec4f74810a..0458044019b 100644 --- a/Gemfile +++ b/Gemfile @@ -10,9 +10,9 @@ gem 'bundler', '>= 1.15.0', '< 3.0' gem 'memory_profiler', platform: :mri gem 'rake', '~> 13.0' gem 'rspec', '~> 3.7' -gem 'rubocop-performance', '~> 1.18.0' +gem 'rubocop-performance', '~> 1.20.0' gem 'rubocop-rake', '~> 0.6.0' -gem 'rubocop-rspec', '~> 2.22.0' +gem 'rubocop-rspec', '~> 2.26.0' # Workaround for cc-test-reporter with SimpleCov 0.18. # Stop upgrading SimpleCov until the following issue will be resolved. # https://github.com/codeclimate/test-reporter/issues/418 diff --git a/LICENSE.txt b/LICENSE.txt index 9f6b36e842e..aee79d6c114 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2012-23 Bozhidar Batsov +Copyright (c) 2012-24 Bozhidar Batsov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index e5937a8133b..7b11c9ee9a5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- RuboCop Logo + RuboCop Logo

---------- @@ -53,7 +53,7 @@ To prevent an unwanted RuboCop update you might want to use a conservative versi in your `Gemfile`: ```rb -gem 'rubocop', '~> 1.52', require: false +gem 'rubocop', '~> 1.60', require: false ``` See [our versioning policy](https://docs.rubocop.org/rubocop/versioning.html) for further details. @@ -67,6 +67,8 @@ $ cd my/cool/ruby/project $ rubocop ``` +You can also use this magic in your favorite editor with RuboCop's [built-in LSP server](https://docs.rubocop.org/rubocop/usage/lsp.html). + ## Documentation You can read a lot more about RuboCop in its [official docs](https://docs.rubocop.org). @@ -246,5 +248,5 @@ RuboCop's changelog is available [here](CHANGELOG.md). ## Copyright -Copyright (c) 2012-2023 Bozhidar Batsov. See [LICENSE.txt](LICENSE.txt) for +Copyright (c) 2012-2024 Bozhidar Batsov. See [LICENSE.txt](LICENSE.txt) for further details. diff --git a/Rakefile b/Rakefile index e4cd84ca400..2b16ab783e1 100644 --- a/Rakefile +++ b/Rakefile @@ -77,7 +77,7 @@ task documentation_syntax_check: :yard_for_generate_documentation do require 'parser/ruby25' require 'parser/ruby26' require 'parser/ruby27' - require 'parser/ruby32' + require 'parser/ruby33' ok = true YARD::Registry.load! @@ -108,7 +108,7 @@ task documentation_syntax_check: :yard_for_generate_documentation do elsif cop == RuboCop::Cop::Lint::NumberedParameterAssignment Parser::Ruby27.new(RuboCop::AST::Builder.new) else - Parser::Ruby32.new(RuboCop::AST::Builder.new) + Parser::Ruby33.new(RuboCop::AST::Builder.new) end parser.diagnostics.all_errors_are_fatal = true parser.parse(buffer) diff --git a/changelog/change_error_message_on_incorrect_namespace.md b/changelog/change_error_message_on_incorrect_namespace.md new file mode 100644 index 00000000000..2a319ba5b64 --- /dev/null +++ b/changelog/change_error_message_on_incorrect_namespace.md @@ -0,0 +1 @@ +* [#12641](https://github.com/rubocop/rubocop/pull/12641): Make error message clearer when the namespace is incorrect. ([@maruth-stripe][]) diff --git a/changelog/change_mark_style_raise_args_as_unsafe.md b/changelog/change_mark_style_raise_args_as_unsafe.md new file mode 100644 index 00000000000..15ae9d9de78 --- /dev/null +++ b/changelog/change_mark_style_raise_args_as_unsafe.md @@ -0,0 +1 @@ +* [#12637](https://github.com/rubocop/rubocop/pull/12637): Mark `Style/RaiseArgs` as unsafe. ([@r7kamura][]) diff --git a/changelog/change_source_order_for_target_ruby.md b/changelog/change_source_order_for_target_ruby.md new file mode 100644 index 00000000000..ece6a74860b --- /dev/null +++ b/changelog/change_source_order_for_target_ruby.md @@ -0,0 +1 @@ +* [#12645](https://github.com/rubocop/rubocop/pull/12645): Change source order for target ruby to check gemspec after RuboCop configuration. ([@jenshenny][]) diff --git a/changelog/fix_a_false_positive_for_layout_redundant_line_break.md b/changelog/fix_a_false_positive_for_layout_redundant_line_break.md deleted file mode 100644 index a27f3f96061..00000000000 --- a/changelog/fix_a_false_positive_for_layout_redundant_line_break.md +++ /dev/null @@ -1 +0,0 @@ -* [#11949](https://github.com/rubocop/rubocop/issues/11949): Fix a false positive for `Layout/RedundantLineBreak` when using a line broken string. ([@koic][]) diff --git a/changelog/fix_an_error_for_lint_number_conversion.md b/changelog/fix_an_error_for_lint_number_conversion.md deleted file mode 100644 index 4375c57a207..00000000000 --- a/changelog/fix_an_error_for_lint_number_conversion.md +++ /dev/null @@ -1 +0,0 @@ -* [#11946](https://github.com/rubocop/rubocop/pull/11946): Fix an error for `Lint/NumberConversion` when using multiple number conversion methods. ([@koic][]) diff --git a/changelog/fix_an_error_for_style_case_like_if.md b/changelog/fix_an_error_for_style_case_like_if.md new file mode 100644 index 00000000000..364a285ff35 --- /dev/null +++ b/changelog/fix_an_error_for_style_case_like_if.md @@ -0,0 +1 @@ +* [#12690](https://github.com/rubocop/rubocop/issues/12690): Fix an error for `Style/CaseLikeIf` when using `==` with literal and using ternary operator. ([@koic][]) diff --git a/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md b/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md new file mode 100644 index 00000000000..3020445682d --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_lint_empty_conditional_body.md @@ -0,0 +1 @@ +* [#12668](https://github.com/rubocop/rubocop/issues/12668): Fix an incorrect autocorrect for `Lint/EmptyConditionalBody` when missing `if` body with conditional `else` body. ([@koic][]) diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md b/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md new file mode 100644 index 00000000000..95221870820 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md @@ -0,0 +1 @@ +* [#12683](https://github.com/rubocop/rubocop/issues/12683): Fix an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` when using guard clause with `next` implicitly nil. ([@koic][]) diff --git a/changelog/fix_an_incorrect_for_style_object_then.md b/changelog/fix_an_incorrect_for_style_object_then.md new file mode 100644 index 00000000000..cdc931c9375 --- /dev/null +++ b/changelog/fix_an_incorrect_for_style_object_then.md @@ -0,0 +1 @@ +* [#12693](https://github.com/rubocop/rubocop/issues/12693): Fix an incorrect autocorrect for `Style/ObjectThen` when using `yield_self` without receiver. ([@koic][]) diff --git a/changelog/fix_error_for_layout_redundant_line_break.md b/changelog/fix_error_for_layout_redundant_line_break.md new file mode 100644 index 00000000000..d5bb6abc74a --- /dev/null +++ b/changelog/fix_error_for_layout_redundant_line_break.md @@ -0,0 +1 @@ +* [#12656](https://github.com/rubocop/rubocop/pull/12656): Fix an error for `Layout/RedundantLineBreak` when using index access call chained on multiline hash literal. ([@koic][]) diff --git a/changelog/fix_error_for_style_conditional_assignment.md b/changelog/fix_error_for_style_conditional_assignment.md deleted file mode 100644 index ae2cd2e5a5d..00000000000 --- a/changelog/fix_error_for_style_conditional_assignment.md +++ /dev/null @@ -1 +0,0 @@ -* [#11947](https://github.com/rubocop/rubocop/issues/11947): Fix an error for `Style/ConditionalAssignment` with an assignment that uses `if` branch bodies, which include a block. ([@koic][]) diff --git a/changelog/fix_error_for_style_multiline_ternary_operator.md b/changelog/fix_error_for_style_multiline_ternary_operator.md new file mode 100644 index 00000000000..d95c296446c --- /dev/null +++ b/changelog/fix_error_for_style_multiline_ternary_operator.md @@ -0,0 +1 @@ +* [#12691](https://github.com/rubocop/rubocop/issues/12691): Fix an error for `Style/MultilineTernaryOperator` when nesting multiline ternary operators. ([@koic][]) diff --git a/changelog/fix_false_negative_for_style_redundant_return.md b/changelog/fix_false_negative_for_style_redundant_return.md new file mode 100644 index 00000000000..a4d95077cc2 --- /dev/null +++ b/changelog/fix_false_negative_for_style_redundant_return.md @@ -0,0 +1 @@ +* [#12674](https://github.com/rubocop/rubocop/pull/12674): Fix false negatives for `Style/RedundantReturn` when using pattern matching. ([@koic][]) diff --git a/changelog/fix_false_negatives_for_lint_redundant_safe_navigation.md b/changelog/fix_false_negatives_for_lint_redundant_safe_navigation.md new file mode 100644 index 00000000000..08e4f28ab12 --- /dev/null +++ b/changelog/fix_false_negatives_for_lint_redundant_safe_navigation.md @@ -0,0 +1 @@ +* [#12673](https://github.com/rubocop/rubocop/pull/12673): Fix false negatives for `Lint/RedundantSafeNavigation` when using safe navigation operator for literal receiver. ([@koic][]) diff --git a/changelog/fix_false_positive_for_lint_void.md b/changelog/fix_false_positive_for_lint_void.md new file mode 100644 index 00000000000..02713b25af8 --- /dev/null +++ b/changelog/fix_false_positive_for_lint_void.md @@ -0,0 +1 @@ +* [#12687](https://github.com/rubocop/rubocop/issues/12687): Fix a false positive for `Lint/Void` when `each` block with conditional expressions that has multiple statements. ([@koic][]) diff --git a/changelog/fix_false_positives_for_style_inverse_methods.md b/changelog/fix_false_positives_for_style_inverse_methods.md new file mode 100644 index 00000000000..67968dc866a --- /dev/null +++ b/changelog/fix_false_positives_for_style_inverse_methods.md @@ -0,0 +1 @@ +* [#12649](https://github.com/rubocop/rubocop/issues/12649): Fix false positives for `Style/InverseMethods` when using relational comparison operator with safe navigation. ([@koic][]) diff --git a/changelog/fix_fix_an_error_for_style_redundant_regexp_escape.md b/changelog/fix_fix_an_error_for_style_redundant_regexp_escape.md deleted file mode 100644 index 24559f29988..00000000000 --- a/changelog/fix_fix_an_error_for_style_redundant_regexp_escape.md +++ /dev/null @@ -1 +0,0 @@ -* [#10902](https://github.com/rubocop/rubocop/issues/10902): Fix an error for `Style/RedundantRegexpEscape` string with invalid byte sequence in UTF-8. ([@ydah][]) diff --git a/changelog/fix_numblock_regressions_in_omit_parentheses.md b/changelog/fix_numblock_regressions_in_omit_parentheses.md new file mode 100644 index 00000000000..39394afe206 --- /dev/null +++ b/changelog/fix_numblock_regressions_in_omit_parentheses.md @@ -0,0 +1 @@ +* [#12648](https://github.com/rubocop/rubocop/pull/12648): Fix numblock regressions in `omit_parentheses` `Style/MethodCallWithArgsParentheses`. ([@gsamokovarov][]) diff --git a/changelog/new_add_editor_mode_option.md b/changelog/new_add_editor_mode_option.md new file mode 100644 index 00000000000..58be37dcf62 --- /dev/null +++ b/changelog/new_add_editor_mode_option.md @@ -0,0 +1 @@ +* [#12682](https://github.com/rubocop/rubocop/issues/12682): Add `--editor-mode` CLI option. ([@koic][]) diff --git a/changelog/new_extend_autocorrect_option_for_lsp.md b/changelog/new_extend_autocorrect_option_for_lsp.md new file mode 100644 index 00000000000..f6eea4363cd --- /dev/null +++ b/changelog/new_extend_autocorrect_option_for_lsp.md @@ -0,0 +1 @@ +* [#12657](https://github.com/rubocop/rubocop/pull/12657): Support `AutoCorrect: contextual` option for LSP. ([@koic][]) diff --git a/changelog/new_make_offense_count_formatter_display_autocorrection_info.md b/changelog/new_make_offense_count_formatter_display_autocorrection_info.md new file mode 100644 index 00000000000..47b1fb348d2 --- /dev/null +++ b/changelog/new_make_offense_count_formatter_display_autocorrection_info.md @@ -0,0 +1 @@ +* [#12273](https://github.com/rubocop/rubocop/issues/12273): Make `OffenseCountFormatter` display autocorrection information. ([@koic][]) diff --git a/changelog/new_publish_lsp_enable_api.md b/changelog/new_publish_lsp_enable_api.md new file mode 100644 index 00000000000..501c889979e --- /dev/null +++ b/changelog/new_publish_lsp_enable_api.md @@ -0,0 +1 @@ +* [#12679](https://github.com/rubocop/rubocop/pull/12679): Publish `RuboCop::LSP.enable` API to enable LSP mode. ([@koic][]) diff --git a/changelog/new_support_built_in_lsp.md b/changelog/new_support_built_in_lsp.md deleted file mode 100644 index a5b255a520e..00000000000 --- a/changelog/new_support_built_in_lsp.md +++ /dev/null @@ -1 +0,0 @@ -* [#11926](https://github.com/rubocop/rubocop/pull/11926): Support built-in LSP server. ([@koic][]) diff --git a/changelog/new_support_dot_config.md b/changelog/new_support_dot_config.md new file mode 100644 index 00000000000..dfdc1e896a8 --- /dev/null +++ b/changelog/new_support_dot_config.md @@ -0,0 +1 @@ +* [#12699](https://github.com/rubocop/rubocop/issues/12699): Support searching for `.rubocop.yml` and `rubocop/config.yml` in compliance with dot-config. ([@koic][]) diff --git a/codespell.txt b/codespell.txt index d8d7bcd5bd7..70c149a4970 100644 --- a/codespell.txt +++ b/codespell.txt @@ -4,6 +4,7 @@ enviromnent filetest fo irregardless +mange ofo thi upto diff --git a/config/default.yml b/config/default.yml index 58e67c0ab3b..29c7d57ee7e 100644 --- a/config/default.yml +++ b/config/default.yml @@ -30,6 +30,7 @@ AllCops: - '**/*.rbx' - '**/*.ru' - '**/*.ruby' + - '**/*.schema' - '**/*.spec' - '**/*.thor' - '**/*.watchr' @@ -55,6 +56,7 @@ AllCops: - '**/Puppetfile' - '**/Rakefile' - '**/rakefile' + - '**/Schemafile' - '**/Snapfile' - '**/Steepfile' - '**/Thorfile' @@ -171,6 +173,16 @@ Bundler/DuplicatedGem: - '**/Gemfile' - '**/gems.rb' +Bundler/DuplicatedGroup: + Description: 'Checks for duplicate group entries in Gemfile.' + Enabled: true + Severity: warning + VersionAdded: '1.56' + Include: + - '**/*.gemfile' + - '**/Gemfile' + - '**/gems.rb' + Bundler/GemComment: Description: 'Add a comment describing each gem.' Enabled: false @@ -467,7 +479,9 @@ Layout/ClassStructure: Description: 'Enforces a configured order of definitions within a class body.' StyleGuide: '#consistent-classes' Enabled: false + SafeAutoCorrect: false VersionAdded: '0.52' + VersionChanged: '1.53' Categories: module_inclusion: - include @@ -542,7 +556,9 @@ Layout/ElseAlignment: Layout/EmptyComment: Description: 'Checks empty comment.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.53' + VersionChanged: '<>' AllowBorderComment: true AllowMarginComment: true @@ -575,6 +591,8 @@ Layout/EmptyLineBetweenDefs: EmptyLineBetweenMethodDefs: true EmptyLineBetweenClassDefs: true EmptyLineBetweenModuleDefs: true + # `DefLikeMacros` takes the name of any macro that you want to treat like a def. + DefLikeMacros: [] # `AllowAdjacentOneLineDefs` means that single line method definitions don't # need an empty line between them. `true` by default. AllowAdjacentOneLineDefs: true @@ -1335,6 +1353,10 @@ Layout/SpaceAroundOperators: SupportedStylesForExponentOperator: - space - no_space + EnforcedStyleForRationalLiterals: no_space + SupportedStylesForRationalLiterals: + - space + - no_space Layout/SpaceBeforeBlockBraces: Description: >- @@ -1530,7 +1552,6 @@ Lint/AmbiguousBlockAssociation: Description: >- Checks for ambiguous block association with method when param passed without parentheses. - StyleGuide: '#syntax' Enabled: true VersionAdded: '0.48' VersionChanged: '1.13' @@ -1806,16 +1827,18 @@ Lint/EmptyClass: Lint/EmptyConditionalBody: Description: 'Checks for the presence of `if`, `elsif` and `unless` branches without a body.' Enabled: true + AutoCorrect: contextual SafeAutoCorrect: false AllowComments: true VersionAdded: '0.89' - VersionChanged: '1.34' + VersionChanged: '<>' Lint/EmptyEnsure: Description: 'Checks for empty ensure block.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.10' - VersionChanged: '0.48' + VersionChanged: '<>' Lint/EmptyExpression: Description: 'Checks for empty expressions.' @@ -1837,8 +1860,9 @@ Lint/EmptyInPattern: Lint/EmptyInterpolation: Description: 'Checks for empty string interpolation.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.20' - VersionChanged: '0.45' + VersionChanged: '<>' Lint/EmptyWhen: Description: 'Checks for `when` branches with empty bodies.' @@ -1944,6 +1968,12 @@ Lint/InterpolationCheck: VersionAdded: '0.50' VersionChanged: '1.40' +Lint/ItWithoutArgumentsInBlock: + Description: 'Checks uses of `it` calls without arguments in block.' + Reference: 'https://bugs.ruby-lang.org/issues/18980' + Enabled: pending + VersionAdded: '1.59' + Lint/LambdaWithoutLiteralBlock: Description: 'Checks uses of lambda without a literal block.' Enabled: pending @@ -1954,6 +1984,11 @@ Lint/LiteralAsCondition: Enabled: true VersionAdded: '0.51' +Lint/LiteralAssignmentInCondition: + Description: 'Checks for literal assignments in the conditions.' + Enabled: pending + VersionAdded: '1.58' + Lint/LiteralInInterpolation: Description: 'Checks for literals used in interpolation.' Enabled: true @@ -1988,9 +2023,16 @@ Lint/MissingSuper: Checks for the presence of constructors and lifecycle callbacks without calls to `super`. Enabled: true + AllowedParentClasses: [] VersionAdded: '0.89' VersionChanged: '1.4' +Lint/MixedCaseRange: + Description: 'Checks for mixed-case character ranges since they include likely unintended characters.' + Enabled: pending + SafeAutoCorrect: false + VersionAdded: '1.53' + Lint/MixedRegexpCaptureTypes: Description: 'Do not mix named captures and numbered captures in a Regexp literal.' Enabled: true @@ -2140,10 +2182,17 @@ Lint/RedundantDirGlobSort: VersionChanged: '1.26' SafeAutoCorrect: false +Lint/RedundantRegexpQuantifiers: + Description: 'Checks for redundant quantifiers in Regexps.' + Enabled: pending + VersionAdded: '1.53' + Lint/RedundantRequireStatement: Description: 'Checks for unnecessary `require` statement.' Enabled: true + SafeAutoCorrect: false VersionAdded: '0.76' + VersionChanged: '1.57' Lint/RedundantSafeNavigation: Description: 'Checks for redundant safe navigation calls.' @@ -2351,7 +2400,9 @@ Lint/TopLevelReturnWithArgument: Lint/TrailingCommaInAttributeDeclaration: Description: 'Checks for trailing commas in attribute declarations.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.90' + VersionChanged: '<>' Lint/TripleQuotes: Description: 'Checks for useless triple quote constructs.' @@ -2411,8 +2462,9 @@ Lint/UnusedBlockArgument: Description: 'Checks for unused block arguments.' StyleGuide: '#underscore-unused-vars' Enabled: true + AutoCorrect: contextual VersionAdded: '0.21' - VersionChanged: '0.22' + VersionChanged: '<>' IgnoreEmptyBlocks: true AllowUnusedKeywordArguments: false @@ -2420,8 +2472,9 @@ Lint/UnusedMethodArgument: Description: 'Checks for unused method arguments.' StyleGuide: '#underscore-unused-vars' Enabled: true + AutoCorrect: contextual VersionAdded: '0.21' - VersionChanged: '0.81' + VersionChanged: '<>' AllowUnusedKeywordArguments: false IgnoreEmptyMethods: true IgnoreNotImplementedMethods: true @@ -2445,8 +2498,9 @@ Lint/UriRegexp: Lint/UselessAccessModifier: Description: 'Checks for useless access modifiers.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.20' - VersionChanged: '0.83' + VersionChanged: '<>' ContextCreatingMethods: [] MethodCreatingMethods: [] @@ -2454,8 +2508,9 @@ Lint/UselessAssignment: Description: 'Checks for useless assignment to a local variable.' StyleGuide: '#underscore-unused-vars' Enabled: true + AutoCorrect: contextual VersionAdded: '0.11' - VersionChanged: '1.51' + VersionChanged: '<>' SafeAutoCorrect: false Lint/UselessElseWithoutRescue: @@ -2467,8 +2522,9 @@ Lint/UselessElseWithoutRescue: Lint/UselessMethodDefinition: Description: 'Checks for useless method definitions.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.90' - VersionChanged: '0.91' + VersionChanged: '<>' Safe: false Lint/UselessRescue: @@ -2491,13 +2547,17 @@ Lint/UselessSetterCall: Lint/UselessTimes: Description: 'Checks for useless `Integer#times` calls.' Enabled: true - VersionAdded: '0.91' Safe: false + AutoCorrect: contextual + VersionAdded: '0.91' + VersionChanged: '<>' Lint/Void: Description: 'Possible use of operator/literal/variable in void context.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.9' + VersionChanged: '<>' CheckForMethodsWithNoSideEffects: false #################### Metrics ############################### @@ -3055,7 +3115,20 @@ Style/ArgumentsForwarding: StyleGuide: '#arguments-forwarding' Enabled: pending AllowOnlyRestArgument: true + UseAnonymousForwarding: true + RedundantRestArgumentNames: + - args + - arguments + RedundantKeywordRestArgumentNames: + - kwargs + - options + - opts + RedundantBlockArgumentNames: + - blk + - block + - proc VersionAdded: '1.1' + VersionChanged: '1.58' Style/ArrayCoercion: Description: >- @@ -3066,6 +3139,13 @@ Style/ArrayCoercion: Enabled: false VersionAdded: '0.88' +Style/ArrayFirstLast: + Description: 'Use `arr.first` and `arr.last` instead of `arr[0]` and `arr[-1]`.' + Reference: '#first-and-last' + Enabled: false + VersionAdded: '1.58' + Safe: false + Style/ArrayIntersect: Description: 'Use `array1.intersect?(array2)` instead of `(array1 & array2).any?`.' Enabled: 'pending' @@ -3326,7 +3406,9 @@ Style/ClassEqualityComparison: Description: 'Enforces the use of `Object#instance_of?` instead of class comparison for equality.' StyleGuide: '#instance-of-vs-class-comparison' Enabled: true + SafeAutoCorrect: false VersionAdded: '0.93' + VersionChanged: '1.57' AllowedMethods: - == - equal? @@ -3381,6 +3463,7 @@ Style/CollectionMethods: PreferredMethods: collect: 'map' collect!: 'map!' + collect_concat: 'flat_map' inject: 'reduce' detect: 'find' find_all: 'select' @@ -3634,8 +3717,9 @@ Style/EmptyCaseCondition: Style/EmptyElse: Description: 'Avoid empty else-clauses.' Enabled: true + AutoCorrect: contextual VersionAdded: '0.28' - VersionChanged: '0.32' + VersionChanged: '<>' EnforcedStyle: both # empty - warn only on empty `else` # nil - warn on `else` with nil in it @@ -3649,7 +3733,9 @@ Style/EmptyElse: Style/EmptyHeredoc: Description: 'Checks for using empty heredoc to reduce redundancy.' Enabled: pending + AutoCorrect: contextual VersionAdded: '1.32' + VersionChanged: '<>' Style/EmptyLambdaParameter: Description: 'Omit parens for empty lambda parameters.' @@ -3667,7 +3753,9 @@ Style/EmptyMethod: Description: 'Checks the formatting of empty method definitions.' StyleGuide: '#no-single-line-methods' Enabled: true + AutoCorrect: contextual VersionAdded: '0.46' + VersionChanged: '<>' EnforcedStyle: compact SupportedStyles: - compact @@ -3899,8 +3987,9 @@ Style/HashConversion: Description: 'Avoid Hash[] in favor of ary.to_h or literal hashes.' StyleGuide: '#avoid-hash-constructor' Enabled: pending + SafeAutoCorrect: false VersionAdded: '1.10' - VersionChanged: '1.11' + VersionChanged: '1.55' AllowSplatArgument: true Style/HashEachMethods: @@ -4101,12 +4190,6 @@ Style/InvertibleUnlessCondition: :none?: :any? :even?: :odd? :odd?: :even? - # `ActiveSupport` defines some common inverse methods. They are listed below, - # and not enabled by default. - # :present?: :blank? - # :blank?: :present? - # :include?: :exclude? - # :exclude?: :include? Style/IpAddresses: Description: "Don't include literal IP addresses in code." @@ -4650,6 +4733,7 @@ Style/OperatorMethodCall: Style/OptionHash: Description: "Don't use option hashes when you can use keyword arguments." + StyleGuide: '#keyword-arguments-vs-option-hashes' Enabled: false VersionAdded: '0.33' VersionChanged: '0.34' @@ -4772,8 +4856,9 @@ Style/RaiseArgs: Description: 'Checks the arguments passed to raise/fail.' StyleGuide: '#exception-class-messages' Enabled: true + Safe: false VersionAdded: '0.14' - VersionChanged: '1.2' + VersionChanged: '<>' EnforcedStyle: exploded SupportedStyles: - compact # raise Exception.new(msg) @@ -4793,12 +4878,16 @@ Style/RedundantArgument: Enabled: pending Safe: false VersionAdded: '1.4' - VersionChanged: '1.40' + VersionChanged: '1.55' Methods: # Array#join join: '' # Array#sum sum: 0 + # Kernel.#exit + exit: true + # Kernel.#exit! + exit!: false # String#split split: ' ' # String#chomp @@ -4843,6 +4932,11 @@ Style/RedundantConstantBase: Enabled: pending VersionAdded: '1.40' +Style/RedundantCurrentDirectoryInPath: + Description: 'Checks for uses a redundant current directory in path.' + Enabled: pending + VersionAdded: '1.53' + Style/RedundantDoubleSplatHashBraces: Description: 'Checks for redundant uses of double splat hash braces.' Enabled: pending @@ -4865,7 +4959,7 @@ Style/RedundantFetchBlock: Description: >- Use `fetch(key, value)` instead of `fetch(key) { value }` when value has Numeric, Rational, Complex, Symbol or String type, `false`, `true`, `nil` or is a constant. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#hashfetch-with-argument-vs-hashfetch--block-code' + Reference: 'https://github.com/fastruby/fast-ruby#hashfetch-with-argument-vs-hashfetch--block-code' Enabled: true Safe: false # If enabled, this cop will autocorrect usages of @@ -4887,7 +4981,9 @@ Style/RedundantFilterChain: Identifies usages of `any?`, `empty?`, `none?` or `one?` predicate methods chained to `select`/`filter`/`find_all` and change them to use predicate method instead. Enabled: pending + SafeAutoCorrect: false VersionAdded: '1.52' + VersionChanged: '1.57' Style/RedundantFreeze: Description: "Checks usages of Object#freeze on immutable objects." @@ -4903,10 +4999,11 @@ Style/RedundantHeredocDelimiterQuotes: Style/RedundantInitialize: Description: 'Checks for redundant `initialize` methods.' Enabled: pending + AutoCorrect: contextual Safe: false AllowComments: true VersionAdded: '1.27' - VersionChanged: '1.28' + VersionChanged: '<>' Style/RedundantInterpolation: Description: 'Checks for strings that are just an interpolated expression.' @@ -4931,6 +5028,11 @@ Style/RedundantPercentQ: Enabled: true VersionAdded: '0.76' +Style/RedundantRegexpArgument: + Description: 'Identifies places where argument can be replaced from a deterministic regexp to a string.' + Enabled: pending + VersionAdded: '1.53' + Style/RedundantRegexpCharacterClass: Description: 'Checks for unnecessary single-element Regexp character classes.' Enabled: true @@ -5043,6 +5145,15 @@ Style/ReturnNil: - return_nil VersionAdded: '0.50' +Style/ReturnNilInPredicateMethodDefinition: + Description: 'Checks if uses of `return` or `return nil` in predicate method definition.' + StyleGuide: '#bool-methods-qmark' + Enabled: pending + SafeAutoCorrect: false + AllowedMethods: [] + AllowedPatterns: [] + VersionAdded: '1.53' + Style/SafeNavigation: Description: >- Transforms usages of a method call safeguarded by @@ -5070,7 +5181,7 @@ Style/Sample: Description: >- Use `sample` instead of `shuffle.first`, `shuffle.last`, and `shuffle[Integer]`. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code' + Reference: 'https://github.com/fastruby/fast-ruby#arrayshufflefirst-vs-arraysample-code' Enabled: true VersionAdded: '0.30' @@ -5135,6 +5246,12 @@ Style/SingleLineBlockParams: - acc - elem +Style/SingleLineDoEndBlock: + Description: 'Checks for single-line `do`...`end` blocks.' + StyleGuide: '#single-line-do-end-block' + Enabled: pending + VersionAdded: '1.57' + Style/SingleLineMethods: Description: 'Avoid single-line methods.' StyleGuide: '#no-single-line-methods' @@ -5144,7 +5261,8 @@ Style/SingleLineMethods: AllowIfMethodIsEmpty: true Style/SlicingWithRange: - Description: 'Checks array slicing is done with endless ranges when suitable.' + Description: 'Checks array slicing is done with redundant, endless, and beginless ranges when suitable.' + StyleGuide: '#slicing-with-ranges' Enabled: true VersionAdded: '0.83' Safe: false @@ -5271,6 +5389,12 @@ Style/StructInheritance: VersionAdded: '0.29' VersionChanged: '1.20' +Style/SuperWithArgsParentheses: + Description: 'Use parentheses for `super` with arguments.' + StyleGuide: '#super-with-args' + Enabled: pending + VersionAdded: '1.58' + Style/SwapValues: Description: 'Enforces the use of shorthand-style swapping of 2 variables.' StyleGuide: '#values-swapping' @@ -5527,6 +5651,11 @@ Style/WordArray: # The regular expression `WordRegex` decides what is considered a word. WordRegex: !ruby/regexp '/\A(?:\p{Word}|\p{Word}-\p{Word}|\n|\t)+\z/' +Style/YAMLFileRead: + Description: 'Checks for the use of `YAML.load`, `YAML.safe_load`, and `YAML.parse` with `File.read` argument.' + Enabled: pending + VersionAdded: '1.53' + Style/YodaCondition: Description: 'Forbid or enforce yoda conditions.' Reference: 'https://en.wikipedia.org/wiki/Yoda_conditions' diff --git a/config/obsoletion.yml b/config/obsoletion.yml index 80f7b20ace6..7f1e16156a2 100644 --- a/config/obsoletion.yml +++ b/config/obsoletion.yml @@ -224,6 +224,11 @@ changed_parameters: - AllowedMethods - AllowedPatterns severity: warning + - cops: Style/ArgumentsForwarding + parameters: AllowOnlyRestArgument + reason: "`AllowOnlyRestArgument` has no effect with TargetRubyVersion >= 3.2." + severity: warning + minimum_ruby_version: 3.2 # Enforced styles that have been removed or replaced changed_enforced_styles: diff --git a/docs/modules/ROOT/pages/about/history.adoc b/docs/modules/ROOT/pages/about/history.adoc index 7509a6b31b1..7a302e39d71 100644 --- a/docs/modules/ROOT/pages/about/history.adoc +++ b/docs/modules/ROOT/pages/about/history.adoc @@ -4,7 +4,7 @@ You don't know where you're going until you know where you've been. RuboCop was created by Bozhidar Batsov in the spring of 2012, as an attempt -to make it easy to apply consistently the guidelines from the community Ruby Style Guide. +to make it easy to apply consistently the guidelines from the community Ruby Style Guide.footnote:[This is the https://github.com/rubocop/ruby-style-guide/issues/54[GitHub issue] that started it all.] == Notable Milestones diff --git a/docs/modules/ROOT/pages/about/license.adoc b/docs/modules/ROOT/pages/about/license.adoc index e6530e752db..3dbd80c9300 100644 --- a/docs/modules/ROOT/pages/about/license.adoc +++ b/docs/modules/ROOT/pages/about/license.adoc @@ -13,4 +13,4 @@ All the original Ruby code is available under the terms of the MIT license. == Copyright -Copyright (c) 2012-2023 Bozhidar Batsov and RuboCop contributors. +Copyright (c) 2012-2024 Bozhidar Batsov and RuboCop contributors. diff --git a/docs/modules/ROOT/pages/compatibility.adoc b/docs/modules/ROOT/pages/compatibility.adoc index df1ee9713a7..51ec36e9346 100644 --- a/docs/modules/ROOT/pages/compatibility.adoc +++ b/docs/modules/ROOT/pages/compatibility.adoc @@ -13,8 +13,9 @@ NOTE: RuboCop might be working with other Ruby implementations as well, but it's == Support Matrix -RuboCop generally aims to follow MRI's own support policy - meaning RuboCop would support all officially supported MRI releases.footnote:[Typically the last 3 releases.] To give people extra time for a smooth transition, we've customarily provided support for about one year after EOL of MRI version. -This means that if Ruby 2.7 reaches its EOL in Spring 2023, it would be supported by RuboCop (at least) until Spring 2024.footnote:[At the core team's discretion this policy might be waived aside for MRI releases causing significant maintenance overhead.] +RuboCop generally aims to follow MRI's own support policy - meaning RuboCop would support all officially supported MRI releases.footnote:[Typically the last 3 releases.] To give people extra time for a smooth transition, we've customarily provided support for about one year after EOL of MRI version. footnote:[At the core team's discretion this policy might be waived aside for MRI releases causing significant maintenance overhead.] + +NOTE: There are major version incompatibilities between Ruby 2.7 and Ruby 3.0, and the latest stable version of Ruby on Rails, 7.1, still supports Ruby 2.7. Therefore, it might be early for RuboCop to drop support for Ruby 2.7 at this stage. As long as Rails 7.1 is in the "Bug Fix" phase of the https://guides.rubyonrails.org/maintenance_policy.html[Maintenance Policy for Ruby on Rails], RuboCop will continue supporting Ruby 2.7. The following table is the runtime support matrix. @@ -33,7 +34,7 @@ The following table is the runtime support matrix. | 3.0 | - | 3.1 | - | 3.2 | - -| 3.3 (experimental) | - +| 3.3 | - |=== RuboCop targets Ruby 2.0+ code analysis since RuboCop 1.30. It restored code analysis support that had been removed earlier by mistake, together with dropping runtime support for unsupported Ruby versions. diff --git a/docs/modules/ROOT/pages/configuration.adoc b/docs/modules/ROOT/pages/configuration.adoc index a6598f327ce..9da64132fa1 100644 --- a/docs/modules/ROOT/pages/configuration.adoc +++ b/docs/modules/ROOT/pages/configuration.adoc @@ -29,10 +29,12 @@ RuboCop will start looking for the configuration file in the directory where the inspected file is and continue its way up to the root directory. If it cannot be found until reaching the project's root directory, then it will -be searched for in the user's global config locations, which consists of a +be searched for in the https://dot-config.github.io[.config directory of the project root] +and the user's global config locations. The user's global config locations consist of a dotfile or a config file inside the https://specifications.freedesktop.org/basedir-spec/latest/index.html[XDG Base Directory specification]. +* `.config/.rubocop.yml` or `.config/rubocop/config.yml` at the project root * `~/.rubocop.yml` * `$XDG_CONFIG_HOME/rubocop/config.yml` (expands to `~/.config/rubocop/config.yml` if `$XDG_CONFIG_HOME` is not set) @@ -46,6 +48,8 @@ files: * `/path/to/project/lib/utils/.rubocop.yml` * `/path/to/project/lib/.rubocop.yml` * `/path/to/project/.rubocop.yml` +* `/path/to/project/.config/.rubocop.yml` +* `/path/to/project/.config/rubocop/config.yml` * `/.rubocop.yml` * `~/.rubocop.yml` * `~/.config/rubocop/config.yml` @@ -567,13 +571,46 @@ These details will only be seen when RuboCop is run with the `--extra-details` f === AutoCorrect -Cops that support the `--autocorrect` option can have that support -disabled. For example: +Cops that support the `--autocorrect` option offer flexible settings for autocorrection. +These settings can be specified in the configuration file as follows: + +- `always` +- `contextual` +- `disabled` + +==== `always (Default)` + +This setting enables autocorrection always by default. For backward compatibility, `true` is treated the same as `always`. + +[source,yaml] +---- +Style/PerlBackrefs: + AutoCorrect: always # or true +---- + +==== `contextual` + +This setting enables autocorrection when launched from the `rubocop` command, but it is not available through LSP. +e.g., `rubocop --lsp`, `rubocop --editor-mode`, or a program where `RuboCop::LSP.enable` has been applied. + +Inspections via the command line are treated as code that has been finalized. + +[source,yaml] +---- +Style/PerlBackrefs: + AutoCorrect: contextual +---- + +This setting prevents autocorrection during editing in the editor. + +==== `disabled` + +This setting disables autocorrection. For backward compatibility, `false` is treated the same as `disabled`. [source,yaml] ---- Style/PerlBackrefs: - AutoCorrect: false + AutoCorrect: disabled # or false ---- == Common configuration parameters @@ -610,7 +647,7 @@ AllCops: Otherwise, RuboCop will then check your project for a series of files where the version may be specified already. The files that will be looked for are -`.ruby-version`, `.tool-versions`, `Gemfile.lock`, and `*.gemspec`. +`*.gemspec`, `.ruby-version`, `.tool-versions`, and `Gemfile.lock`. If Gemspec file has an array for `required_ruby_version`, the lowest version will be used. If none of the files are found a default version value will be used. diff --git a/docs/modules/ROOT/pages/cops.adoc b/docs/modules/ROOT/pages/cops.adoc index 9d03824c1ee..0aea3d2af73 100644 --- a/docs/modules/ROOT/pages/cops.adoc +++ b/docs/modules/ROOT/pages/cops.adoc @@ -77,6 +77,7 @@ In the following section you find all available cops: === Department xref:cops_bundler.adoc[Bundler] * xref:cops_bundler.adoc#bundlerduplicatedgem[Bundler/DuplicatedGem] +* xref:cops_bundler.adoc#bundlerduplicatedgroup[Bundler/DuplicatedGroup] * xref:cops_bundler.adoc#bundlergemcomment[Bundler/GemComment] * xref:cops_bundler.adoc#bundlergemfilename[Bundler/GemFilename] * xref:cops_bundler.adoc#bundlergemversion[Bundler/GemVersion] @@ -252,12 +253,15 @@ In the following section you find all available cops: * xref:cops_lint.adoc#lintineffectiveaccessmodifier[Lint/IneffectiveAccessModifier] * xref:cops_lint.adoc#lintinheritexception[Lint/InheritException] * xref:cops_lint.adoc#lintinterpolationcheck[Lint/InterpolationCheck] +* xref:cops_lint.adoc#lintitwithoutargumentsinblock[Lint/ItWithoutArgumentsInBlock] * xref:cops_lint.adoc#lintlambdawithoutliteralblock[Lint/LambdaWithoutLiteralBlock] * xref:cops_lint.adoc#lintliteralascondition[Lint/LiteralAsCondition] +* xref:cops_lint.adoc#lintliteralassignmentincondition[Lint/LiteralAssignmentInCondition] * xref:cops_lint.adoc#lintliteralininterpolation[Lint/LiteralInInterpolation] * xref:cops_lint.adoc#lintloop[Lint/Loop] * xref:cops_lint.adoc#lintmissingcopenabledirective[Lint/MissingCopEnableDirective] * xref:cops_lint.adoc#lintmissingsuper[Lint/MissingSuper] +* xref:cops_lint.adoc#lintmixedcaserange[Lint/MixedCaseRange] * xref:cops_lint.adoc#lintmixedregexpcapturetypes[Lint/MixedRegexpCaptureTypes] * xref:cops_lint.adoc#lintmultiplecomparison[Lint/MultipleComparison] * xref:cops_lint.adoc#lintnestedmethoddefinition[Lint/NestedMethodDefinition] @@ -280,6 +284,7 @@ In the following section you find all available cops: * xref:cops_lint.adoc#lintredundantcopdisabledirective[Lint/RedundantCopDisableDirective] * xref:cops_lint.adoc#lintredundantcopenabledirective[Lint/RedundantCopEnableDirective] * xref:cops_lint.adoc#lintredundantdirglobsort[Lint/RedundantDirGlobSort] +* xref:cops_lint.adoc#lintredundantregexpquantifiers[Lint/RedundantRegexpQuantifiers] * xref:cops_lint.adoc#lintredundantrequirestatement[Lint/RedundantRequireStatement] * xref:cops_lint.adoc#lintredundantsafenavigation[Lint/RedundantSafeNavigation] * xref:cops_lint.adoc#lintredundantsplatexpansion[Lint/RedundantSplatExpansion] @@ -388,6 +393,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#styleandor[Style/AndOr] * xref:cops_style.adoc#styleargumentsforwarding[Style/ArgumentsForwarding] * xref:cops_style.adoc#stylearraycoercion[Style/ArrayCoercion] +* xref:cops_style.adoc#stylearrayfirstlast[Style/ArrayFirstLast] * xref:cops_style.adoc#stylearrayintersect[Style/ArrayIntersect] * xref:cops_style.adoc#stylearrayjoin[Style/ArrayJoin] * xref:cops_style.adoc#styleasciicomments[Style/AsciiComments] @@ -556,6 +562,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#styleredundantcondition[Style/RedundantCondition] * xref:cops_style.adoc#styleredundantconditional[Style/RedundantConditional] * xref:cops_style.adoc#styleredundantconstantbase[Style/RedundantConstantBase] +* xref:cops_style.adoc#styleredundantcurrentdirectoryinpath[Style/RedundantCurrentDirectoryInPath] * xref:cops_style.adoc#styleredundantdoublesplathashbraces[Style/RedundantDoubleSplatHashBraces] * xref:cops_style.adoc#styleredundanteach[Style/RedundantEach] * xref:cops_style.adoc#styleredundantexception[Style/RedundantException] @@ -569,6 +576,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#styleredundantlinecontinuation[Style/RedundantLineContinuation] * xref:cops_style.adoc#styleredundantparentheses[Style/RedundantParentheses] * xref:cops_style.adoc#styleredundantpercentq[Style/RedundantPercentQ] +* xref:cops_style.adoc#styleredundantregexpargument[Style/RedundantRegexpArgument] * xref:cops_style.adoc#styleredundantregexpcharacterclass[Style/RedundantRegexpCharacterClass] * xref:cops_style.adoc#styleredundantregexpconstructor[Style/RedundantRegexpConstructor] * xref:cops_style.adoc#styleredundantregexpescape[Style/RedundantRegexpEscape] @@ -584,6 +592,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#stylerescuemodifier[Style/RescueModifier] * xref:cops_style.adoc#stylerescuestandarderror[Style/RescueStandardError] * xref:cops_style.adoc#stylereturnnil[Style/ReturnNil] +* xref:cops_style.adoc#stylereturnnilinpredicatemethoddefinition[Style/ReturnNilInPredicateMethodDefinition] * xref:cops_style.adoc#stylesafenavigation[Style/SafeNavigation] * xref:cops_style.adoc#stylesample[Style/Sample] * xref:cops_style.adoc#styleselectbyregexp[Style/SelectByRegexp] @@ -593,6 +602,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#stylesignalexception[Style/SignalException] * xref:cops_style.adoc#stylesingleargumentdig[Style/SingleArgumentDig] * xref:cops_style.adoc#stylesinglelineblockparams[Style/SingleLineBlockParams] +* xref:cops_style.adoc#stylesinglelinedoendblock[Style/SingleLineDoEndBlock] * xref:cops_style.adoc#stylesinglelinemethods[Style/SingleLineMethods] * xref:cops_style.adoc#styleslicingwithrange[Style/SlicingWithRange] * xref:cops_style.adoc#stylesolenestedconditional[Style/SoleNestedConditional] @@ -608,6 +618,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#stylestringmethods[Style/StringMethods] * xref:cops_style.adoc#stylestrip[Style/Strip] * xref:cops_style.adoc#stylestructinheritance[Style/StructInheritance] +* xref:cops_style.adoc#stylesuperwithargsparentheses[Style/SuperWithArgsParentheses] * xref:cops_style.adoc#styleswapvalues[Style/SwapValues] * xref:cops_style.adoc#stylesymbolarray[Style/SymbolArray] * xref:cops_style.adoc#stylesymbolliteral[Style/SymbolLiteral] @@ -632,6 +643,7 @@ In the following section you find all available cops: * xref:cops_style.adoc#stylewhileuntildo[Style/WhileUntilDo] * xref:cops_style.adoc#stylewhileuntilmodifier[Style/WhileUntilModifier] * xref:cops_style.adoc#stylewordarray[Style/WordArray] +* xref:cops_style.adoc#styleyamlfileread[Style/YAMLFileRead] * xref:cops_style.adoc#styleyodacondition[Style/YodaCondition] * xref:cops_style.adoc#styleyodaexpression[Style/YodaExpression] * xref:cops_style.adoc#stylezerolengthpredicate[Style/ZeroLengthPredicate] diff --git a/docs/modules/ROOT/pages/cops_bundler.adoc b/docs/modules/ROOT/pages/cops_bundler.adoc index 454d018e8c4..945d14f71ef 100644 --- a/docs/modules/ROOT/pages/cops_bundler.adoc +++ b/docs/modules/ROOT/pages/cops_bundler.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Bundler == Bundler/DuplicatedGem @@ -63,6 +69,88 @@ end | Array |=== +== Bundler/DuplicatedGroup + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Enabled +| Yes +| No +| 1.56 +| - +|=== + +A Gem group, or a set of groups, should be listed only once in a Gemfile. + +For example, if the values of `source`, `git`, `platforms`, or `path` +surrounding `group` are different, no offense will be registered: + +[source,ruby] +----- +platforms :ruby do + group :default do + gem 'openssl' + end +end + +platforms :jruby do + group :default do + gem 'jruby-openssl' + end +end +----- + +=== Examples + +[source,ruby] +---- +# bad +group :development do + gem 'rubocop' +end + +group :development do + gem 'rubocop-rails' +end + +# bad (same set of groups declared twice) +group :development, :test do + gem 'rubocop' +end + +group :test, :development do + gem 'rspec' +end + +# good +group :development do + gem 'rubocop' +end + +group :development, :test do + gem 'rspec' +end + +# good +gem 'rubocop', groups: [:development, :test] +gem 'rspec', groups: [:development, :test] +---- + +=== Configurable attributes + +|=== +| Name | Default value | Configurable values + +| Severity +| `warning` +| String + +| Include +| `+**/*.gemfile+`, `+**/Gemfile+`, `+**/gems.rb+` +| Array +|=== + == Bundler/GemComment |=== @@ -439,8 +527,24 @@ gem 'rubocop' gem 'rubocop' gem 'rspec' +---- -# good only if TreatCommentsAsGroupSeparators is true +==== TreatCommentsAsGroupSeparators: true (default) + +[source,ruby] +---- +# good +# For code quality +gem 'rubocop' +# For tests +gem 'rspec' +---- + +==== TreatCommentsAsGroupSeparators: false + +[source,ruby] +---- +# bad # For code quality gem 'rubocop' # For tests diff --git a/docs/modules/ROOT/pages/cops_gemspec.adoc b/docs/modules/ROOT/pages/cops_gemspec.adoc index 7e126e2cd39..ee167a97cfa 100644 --- a/docs/modules/ROOT/pages/cops_gemspec.adoc +++ b/docs/modules/ROOT/pages/cops_gemspec.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Gemspec == Gemspec/DependencyVersion @@ -362,8 +368,24 @@ spec.add_runtime_dependency 'rubocop' spec.add_runtime_dependency 'rubocop' spec.add_runtime_dependency 'rspec' +---- -# good only if TreatCommentsAsGroupSeparators is true +==== TreatCommentsAsGroupSeparators: true (default) + +[source,ruby] +---- +# good +# For code quality +spec.add_dependency 'rubocop' +# For tests +spec.add_dependency 'rspec' +---- + +==== TreatCommentsAsGroupSeparators: false + +[source,ruby] +---- +# bad # For code quality spec.add_dependency 'rubocop' # For tests diff --git a/docs/modules/ROOT/pages/cops_layout.adoc b/docs/modules/ROOT/pages/cops_layout.adoc index fb141300267..2c595753eb5 100644 --- a/docs/modules/ROOT/pages/cops_layout.adoc +++ b/docs/modules/ROOT/pages/cops_layout.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Layout == Layout/AccessModifierIndentation @@ -632,9 +638,9 @@ end | Disabled | Yes -| Yes +| Yes (Unsafe) | 0.52 -| - +| 1.53 |=== Checks if the code style follows the ExpectedOrder configuration: @@ -702,6 +708,14 @@ automatically. - extend ---- +=== Safety + +Autocorrection is unsafe because class methods and module inclusion +can behave differently, based on which methods or constants have +already been defined. + +Constants will only be moved when they are assigned with literals. + === Examples [source,ruby] @@ -1322,7 +1336,23 @@ end | 0.59 |=== -Enforces empty line after guard clause +Enforces empty line after guard clause. + +This cop allows `# :nocov:` directive after guard clause because +SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`: + +[source,ruby] +---- +def foo + # :nocov: + return if condition + # :nocov: + bar +end +---- + +Refer to SimpleCov's documentation for more details: +https://github.com/simplecov-ruby/simplecov#ignoringskipping-code === Examples @@ -1618,6 +1648,10 @@ class ErrorC < BaseError; end | `true` | Boolean +| DefLikeMacros +| `[]` +| Array + | AllowAdjacentOneLineDefs | `true` | Boolean @@ -2739,7 +2773,10 @@ second_param Checks the indentation of the first element in an array literal where the opening bracket and the first element are on separate lines. -The other elements' indentations are handled by the ArrayAlignment cop. +The other elements' indentations are handled by `Layout/ArrayAlignment` cop. + +This cop will respect `Layout/ArrayAlignment` and will not work when +`EnforcedStyle: with_fixed_indentation` is specified for `Layout/ArrayAlignment`. By default, array literals that are arguments in a method call with parentheses, and where the opening square bracket of the array is on the @@ -2764,7 +2801,7 @@ styles are 'consistent' and 'align_brackets'. Here are examples: # element are on separate lines is indented one step (two spaces) more # than the position inside the opening parenthesis. -#bad +# bad array = [ :value ] @@ -2772,7 +2809,7 @@ and_in_a_method_call([ :no_difference ]) -#good +# good array = [ :value ] @@ -2790,7 +2827,7 @@ but_in_a_method_call([ # separate lines is indented the same as an array literal which is not # defined inside a method call. -#bad +# bad # consistent array = [ :value @@ -2799,7 +2836,7 @@ but_in_a_method_call([ :its_like_this ]) -#good +# good array = [ :value ] @@ -2815,13 +2852,13 @@ and_in_a_method_call([ # The `align_brackets` style enforces that the opening and closing # brackets are indented to the same position. -#bad +# bad # align_brackets and_now_for_something = [ :completely_different ] -#good +# good # align_brackets and_now_for_something = [ :completely_different @@ -3689,6 +3726,8 @@ opening HEREDOC tag. == Layout/HeredocIndentation +NOTE: Required Ruby version: 2.3 + |=== | Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed @@ -3704,7 +3743,7 @@ are indented one step. Note: When ``Layout/LineLength``'s `AllowHeredoc` is false (not default), this cop does not add any offenses for long here documents to - avoid `Layout/LineLength`'s offenses. + avoid ``Layout/LineLength``'s offenses. === Examples @@ -6227,7 +6266,7 @@ foo &.bar foo &. bar foo &. bar&. buzz RuboCop:: Cop -RuboCop:: Cop:: Cop +RuboCop:: Cop:: Base :: RuboCop::Cop # good @@ -6239,7 +6278,7 @@ foo foo&.bar foo&.bar&.buzz RuboCop::Cop -RuboCop::Cop::Cop +RuboCop::Cop::Base ::RuboCop::Cop ---- @@ -6323,6 +6362,28 @@ a**b a ** b ---- +==== EnforcedStyleForRationalLiterals: no_space (default) + +[source,ruby] +---- +# bad +1 / 48r + +# good +1/48r +---- + +==== EnforcedStyleForRationalLiterals: space + +[source,ruby] +---- +# bad +1/48r + +# good +1 / 48r +---- + === Configurable attributes |=== @@ -6335,6 +6396,10 @@ a ** b | EnforcedStyleForExponentOperator | `no_space` | `space`, `no_space` + +| EnforcedStyleForRationalLiterals +| `no_space` +| `space`, `no_space` |=== === References diff --git a/docs/modules/ROOT/pages/cops_lint.adoc b/docs/modules/ROOT/pages/cops_lint.adoc index b345470909b..bbdd02a163f 100644 --- a/docs/modules/ROOT/pages/cops_lint.adoc +++ b/docs/modules/ROOT/pages/cops_lint.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Lint == Lint/AmbiguousAssignment @@ -121,10 +127,6 @@ expect { do_something }.to not_change { object.attribute } | Array |=== -=== References - -* https://rubystyle.guide#syntax - == Lint/AmbiguousOperator |=== @@ -358,12 +360,12 @@ the author meant to use an assignment result as a condition. [source,ruby] ---- # bad -if some_var = true +if some_var = value do_something end # good -if some_var == true +if some_var == value do_something end ---- @@ -373,7 +375,7 @@ end [source,ruby] ---- # good -if (some_var = true) +if (some_var = value) do_something end ---- @@ -383,7 +385,7 @@ end [source,ruby] ---- # bad -if (some_var = true) +if (some_var = value) do_something end ---- @@ -444,10 +446,10 @@ BigDecimal(123.456, 3) Checks for places where binary operator has identical operands. It covers arithmetic operators: `-`, `/`, `%`; -comparison operators: `==`, `===`, `=~`, `>`, `>=`, `<`, `<=`; +comparison operators: `==`, `===`, `=~`, `>`, `>=`, `<`, ``<=``; bitwise operators: `|`, `^`, `&`; boolean operators: `&&`, `||` -and "spaceship" operator - `<=>`. +and "spaceship" operator - ``<=>``. Simple arithmetic operations are allowed by this cop: `+`, `*`, `**`, `<<` and `>>`. Although these can be rewritten in a different way, it should not be necessary to @@ -697,7 +699,7 @@ end | - |=== -Checks for overwriting an exception with an exception result by use `rescue =>`. +Checks for overwriting an exception with an exception result by use ``rescue =>``. You intended to write as `rescue StandardError`. However, you have written `rescue => StandardError`. @@ -1324,6 +1326,7 @@ end |=== Checks for duplicated keys in hash literals. +This cop considers both primitive types and constants for the hash keys. This cop mirrors a warning in Ruby 2.2. @@ -1755,7 +1758,7 @@ end Checks for blocks without a body. Such empty blocks are typically an oversight or we should provide a comment -be clearer what we're aiming for. +to clarify what we're aiming for. Empty lambdas and procs are ignored by default. @@ -2550,6 +2553,20 @@ is almost never the desired semantics. Comparison via the `==/!=` operators chec floating-point value representation to be exactly the same, which is very unlikely if you perform any arithmetic operations involving precision loss. + # good - comparing against zero + x == 0.0 + x != 0.0 + + # good + (x - 0.1).abs < Float::EPSILON + + # good + tolerance = 0.0001 + (x - 0.1).abs < tolerance + + # Or some other epsilon based type of comparison: + # https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/ + === Examples [source,ruby] @@ -2560,16 +2577,6 @@ x != 0.1 # good - using BigDecimal x.to_d == 0.1.to_d - -# good -(x - 0.1).abs < Float::EPSILON - -# good -tolerance = 0.0001 -(x - 0.1).abs < tolerance - -# Or some other epsilon based type of comparison: -# https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/ ---- === References @@ -3026,6 +3033,46 @@ foo = 'something with #{interpolation} inside' foo = "something with #{interpolation} inside" ---- +== Lint/ItWithoutArgumentsInBlock + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| No +| 1.59 +| - +|=== + +Emulates the following Ruby warning in Ruby 3.3. + +[source,ruby] +---- +$ ruby -e '0.times { it }' +-e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; +use it() or self.it +---- + +`it` calls without arguments will refer to the first block param in Ruby 3.4. +So use `it()` or `self.it` to ensure compatibility. + +=== Examples + +[source,ruby] +---- +# bad +do_something { it } + +# good +do_something { it() } +do_something { self.it } +---- + +=== References + +* https://bugs.ruby-lang.org/issues/18980 + == Lint/LambdaWithoutLiteralBlock |=== @@ -3108,6 +3155,50 @@ while true end ---- +== Lint/LiteralAssignmentInCondition + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| No +| 1.58 +| - +|=== + +Checks for literal assignments in the conditions of `if`, `while`, and `until`. +It emulates the following Ruby warning: + +[source,console] +---- +$ ruby -we 'if x = true; end' +-e:1: warning: found `= literal' in conditional, should be == +---- + +As a lint cop, it cannot be determined if `==` is appropriate as intended, +therefore this cop does not provide autocorrection. + +=== Examples + +[source,ruby] +---- +# bad +if x = 42 + do_something +end + +# good +if x == 42 + do_something +end + +# good +if x = y + do_something +end +---- + == Lint/LiteralInInterpolation |=== @@ -3295,6 +3386,13 @@ challenging or verbose for no actual gain. Autocorrection is not supported because the position of `super` cannot be determined automatically. +`Object` and `BasicObject` are allowed by this cop because of their +stateless nature. However, sometimes you might want to allow other parent +classes from this cop, for example in the case of an abstract class that is +not meant to be called with `super`. In those cases, you can use the +`AllowedParentClasses` option to specify which classes should be allowed +*in addition to* `Object` and `BasicObject`. + === Examples [source,ruby] @@ -3343,6 +3441,74 @@ class Parent do_something end end + +# good +class ClassWithNoParent + def initialize + do_something + end +end +---- + +==== AllowedParentClasses: [MyAbstractClass] + +[source,ruby] +---- +# good +class MyConcreteClass < MyAbstractClass + def initialize + do_something + end +end +---- + +=== Configurable attributes + +|=== +| Name | Default value | Configurable values + +| AllowedParentClasses +| `[]` +| Array +|=== + +== Lint/MixedCaseRange + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes (Unsafe) +| 1.53 +| - +|=== + +Checks for mixed-case character ranges since they include likely unintended characters. + +Offenses are registered for regexp character classes like `/[A-z]/` +as well as range objects like `('A'..'z')`. + +NOTE: Range objects cannot be autocorrected. + +=== Safety + +The cop autocorrects regexp character classes +by replacing one character range with two: `A-z` becomes `A-Za-z`. +In most cases this is probably what was originally intended +but it changes the regexp to no longer match symbols it used to include. +For this reason, this cop's autocorrect is unsafe (it will +change the behavior of the code). + +=== Examples + +[source,ruby] +---- +# bad +r = /[A-z]/ + +# good +r = /[A-Za-z]/ ---- == Lint/MixedRegexpCaptureTypes @@ -3879,7 +4045,7 @@ fails. Cop prefer parsing with number class instead. Conversion with `Integer`, `Float`, etc. will raise an `ArgumentError` if given input that is not numeric (eg. an empty string), whereas -`to_i`, etc. will try to convert regardless of input (`''.to_i => 0`). +`to_i`, etc. will try to convert regardless of input (``''.to_i => 0``). As such, this cop is disabled by default because it's not necessarily always correct to raise if a value is not numeric. @@ -4474,6 +4640,51 @@ Dir['./lib/**/*.rb'].each do |file| end ---- +== Lint/RedundantRegexpQuantifiers + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.53 +| - +|=== + +Checks for redundant quantifiers inside Regexp literals. + +It is always allowed when interpolation is used in a regexp literal, +because it's unknown what kind of string will be expanded as a result: + +[source,ruby] +---- +/(?:a*#{interpolation})?/x +---- + +=== Examples + +[source,ruby] +---- +# bad +/(?:x+)+/ + +# good +/(?:x)+/ + +# good +/(?:x+)/ + +# bad +/(?:x+)?/ + +# good +/(?:x)*/ + +# good +/(?:x*)/ +---- + == Lint/RedundantRequireStatement |=== @@ -4481,9 +4692,9 @@ end | Enabled | Yes -| Yes +| Yes (Unsafe) | 0.76 -| - +| 1.57 |=== Checks for unnecessary `require` statement. @@ -4507,6 +4718,11 @@ Below are the features that each `TargetRubyVersion` targets. This cop target those features. +=== Safety + +This cop's autocorrection is unsafe because if `require 'pp'` is removed from one file, +`NameError` can be encountered when another file uses `PP.pp`. + === Examples [source,ruby] @@ -4532,8 +4748,12 @@ require 'unloaded_feature' |=== Checks for redundant safe navigation calls. -`instance_of?`, `kind_of?`, `is_a?`, `eql?`, `respond_to?`, and `equal?` methods -are checked by default. These are customizable with `AllowedMethods` option. +Use cases where a constant, named in camel case for classes and modules is `nil` are rare, +and an offense is not detected when the receiver is a snake case constant. + +For all receivers, the `instance_of?`, `kind_of?`, `is_a?`, `eql?`, `respond_to?`, +and `equal?` methods are checked by default. +These are customizable with `AllowedMethods` option. The `AllowedMethods` option specifies nil-safe methods, in other words, it is a method that is allowed to skip safe navigation. @@ -4553,6 +4773,9 @@ will be autocorrected to never return `nil`. [source,ruby] ---- +# bad +CamelCaseConst&.do_something + # bad do_something if attrs&.respond_to?(:[]) @@ -4564,6 +4787,9 @@ while node&.is_a?(BeginNode) node = node.parent end +# good +CamelCaseConst.do_something + # good while node.is_a?(BeginNode) node = node.parent @@ -4571,6 +4797,22 @@ end # good - without `&.` this will always return `true` foo&.respond_to?(:to_a) + +# bad - for `nil`s conversion methods return default values for the type +foo&.to_h || {} +foo&.to_h { |k, v| [k, v] } || {} +foo&.to_a || [] +foo&.to_i || 0 +foo&.to_f || 0.0 +foo&.to_s || '' + +# good +foo.to_h +foo.to_h { |k, v| [k, v] } +foo.to_a +foo.to_i +foo.to_f +foo.to_s ---- ==== AllowedMethods: [nil_safe_method] @@ -5336,11 +5578,18 @@ Checks for self-assignments. foo = foo foo, bar = foo, bar Foo = Foo +hash['foo'] = hash['foo'] +obj.attr = obj.attr # good foo = bar foo, bar = bar, foo Foo = Bar +hash['foo'] = hash['bar'] +obj.attr = obj.attr2 + +# good (method calls possibly can return different results) +hash[foo] = hash[foo] ---- == Lint/SendWithMixinArgument @@ -5816,6 +6065,7 @@ all keys to be quoted). 'underscored_string'.to_sym :'underscored_symbol' 'hyphenated-string'.to_sym +"string_#{interpolation}".to_sym # good :string @@ -5823,6 +6073,7 @@ all keys to be quoted). :underscored_string :underscored_symbol :'hyphenated-string' +:"string_#{interpolation}" ---- ==== EnforcedStyle: strict (default) @@ -6953,12 +7204,18 @@ Checks for every useless assignment to local variable in every scope. The basic idea for this cop was from the warning of `ruby -cw`: - assigned but unused variable - foo +[source,console] +---- +assigned but unused variable - foo +---- Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc. +NOTE: Given the assignment `foo = 1, bar = 2`, removing unused variables +can lead to a syntax error, so this case is not autocorrected. + === Safety This cop's autocorrection is unsafe because removing assignment from @@ -7278,7 +7535,7 @@ end |=== Checks for uses of `Integer#times` that will never yield -(when the integer <= 0) or that will only ever yield once +(when the integer ``<= 0``) or that will only ever yield once (`1.times`). === Safety @@ -7316,6 +7573,16 @@ do_something(1) Checks for operators, variables, literals, lambda, proc and nonmutating methods used in void context. +`each` blocks are allowed to prevent false positives. +For example, the expression inside the `each` block below. +It's not void, especially when the receiver is an `Enumerator`: + +[source,ruby] +---- +enumerator = [1, 2, 3].filter +enumerator.each { |item| item >= 2 } #=> [2, 3] +---- + === Examples ==== CheckForMethodsWithNoSideEffects: false (default) diff --git a/docs/modules/ROOT/pages/cops_metrics.adoc b/docs/modules/ROOT/pages/cops_metrics.adoc index e8f97e8f244..9d4ec65b436 100644 --- a/docs/modules/ROOT/pages/cops_metrics.adoc +++ b/docs/modules/ROOT/pages/cops_metrics.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Metrics == Metrics/AbcSize @@ -19,9 +25,9 @@ and https://en.wikipedia.org/wiki/ABC_Software_Metric. Interpreting ABC size: -* <= 17 satisfactory -* 18..30 unsatisfactory -* > 30 dangerous +* ``<= 17`` satisfactory +* `18..30` unsatisfactory +* `>` 30 dangerous You can have repeated "attributes" calls count as a single "branch". For this purpose, attributes are any method with no argument; no attempt @@ -98,13 +104,12 @@ You can set constructs you want to fold with `CountAsOne`. Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct will be counted as one line regardless of its actual size. +NOTE: This cop does not apply for `Struct` definitions. NOTE: The `ExcludedMethods` configuration is deprecated and only kept for backwards compatibility. Please use `AllowedMethods` and `AllowedPatterns` instead. By default, there are no methods to allowed. -NOTE: This cop does not apply for `Struct` definitions. - === Examples ==== CountAsOne: ['array', 'heredoc', 'method_call'] diff --git a/docs/modules/ROOT/pages/cops_migration.adoc b/docs/modules/ROOT/pages/cops_migration.adoc index 03880f2578a..07cae85ee07 100644 --- a/docs/modules/ROOT/pages/cops_migration.adoc +++ b/docs/modules/ROOT/pages/cops_migration.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Migration == Migration/DepartmentName diff --git a/docs/modules/ROOT/pages/cops_naming.adoc b/docs/modules/ROOT/pages/cops_naming.adoc index 5ad972417fa..5cb176169bd 100644 --- a/docs/modules/ROOT/pages/cops_naming.adoc +++ b/docs/modules/ROOT/pages/cops_naming.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Naming == Naming/AccessorMethodName diff --git a/docs/modules/ROOT/pages/cops_security.adoc b/docs/modules/ROOT/pages/cops_security.adoc index 221fb08748b..5092bc7f279 100644 --- a/docs/modules/ROOT/pages/cops_security.adoc +++ b/docs/modules/ROOT/pages/cops_security.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Security == Security/CompoundHash @@ -217,6 +223,7 @@ in a class and then used without a receiver in that class. # bad open(something) open("| #{something}") +open("| foo") URI.open(something) # good @@ -226,7 +233,6 @@ URI.parse(something).open # good (literal strings) open("foo.text") -open("| foo") URI.open("http://example.com") ---- diff --git a/docs/modules/ROOT/pages/cops_style.adoc b/docs/modules/ROOT/pages/cops_style.adoc index f4c38360354..aafaaf343e5 100644 --- a/docs/modules/ROOT/pages/cops_style.adoc +++ b/docs/modules/ROOT/pages/cops_style.adoc @@ -1,3 +1,9 @@ +//// + Do NOT edit this file by hand directly, as it is automatically generated. + + Please make any necessary changes to the cop documentation within the source files themselves. +//// + = Style == Style/AccessModifierDeclarations @@ -334,7 +340,7 @@ NOTE: Required Ruby version: 2.7 | Yes | Yes | 1.1 -| - +| 1.58 |=== In Ruby 2.7, arguments forwarding has been added. @@ -342,6 +348,21 @@ In Ruby 2.7, arguments forwarding has been added. This cop identifies places where `do_something(*args, &block)` can be replaced by `do_something(...)`. +In Ruby 3.2, anonymous args/kwargs forwarding has been added. + +This cop also identifies places where `use_args(*args)`/`use_kwargs(**kwargs)` can be +replaced by `use_args(*)`/`use_kwargs(**)`; if desired, this functionality can be disabled +by setting `UseAnonymousForwarding: false`. + +And this cop has `RedundantRestArgumentNames`, `RedundantKeywordRestArgumentNames`, +and `RedundantBlockArgumentNames` options. This configuration is a list of redundant names +that are sufficient for anonymizing meaningless naming. + +Meaningless names that are commonly used can be anonymized by default: +e.g., `*args`, `**options`, `&block`, and so on. + +Names not on this list are likely to be meaningful and are allowed by default. + === Examples [source,ruby] @@ -362,7 +383,35 @@ def foo(...) end ---- -==== AllowOnlyRestArgument: true (default) +==== UseAnonymousForwarding: true (default, only relevant for Ruby >= 3.2) + +[source,ruby] +---- +# bad +def foo(*args, **kwargs) + args_only(*args) + kwargs_only(**kwargs) +end + +# good +def foo(*, **) + args_only(*) + kwargs_only(**) +end +---- + +==== UseAnonymousForwarding: false (only relevant for Ruby >= 3.2) + +[source,ruby] +---- +# good +def foo(*args, **kwargs) + args_only(*args) + kwargs_only(**kwargs) +end +---- + +==== AllowOnlyRestArgument: true (default, only relevant for Ruby < 3.2) [source,ruby] ---- @@ -376,7 +425,7 @@ def foo(**kwargs) end ---- -==== AllowOnlyRestArgument: false +==== AllowOnlyRestArgument: false (only relevant for Ruby < 3.2) [source,ruby] ---- @@ -392,6 +441,51 @@ def foo(**kwargs) end ---- +==== RedundantRestArgumentNames: ['args', 'arguments'] (default) + +[source,ruby] +---- +# bad +def foo(*args) + bar(*args) +end + +# good +def foo(*) + bar(*) +end +---- + +==== RedundantKeywordRestArgumentNames: ['kwargs', 'options', 'opts'] (default) + +[source,ruby] +---- +# bad +def foo(**kwargs) + bar(**kwargs) +end + +# good +def foo(**) + bar(**) +end +---- + +==== RedundantBlockArgumentNames: ['blk', 'block', 'proc'] (default) + +[source,ruby] +---- +# bad - But it is good with `EnforcedStyle: explicit` set for `Naming/BlockForwarding`. +def foo(&block) + bar(&block) +end + +# good +def foo(&) + bar(&) +end +---- + === Configurable attributes |=== @@ -400,6 +494,22 @@ end | AllowOnlyRestArgument | `true` | Boolean + +| UseAnonymousForwarding +| `true` +| Boolean + +| RedundantRestArgumentNames +| `args`, `arguments` +| Array + +| RedundantKeywordRestArgumentNames +| `kwargs`, `options`, `opts` +| Array + +| RedundantBlockArgumentNames +| `blk`, `block`, `proc` +| Array |=== === References @@ -462,6 +572,49 @@ Array(paths).each { |path| do_something(path) } * https://rubystyle.guide#array-coercion +== Style/ArrayFirstLast + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Disabled +| No +| Yes (Unsafe) +| 1.58 +| - +|=== + +Identifies usages of `arr[0]` and `arr[-1]` and suggests to change +them to use `arr.first` and `arr.last` instead. + +The cop is disabled by default due to safety concerns. + +=== Safety + +This cop is unsafe because `[0]` or `[-1]` can be called on a Hash, +which returns a value for `0` or `-1` key, but changing these to use +`.first` or `.last` will return first/last tuple instead. Also, String +does not implement `first`/`last` methods. + +=== Examples + +[source,ruby] +---- +# bad +arr[0] +arr[-1] + +# good +arr.first +arr.last +arr[0] = 2 +arr[0][-2] +---- + +=== References + +* #first-and-last + == Style/ArrayIntersect NOTE: Required Ruby version: 3.1 @@ -484,6 +637,15 @@ can be replaced by `array1.intersect?(array2)`. The `array1.intersect?(array2)` method is faster than `(array1 & array2).any?` and is more readable. +In cases like the following, compatibility is not ensured, +so it will not be detected when using block argument. + +[source,ruby] +---- +([1] & [1,2]).any? { |x| false } # => false +[1].intersect?([1,2]) { |x| false } # => true +---- + === Safety This cop cannot guarantee that `array1` and `array2` are @@ -656,6 +818,14 @@ f = File.open('file') File.open('file') do |f| # ... end + +# bad +f = Tempfile.open('temp') + +# good +Tempfile.open('temp') do |f| + # ... +end ---- == Style/BarePercentLiterals @@ -1372,9 +1542,9 @@ var.kind_of?(String) | Enabled | Yes -| Yes +| Yes (Unsafe) | 0.93 -| - +| 1.57 |=== Enforces the use of `Object#instance_of?` instead of class comparison @@ -1382,6 +1552,12 @@ for equality. `==`, `equal?`, and `eql?` custom method definitions are allowed by default. These are customizable with `AllowedMethods` option. +=== Safety + +This cop's autocorrection is unsafe because there is no guarantee that +the constant `Foo` exists when autocorrecting `var.class.name == 'Foo'` to +`var.instance_of?(Foo)`. + === Examples [source,ruby] @@ -1681,6 +1857,8 @@ array.delete_if(&:nil?) array.reject { |e| e.nil? } array.delete_if { |e| e.nil? } array.select { |e| !e.nil? } +array.grep_v(nil) +array.grep_v(NilClass) # good array.compact @@ -1750,6 +1928,7 @@ this cop may register false positives. # bad items.collect items.collect! +items.collect_concat items.inject items.detect items.find_all @@ -1758,6 +1937,7 @@ items.member? # good items.map items.map! +items.flat_map items.reduce items.find items.select @@ -1770,7 +1950,7 @@ items.include? | Name | Default value | Configurable values | PreferredMethods -| `{"collect"=>"map", "collect!"=>"map!", "inject"=>"reduce", "detect"=>"find", "find_all"=>"select", "member?"=>"include?"}` +| `{"collect"=>"map", "collect!"=>"map!", "collect_concat"=>"flat_map", "inject"=>"reduce", "detect"=>"find", "find_all"=>"select", "member?"=>"include?"}` | | MethodsAcceptingSymbol @@ -4682,13 +4862,25 @@ end |=== Enforces the use of a single string formatting utility. -Valid options include Kernel#format, Kernel#sprintf and String#%. +Valid options include `Kernel#format`, `Kernel#sprintf`, and `String#%`. -The detection of String#% cannot be implemented in a reliable +The detection of `String#%` cannot be implemented in a reliable manner for all cases, so only two scenarios are considered - if the first argument is a string literal and if the second argument is an array literal. +Autocorrection will be applied when using argument is a literal or known built-in conversion +methods such as `to_d`, `to_f`, `to_h`, `to_i`, `to_r`, `to_s`, and `to_sym` on variables, +provided that their return value is not an array. For example, when using `to_s`, +`'%s' % [1, 2, 3].to_s` can be autocorrected without any incompatibility: + +[source,ruby] +---- +'%s' % [1, 2, 3] #=> '1' +format('%s', [1, 2, 3]) #=> '[1, 2, 3]' +'%s' % [1, 2, 3].to_s #=> '[1, 2, 3]' +---- + === Examples ==== EnforcedStyle: format (default) @@ -5164,6 +5356,25 @@ end # good foo || raise('exception') if something ok + +# bad +define_method(:test) do + if something + work + end +end + +# good +define_method(:test) do + return unless something + + work +end + +# also good +define_method(:test) do + work if something +end ---- ==== AllowConsecutiveConditionals: false (default) @@ -5298,9 +5509,9 @@ EnforcedStyle. | Pending | Yes -| Yes +| Yes (Unsafe) | 1.10 -| 1.11 +| 1.55 |=== Checks the usage of pre-2.1 `Hash[args]` method of converting enumerables and @@ -5310,6 +5521,17 @@ Correction code from splat argument (`Hash[*ary]`) is not simply determined. For `Hash[*ary]` can be replaced with `ary.each_slice(2).to_h` but it will be complicated. So, `AllowSplatArgument` option is true by default to allow splat argument for simple code. +=== Safety + +This cop's autocorrection is unsafe because `ArgumentError` occurs +if the number of elements is odd: + +[source,ruby] +---- +Hash[[[1, 2], [3]]] #=> {1=>2, 3=>nil} +[[1, 2], [5]].to_h #=> wrong array length at 1 (expected 2, was 1) (ArgumentError) +---- + === Examples [source,ruby] @@ -5387,10 +5609,16 @@ but not fully resolve, this safety issue. ---- # bad hash.keys.each { |k| p k } -hash.values.each { |v| p v } +hash.each { |k, unused_value| p k } # good hash.each_key { |k| p k } + +# bad +hash.values.each { |v| p v } +hash.each { |unused_key, v| p v } + +# good hash.each_value { |v| p v } ---- @@ -7367,6 +7595,9 @@ Checks for unwanted parentheses in parameterless method calls. This cop can be customized allowed methods with `AllowedMethods`. By default, there are no methods to allowed. +NOTE: This cop allows the use of `it()` without arguments in blocks, +as in `0.times { it() }`, following `Lint/ItWithoutArgumentsInBlock` cop. + === Examples [source,ruby] @@ -7806,12 +8037,12 @@ defining `respond_to_missing?`. [source,ruby] ---- -#bad +# bad def method_missing(name, *args) # ... end -#good +# good def respond_to_missing?(name, include_private) # ... end @@ -9904,8 +10135,8 @@ allow(test_double).to receive(:a).and_return('b') |=== Checks for redundant dot before operator method call. -The target operator methods are `|`, `^`, `&`, `<=>`, `==`, `===`, `=~`, `>`, `>=`, `<`, -`<=`, `<<`, `>>`, `+`, `-`, `*`, `/`, `%`, `**`, `~`, `!`, `!=`, and `!~`. +The target operator methods are `|`, `^`, `&`, ``<=>``, `==`, `===`, `=~`, `>`, `>=`, `<`, +``<=``, `<<`, `>>`, `+`, `-`, `*`, `/`, `%`, `**`, `~`, `!`, `!=`, and `!~`. === Examples @@ -9969,6 +10200,10 @@ end | Array |=== +=== References + +* https://rubystyle.guide#keyword-arguments-vs-option-hashes + == Style/OptionalArguments |=== @@ -10678,7 +10913,7 @@ rand(1...7) | No | Yes (Unsafe) | 1.4 -| 1.40 +| 1.55 |=== Checks for a redundant argument passed to certain methods. @@ -10717,6 +10952,8 @@ This cop is unsafe because of the following limitations: array.join('') [1, 2, 3].join("") array.sum(0) +exit(true) +exit!(false) string.split(" ") "first\nsecond".split(" ") string.chomp("\n") @@ -10727,6 +10964,8 @@ A.foo(2) array.join [1, 2, 3].join array.sum +exit +exit! string.split "first second".split string.chomp @@ -10740,7 +10979,7 @@ A.foo | Name | Default value | Configurable values | Methods -| `{"join"=>"", "sum"=>0, "split"=>" ", "chomp"=>"\n", "chomp!"=>"\n"}` +| `{"join"=>"", "sum"=>0, "exit"=>true, "exit!"=>false, "split"=>" ", "chomp"=>"\n", "chomp!"=>"\n"}` | |=== @@ -11072,6 +11311,31 @@ module A end ---- +== Style/RedundantCurrentDirectoryInPath + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.53 +| - +|=== + +Checks for uses a redundant current directory in path. + +=== Examples + +[source,ruby] +---- +# bad +require_relative './path/to/feature' + +# good +require_relative 'path/to/feature' +---- + == Style/RedundantDoubleSplatHashBraces |=== @@ -11095,6 +11359,12 @@ do_something(**{foo: bar, baz: qux}) # good do_something(foo: bar, baz: qux) + +# bad +do_something(**{foo: bar, baz: qux}.merge(options)) + +# good +do_something(foo: bar, baz: qux, **options) ---- == Style/RedundantEach @@ -11155,20 +11425,23 @@ array.each_with_object { |v, o| do_something(v, o) } Checks for RuntimeError as the argument of raise/fail. -It checks for code like this: - === Examples [source,ruby] ---- -# Bad +# bad raise RuntimeError, 'message' - -# Bad raise RuntimeError.new('message') -# Good +# good raise 'message' + +# bad - message is not a string +raise RuntimeError, Object.new +raise RuntimeError.new(Object.new) + +# good +raise Object.new.to_s ---- === References @@ -11244,7 +11517,7 @@ ENV.fetch(:key, VALUE) === References -* https://github.com/JuanitoFatas/fast-ruby#hashfetch-with-argument-vs-hashfetch--block-code +* https://github.com/fastruby/fast-ruby#hashfetch-with-argument-vs-hashfetch--block-code == Style/RedundantFileExtensionInRequire @@ -11294,14 +11567,21 @@ require_relative '../foo.so' | Pending | Yes -| Yes +| Yes (Unsafe) | 1.52 -| - +| 1.57 |=== Identifies usages of `any?`, `empty?` or `none?` predicate methods chained to `select`/`filter`/`find_all` and change them to use predicate method instead. +=== Safety + +This cop's autocorrection is unsafe because `array.select.any?` evaluates all elements +through the `select` method, while `array.any?` uses short-circuit evaluation. +In other words, `array.select.any?` guarantees the evaluation of every element, +but `array.any?` does not necessarily evaluate all of them. + === Examples [source,ruby] @@ -11330,6 +11610,9 @@ arr.select { |x| x > 1 }.any?(&:odd?) ---- # good arr.select { |x| x > 1 }.many? + +# good +arr.select { |x| x > 1 }.present? ---- ==== AllCops:ActiveSupportExtensionsEnabled: true @@ -11341,6 +11624,12 @@ arr.select { |x| x > 1 }.many? # good arr.many? { |x| x > 1 } + +# bad +arr.select { |x| x > 1 }.present? + +# good +arr.any? { |x| x > 1 } ---- == Style/RedundantFreeze @@ -11720,6 +12009,52 @@ question = '"What did you say?"' * https://rubystyle.guide#percent-q +== Style/RedundantRegexpArgument + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.53 +| - +|=== + +Identifies places where argument can be replaced from +a deterministic regexp to a string. + +=== Examples + +[source,ruby] +---- +# bad +'foo'.byteindex(/f/) +'foo'.byterindex(/f/) +'foo'.gsub(/f/, 'x') +'foo'.gsub!(/f/, 'x') +'foo'.partition(/f/) +'foo'.rpartition(/f/) +'foo'.scan(/f/) +'foo'.split(/f/) +'foo'.start_with?(/f/) +'foo'.sub(/f/, 'x') +'foo'.sub!(/f/, 'x') + +# good +'foo'.byteindex('f') +'foo'.byterindex('f') +'foo'.gsub('f', 'x') +'foo'.gsub!('f', 'x') +'foo'.partition('f') +'foo'.rpartition('f') +'foo'.scan('f') +'foo'.split('f') +'foo'.start_with?('f') +'foo'.sub('f', 'x') +'foo'.sub!('f', 'x') +---- + == Style/RedundantRegexpCharacterClass |=== @@ -11869,11 +12204,16 @@ def test return something end -# good +# bad def test return something if something_else end +# good +def test + something if something_else +end + # good def test if x @@ -11943,7 +12283,8 @@ Note, with using explicit self you can only send messages with public or protected scope, you cannot send private messages this way. Note we allow uses of `self` with operators because it would be awkward -otherwise. +otherwise. Also allows the use of `self.it` without arguments in blocks, +as in `0.times { self.it }`, following `Lint/ItWithoutArgumentsInBlock` cop. === Examples @@ -12077,7 +12418,7 @@ after which only the first or last element is used. This cop is unsafe, because `sort...last` and `max` may not return the same element in all cases. -In an enumerable where there are multiple elements where `a <=> b == 0`, +In an enumerable where there are multiple elements where ``a <=> b == 0``, or where the transformation done by the `sort_by` block has the same result, `sort.last` and `max` (or `sort_by.last` and `max_by`) will return different elements. `sort.last` will return the last @@ -12602,9 +12943,13 @@ end | - |=== -Enforces consistency between 'return nil' and 'return'. +Enforces consistency between `return nil` and `return`. -Supported styles are: return, return_nil. +This cop is disabled by default. Because there seems to be a perceived semantic difference +between `return` and `return nil`. The former can be seen as just halting evaluation, +while the latter might be used when the return value is of specific concern. + +Supported styles are `return` and `return_nil`. === Examples @@ -12648,6 +12993,93 @@ end | `return`, `return_nil` |=== +== Style/ReturnNilInPredicateMethodDefinition + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes (Unsafe) +| 1.53 +| - +|=== + +Checks if `return` or `return nil` is used in predicate method definitions. + +=== Safety + +Autocorrection is marked as unsafe because the change of the return value +from `nil` to `false` could potentially lead to incompatibility issues. + +=== Examples + +[source,ruby] +---- +# bad +def foo? + return if condition + + do_something? +end + +# bad +def foo? + return nil if condition + + do_something? +end + +# good +def foo? + return false if condition + + do_something? +end +---- + +==== AllowedMethods: ['foo?'] + +[source,ruby] +---- +# good +def foo? + return if condition + + do_something? +end +---- + +==== AllowedPatterns: [/foo/] + +[source,ruby] +---- +# good +def foo? + return if condition + + do_something? +end +---- + +=== Configurable attributes + +|=== +| Name | Default value | Configurable values + +| AllowedMethods +| `[]` +| Array + +| AllowedPatterns +| `[]` +| Array +|=== + +=== References + +* https://rubystyle.guide#bool-methods-qmark + == Style/SafeNavigation NOTE: Required Ruby version: 2.3 @@ -12807,7 +13239,7 @@ Identifies usages of `shuffle.first`, === References -* https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code +* https://github.com/fastruby/fast-ruby#arrayshufflefirst-vs-arraysample-code == Style/SelectByRegexp @@ -13142,8 +13574,11 @@ explicit_receiver.raise | - |=== -Sometimes using dig method ends up with just a single -argument. In such cases, dig should be replaced with []. +Sometimes using `dig` method ends up with just a single +argument. In such cases, dig should be replaced with `[]`. + +Since replacing `hash&.dig(:key)` with `hash[:key]` could potentially lead to error, +calls to the `dig` method using safe navigation will be ignored. === Safety @@ -13226,6 +13661,47 @@ end | Array |=== +== Style/SingleLineDoEndBlock + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.57 +| - +|=== + +Checks for single-line `do`...`end` block. + +In practice a single line `do`...`end` is autocorrected when `EnforcedStyle: semantic` +in `Style/BlockDelimiters`. The autocorrection maintains the `do` ... `end` syntax to +preserve semantics and does not change it to `{`...`}` block. + +=== Examples + +[source,ruby] +---- +# bad +foo do |arg| bar(arg) end + +# good +foo do |arg| + bar(arg) +end + +# bad +->(arg) do bar(arg) end + +# good +->(arg) { bar(arg) } +---- + +=== References + +* https://rubystyle.guide#single-line-do-end-block + == Style/SingleLineMethods |=== @@ -13306,8 +13782,9 @@ NOTE: Required Ruby version: 2.6 | - |=== -Checks that arrays are sliced with endless ranges instead of -`ary[start..-1]` on Ruby 2.6+. +Checks that arrays are not sliced with the redundant `ary[0..-1]`, replacing it with `ary`, +and ensures arrays are sliced with endless ranges instead of `ary[start..-1]` on Ruby 2.6+, +and with beginless ranges instead of `ary[nil..end]` on Ruby 2.7+. === Safety @@ -13328,12 +13805,32 @@ sum[-3..] # Hangs forever [source,ruby] ---- # bad -items[1..-1] +items[0..-1] +items[0..nil] +items[0...nil] # good -items[1..] +items + +# bad +items[1..-1] # Ruby 2.6+ +items[1..nil] # Ruby 2.6+ + +# good +items[1..] # Ruby 2.6+ + +# bad +items[nil..42] # Ruby 2.7+ + +# good +items[..42] # Ruby 2.7+ +items[0..42] # Ruby 2.7+ ---- +=== References + +* https://rubystyle.guide#slicing-with-ranges + == Style/SoleNestedConditional |=== @@ -13915,7 +14412,7 @@ Checks if uses of quotes match the configured preference. | - |=== -Checks that quotes inside the string interpolation +Checks that quotes inside string, symbol, and regexp interpolations match the configured preference. === Examples @@ -13925,10 +14422,20 @@ match the configured preference. [source,ruby] ---- # bad -result = "Tests #{success ? "PASS" : "FAIL"}" +string = "Tests #{success ? "PASS" : "FAIL"}" +symbol = :"Tests #{success ? "PASS" : "FAIL"}" +heredoc = <<~TEXT + Tests #{success ? "PASS" : "FAIL"} +TEXT +regexp = /Tests #{success ? "PASS" : "FAIL"}/ # good -result = "Tests #{success ? 'PASS' : 'FAIL'}" +string = "Tests #{success ? 'PASS' : 'FAIL'}" +symbol = :"Tests #{success ? 'PASS' : 'FAIL'}" +heredoc = <<~TEXT + Tests #{success ? 'PASS' : 'FAIL'} +TEXT +regexp = /Tests #{success ? 'PASS' : 'FAIL'}/ ---- ==== EnforcedStyle: double_quotes @@ -13936,10 +14443,20 @@ result = "Tests #{success ? 'PASS' : 'FAIL'}" [source,ruby] ---- # bad -result = "Tests #{success ? 'PASS' : 'FAIL'}" +string = "Tests #{success ? 'PASS' : 'FAIL'}" +symbol = :"Tests #{success ? 'PASS' : 'FAIL'}" +heredoc = <<~TEXT + Tests #{success ? 'PASS' : 'FAIL'} +TEXT +regexp = /Tests #{success ? 'PASS' : 'FAIL'}/ # good -result = "Tests #{success ? "PASS" : "FAIL"}" +string = "Tests #{success ? "PASS" : "FAIL"}" +symbol = :"Tests #{success ? "PASS" : "FAIL"}" +heredoc = <<~TEXT + Tests #{success ? "PASS" : "FAIL"} +TEXT +regexp = /Tests #{success ? "PASS" : "FAIL"}/ ---- === Configurable attributes @@ -14059,6 +14576,37 @@ end * https://rubystyle.guide#no-extend-struct-new +== Style/SuperWithArgsParentheses + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.58 +| - +|=== + +Enforces the presence of parentheses in `super` containing arguments. + +`super` is a keyword and is provided as a distinct cop from those designed for method call. + +=== Examples + +[source,ruby] +---- +# bad +super name, age + +# good +super(name, age) +---- + +=== References + +* https://rubystyle.guide#super-with-args + == Style/SwapValues |=== @@ -14132,6 +14680,15 @@ array of 2 or fewer elements. # bad [:foo, :bar, :baz] + +# bad (contains spaces) +%i[foo\ bar baz\ quux] + +# bad (contains [] with spaces) +%i[foo \[ \]] + +# bad (contains () with spaces) +%i(foo \( \)) ---- ==== EnforcedStyle: brackets @@ -14235,6 +14792,42 @@ call(&:bar) # ArgumentError: wrong number of arguments (given 1, expected 0) ---- +It is also unsafe because `Symbol#to_proc` does not work with +`protected` methods which would otherwise be accessible. + +For example: + +[source,ruby] +---- +class Box + def initialize + @secret = rand + end + + def normal_matches?(*others) + others.map { |other| other.secret }.any?(secret) + end + + def symbol_to_proc_matches?(*others) + others.map(&:secret).any?(secret) + end + + protected + + attr_reader :secret +end + +boxes = [Box.new, Box.new] +Box.new.normal_matches?(*boxes) +# => false +boxes.first.normal_matches?(*boxes) +# => true +Box.new.symbol_to_proc_matches?(*boxes) +# => NoMethodError: protected method `secret' called for # +boxes.first.symbol_to_proc_matches?(*boxes) +# => NoMethodError: protected method `secret' called for # +---- + === Examples [source,ruby] @@ -15727,6 +16320,42 @@ array of 2 or fewer elements. * https://rubystyle.guide#percent-w +== Style/YAMLFileRead + +|=== +| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed + +| Pending +| Yes +| Yes +| 1.53 +| - +|=== + +Checks for the use of `YAML.load`, `YAML.safe_load`, and `YAML.parse` with +`File.read` argument. + +NOTE: `YAML.safe_load_file` was introduced in Ruby 3.0. + +=== Examples + +[source,ruby] +---- +# bad +YAML.load(File.read(path)) +YAML.parse(File.read(path)) + +# good +YAML.load_file(path) +YAML.parse_file(path) + +# bad +YAML.safe_load(File.read(path)) # Ruby 3.0 and newer + +# good +YAML.safe_load_file(path) # Ruby 3.0 and newer +---- + == Style/YodaCondition |=== @@ -15875,25 +16504,26 @@ have the same result if reversed. === Examples -==== SupportedOperators: ['*', '+', '&''] +==== SupportedOperators: ['*', '+', '&', '|', '^'] (default) [source,ruby] ---- # bad -1 + x 10 * y +1 + x 1 & z +1 | x +1 ^ x 1 + CONST # good -60 * 24 -x + 1 y * 10 +x + 1 z & 1 +x | 1 +x ^ 1 CONST + 1 - -# good -1 | x +60 * 24 ---- === Configurable attributes diff --git a/docs/modules/ROOT/pages/development.adoc b/docs/modules/ROOT/pages/development.adoc index b7bf01e1dfc..a9789204a9a 100644 --- a/docs/modules/ROOT/pages/development.adoc +++ b/docs/modules/ROOT/pages/development.adoc @@ -15,13 +15,10 @@ Use the bundled rake task `new_cop` to generate a cop template: [source,sh] ---- $ bundle exec rake 'new_cop[Department/Name]' -Files created: - - lib/rubocop/cop/department/name.rb - - spec/rubocop/cop/department/name_spec.rb -File modified: - - `require_relative 'rubocop/cop/department/name'` added into lib/rubocop.rb - - A configuration for the cop is added into config/default.yml - +[create] lib/rubocop/cop/department/name.rb +[create] spec/rubocop/cop/department/name_spec.rb +[modify] lib/rubocop.rb - `require_relative 'rubocop/cop/department/name'` was injected. +[modify] A configuration for the cop is added into config/default.yml. Do 4 steps: 1. Modify the description of Department/Name in config/default.yml 2. Implement your new cop in the generated file! diff --git a/docs/modules/ROOT/pages/extensions.adoc b/docs/modules/ROOT/pages/extensions.adoc index 4af0b7db93c..0377f1d4f0c 100644 --- a/docs/modules/ROOT/pages/extensions.adoc +++ b/docs/modules/ROOT/pages/extensions.adoc @@ -216,14 +216,14 @@ Normally, RuboCop extracts one Ruby code from one Ruby file, however there are m Ruby extractor must be a callable object that takes a `RuboCop::ProcessedSource` and returns an `Array` of `Hash` that contains Ruby source codes and their offsets from original source code, or returns `nil` for unrelated file. [source,ruby] ---- +---- ruby_extractor.call(processed_source) ---- +---- An example returned value from a Ruby extractor would be as follows: -[source] ---- +[source,ruby] +---- [ { offset: 2, @@ -232,16 +232,16 @@ An example returned value from a Ruby extractor would be as follows: { offset: 10, processed_source: # - }, + } ] ---- +---- On the extension side, the code would be something like this: [source,ruby] ---- +---- RuboCop::Runner.ruby_extractors.unshift(ruby_extractor) ---- +---- `RuboCop::Runners.ruby_extractors` is processed from the beginning and ends when one of them returns a non-nil value. By default, there is a Ruby extractor that returns the given Ruby source code with offset 0, so you can unshift any Ruby extractor before it. diff --git a/docs/modules/ROOT/pages/formatters.adoc b/docs/modules/ROOT/pages/formatters.adoc index ab8626dcdc4..eebe99c1021 100644 --- a/docs/modules/ROOT/pages/formatters.adoc +++ b/docs/modules/ROOT/pages/formatters.adoc @@ -305,17 +305,17 @@ cops and the number of offenses found for each by running: ---- $ rubocop --format offenses -36 Layout/LineLength -18 Style/StringLiterals +36 Layout/LineLength [Safe Correctable] +18 Style/StringLiterals [Safe Correctable] 13 Style/Documentation -10 Style/ExpandPathArguments -8 Style/EmptyMethod -6 Layout/IndentationConsistency +10 Style/ExpandPathArguments [Safe Correctable] +8 Style/EmptyMethod [Safe Correctable] +6 Layout/IndentationConsistency [Safe Correctable] 4 Lint/SuppressedException -3 Layout/EmptyLinesAroundAccessModifier -2 Layout/ExtraSpacing -1 Layout/AccessModifierIndentation -1 Style/ClassAndModuleChildren +3 Layout/EmptyLinesAroundAccessModifier [Safe Correctable] +2 Layout/ExtraSpacing [Safe Correctable] +1 Layout/AccessModifierIndentation [Safe Correctable] +1 Style/ClassAndModuleChildren [Unsafe Correctable] -- 102 Total in 31 files ---- diff --git a/docs/modules/ROOT/pages/installation.adoc b/docs/modules/ROOT/pages/installation.adoc index c06fb766f7b..b72d7cf5ce3 100644 --- a/docs/modules/ROOT/pages/installation.adoc +++ b/docs/modules/ROOT/pages/installation.adoc @@ -22,7 +22,7 @@ in your `Gemfile`: [source,rb] ---- -gem 'rubocop', '~> 1.52', require: false +gem 'rubocop', '~> 1.60', require: false ---- .A Modular RuboCop diff --git a/docs/modules/ROOT/pages/integration_with_other_tools.adoc b/docs/modules/ROOT/pages/integration_with_other_tools.adoc index ea926809fe6..f151bb0d275 100644 --- a/docs/modules/ROOT/pages/integration_with_other_tools.adoc +++ b/docs/modules/ROOT/pages/integration_with_other_tools.adoc @@ -27,14 +27,15 @@ has designed to address this problem and provide lightning fast editor integrati === LSP -https://microsoft.github.io/language-server-protocol/[The Language Server Protocol] is the modern standard for providing cross-editor support for various programming languages. The following Ruby LSP servers are using RuboCop internally to provide -code linting functionality: +https://microsoft.github.io/language-server-protocol/[The Language Server Protocol] is the modern standard for providing cross-editor support for various programming languages. The RuboCop xref:usage/lsp.adoc[LSP] functionality has designed to provide built-in language server. The following is a LSP client for interacting with the built-in server: + +- https://github.com/rubocop/vscode-rubocop[vscode-rubocop] + +And the following Ruby LSP servers are using RuboCop internally to provide code linting functionality: - https://github.com/Shopify/ruby-lsp[ruby-lsp] - https://solargraph.org/[Solargraph] -And the RuboCop xref:usage/lsp.adoc[LSP] functionality has designed to provide built-in language server. - === Emacs https://github.com/rubocop/rubocop-emacs[rubocop.el] is a simple @@ -47,9 +48,9 @@ RuboCop and uses it by default when available. === Vim RuboCop is supported by -https://github.com/scrooloose/syntastic[syntastic], +https://github.com/vim-syntastic/syntastic[syntastic], https://github.com/neomake/neomake[neomake], -and https://github.com/w0rp/ale[ale]. +and https://github.com/dense-analysis/ale[ale]. There is also the https://github.com/ngmy/vim-rubocop[vim-rubocop] plugin. @@ -59,9 +60,11 @@ Helix supports Solargraph natively to provide LSP features. For formatting suppo === Sublime Text -If you're a ST user you might find the -https://github.com/pderichs/sublime_rubocop[Sublime RuboCop plugin] -useful. +For ST you might find the +https://github.com/SublimeLinter/SublimeLinter-rubocop[SublimeLinter-rubocop] or the +https://github.com/pderichs/sublime_rubocop[Sublime RuboCop] plugin useful. + +You may also consider using one of the LSP servers mentioned above which utilize RuboCop by using the https://github.com/sublimelsp/LSP[Sublime-LSP] plugin and follow its https://lsp.sublimetext.io/language_servers/#ruby-ruby-on-rails[documentation] for configuration. === Brackets @@ -78,7 +81,7 @@ Installation instructions can be found https://github.com/mrdougal/textmate2-rub === Atom The https://github.com/AtomLinter/linter-rubocop[linter-rubocop] plugin for Atom's -https://github.com/AtomLinter/Linter[linter] runs RuboCop and highlights the offenses in Atom. +https://github.com/steelbrain/linter[linter] runs RuboCop and highlights the offenses in Atom. === LightTable @@ -102,7 +105,7 @@ RuboCop integration for your favorite editor. == Git pre-commit hook integration with overcommit -https://github.com/brigade/overcommit[overcommit] is a fully configurable and +https://github.com/sds/overcommit[overcommit] is a fully configurable and extendable Git commit hook manager. To use RuboCop with overcommit, add the following to your `.overcommit.yml` file: @@ -145,21 +148,21 @@ entries in `additional_dependencies`: If you're fond of https://github.com/guard/guard[Guard] you might like -https://github.com/yujinakayama/guard-rubocop[guard-rubocop]. It +https://github.com/rubocop/guard-rubocop[guard-rubocop]. It allows you to automatically check Ruby code style with RuboCop when files are modified. == Mega-Linter integration -You can use https://nvuillam.github.io/mega-linter/[Mega-Linter] +You can use https://megalinter.io/latest/[Mega-Linter] to run RuboCop automatically on every PR, and also lint all file types detected in your repository. Please follow the -https://nvuillam.github.io/mega-linter/installation[installation instructions] +https://megalinter.io/latest/installation[installation instructions] to activate RuboCop without any additional configuration. -https://nvuillam.github.io/mega-linter/flavors/ruby/[Mega-Linter's Ruby flavor] +https://megalinter.io/latest/flavors/ruby/[Mega-Linter's Ruby flavor] is optimized for Ruby linting. == Rake integration diff --git a/docs/modules/ROOT/pages/usage/basic_usage.adoc b/docs/modules/ROOT/pages/usage/basic_usage.adoc index 1cae5d09664..9380783387e 100644 --- a/docs/modules/ROOT/pages/usage/basic_usage.adoc +++ b/docs/modules/ROOT/pages/usage/basic_usage.adoc @@ -168,6 +168,9 @@ $ rubocop --only Rails/Blank,Layout/HeredocIndentation,Naming/FileName | `-D/--[no-]display-cop-names` | Displays cop names in offense messages. Default is true. +| `--display-time` +| Display elapsed time in seconds. + | `--display-only-fail-level-offenses` | Only output offense messages at the specified `--fail-level` or above. @@ -196,7 +199,7 @@ $ rubocop --only Rails/Blank,Layout/HeredocIndentation,Naming/FileName | Inspect files in order of modification time and stops after first file with offenses. | `--fail-level` -| Minimum xref:configuration.adoc#severity[severity] for exit with error code. Full severity name or upper case initial can be given. Normally, autocorrected offenses are ignored. Use `A` or `autocorrect` if you'd like them to trigger failure. +| Minimum xref:configuration.adoc#severity[severity] for exit with error code. Full severity name or upper case initial can be given. Normally, autocorrected offenses are ignored. Use `A` or `autocorrect` if you'd like any autocorrectable offense to trigger failure, regardless of severity. | `--force-exclusion` | Force excluding files specified in the configuration `Exclude` even if they are explicitly passed as arguments. @@ -267,6 +270,9 @@ $ rubocop --only Rails/Blank,Layout/HeredocIndentation,Naming/FileName | `-s/--stdin` | Pipe source from STDIN. This is useful for editor integration. Takes one argument, a path, relative to the root of the project. RuboCop will use this path to determine which cops are enabled (via eg. Include/Exclude), and so that certain cops like Naming/FileName can be checked. +| `--editor-mode` +| Optimize real-time feedback in editors, adjusting behaviors for editing experience. Editors that run RuboCop directly (e.g., by shelling out) encounter the same issues as with `--lsp`. This option is designed for such editors. + | `-S/--display-style-guide` | Display style guide URLs in offense messages. diff --git a/docs/modules/ROOT/pages/usage/lsp.adoc b/docs/modules/ROOT/pages/usage/lsp.adoc index b89b9c0ccd9..0ca0f0c6f76 100644 --- a/docs/modules/ROOT/pages/usage/lsp.adoc +++ b/docs/modules/ROOT/pages/usage/lsp.adoc @@ -7,29 +7,22 @@ https://microsoft.github.io/language-server-protocol/[The Language Server Protoc This feature enables extremely fast interactions through the LSP. Offense detection and autocorrection are performed in real-time by editors and IDEs using the language server. -The xref:usage/lsp.adoc[Server Mode] is primarily used to speed up RuboCop runs in the terminal. +The xref:usage/server.adoc[Server Mode] is primarily used to speed up RuboCop runs in the terminal. Therefore, if you want real-time feedback from RuboCop in your editor or IDE, opting to use this language server instead of the server mode will not only provide a fast and efficient solution, but also offer a straightforward setup for integration. -== Run as a Language Server - -Run `rubocop --lsp` command from LSP client. - -When the language server is started, the command displays the language server's PID: +== Examples of LSP Client -```console -$ ps aux | grep rubocop -user 17414 0.0 0.2 5557716 144376 ?? Ss 4:48PM 0:02.13 /Users/user/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/bin/rubocop --lsp -``` +Here are examples of LSP client configurations. -== Autocorrection +=== VS Code -The language server supports `textDocument/formatting` method and is autocorrectable. The autocorrection is safe. +https://github.com/rubocop/vscode-rubocop[vscode-rubocop] integrates RuboCop into VS Code. -== Examples of LSP Client +You can install this VS Code extension from the https://marketplace.visualstudio.com/items?itemName=rubocop.vscode-rubocop[Visual Studio Marketplace]. -Here are examples of LSP client configurations. +For VS Code-based IDEs like VSCodium or Eclipse Theia, the extension can be installed from the https://open-vsx.org/extension/rubocop/vscode-rubocop[Open VSX Registry]. === Emacs (Eglot) @@ -53,3 +46,225 @@ Below is an example of additional setting for autocorrecting on save: If you run into problems, first use "M-x eglot-reconnect" to reconnect to the language server. See Eglot's official documentation for more information. + +=== Emacs (LSP Mode) + +https://github.com/emacs-lsp/lsp-mode[LSP Mode] is an Emacs client/library for the Language Server Protocol. + +You can get the new `lsp-mode` package from https://melpa.org/#/lsp-mode[MELPA]. + +See LSP Mode official documentation for more information: +https://emacs-lsp.github.io/lsp-mode/page/lsp-rubocop/ + +=== Vim and Neovim (coc.nvim) + +https://github.com/neoclide/coc.nvim[coc.nvim] is an extension host for Vim and Neovim, powered by Node.js. +It allows the loading of extensions similar to VSCode and provides hosting for language servers. + +Add the following to your coc.nvim configuration file. For example, in Vim, it would be `~/.vim/coc-settings.json`, +and in Neovim, it would be `~/.config/nvim/coc-settings.json`: + +```json +{ + "languageserver": { + "rubocop": { + "command": "bundle", + "args" : ["exec", "rubocop", "--lsp"], + "filetypes": ["ruby"], + "rootPatterns": [".git", "Gemfile"], + "requireRootPattern": true + } + } +} +``` + +Below is an example of additional setting for autocorrecting on save: + +```json +{ + "coc.preferences.formatOnSave": true +} +``` + +See coc.nvim's official documentation for more information. + +=== Neovim (nvim-lspconfig) + +https://github.com/neovim/nvim-lspconfig[nvim-lspconfig] provides quickstart configs for Neovim's LSP. + +Add the following to your nvim-lspconfig configuration file (e.g. `~/.config/nvim/init.lua`): + +```lua +vim.opt.signcolumn = "yes" +vim.api.nvim_create_autocmd("FileType", { + pattern = "ruby", + callback = function() + vim.lsp.start { + name = "rubocop", + cmd = { "bundle", "exec", "rubocop", "--lsp" }, + } + end, +}) +``` + +Below is an example of additional setting for autocorrecting on save: + +```lua +vim.api.nvim_create_autocmd("BufWritePre", { + pattern = "*.rb", + callback = function() + vim.lsp.buf.format() + end, +}) +``` + +See nvim-lspconfig's official documentation for more information. + +=== Helix + +https://github.com/helix-editor/helix[Helix] is a post-modern modal text editor with built-in language server support. + +Add the following to your Helix language configuration file (e.g. `~/.config/helix/languages.toml`): + +Helix 23.10 or later: + +```toml +[language-server.rubocop] +command = "bundle" +args = ["exec", "rubocop", "--lsp"] + +[[language]] +name = "ruby" +auto-format = true +language-servers = [ + { name = "rubocop" } +] +``` + +Before Helix 23.10 or earlier: + +```toml +[[language]] +name = "ruby" +language-server = { command = "bundle", args = ["exec", "rubocop", "--lsp"] } +auto-format = true +``` + +See Helix's official documentation for more information: +https://docs.helix-editor.com/languages.html + +=== Sublime Text + +For https://www.sublimetext.com/[Sublime Text] LSP support is available through the https://github.com/sublimelsp/LSP[Sublime-LSP] plugin. +Add the following to its settings (accessible via `Preferences → Package Settings → LSP → Settings`) to enable RuboCop: + +```json +{ + "clients": { + "rubocop": { + "enabled": true, + "command": ["bundle", "exec", "rubocop", "--lsp"], + "selector": "source.ruby | text.html.ruby | text.html.rails", + }, + }, +} +``` + +== Autocorrection + +The language server supports `textDocument/formatting` method and is autocorrectable. The autocorrection is safe by default (`rubocop -a`). + +LSP client can switch to unsafe autocorrection (`rubocop -A`) by passing the following `safeAutocorrect` parameter in the `initialize` request. + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "initialize", + "params": { + "initializationOptions": { + "safeAutocorrect": false + } + } +} +``` + +For detailed instructions on setting the parameter, please refer to the configuration methods of your LSP client. + +NOTE: The `safeAutocorrect` parameter was introduced in RuboCop 1.54. + +As execute commands in the `workspace/executeCommand` parameters, it provides `rubocop.formatAutocorrects` for safe autocorrections (`rubocop -a`) and +`rubocop.formatAutocorrectsAll` for unsafe autocorrections (`rubocop -A`). +These parameters take precedence over the `initializationOptions:safeAutocorrect` value set in the `initialize` parameter. + +NOTE: The `rubocop.formatAutocorrectsAll` execute command was introduced in RuboCop 1.56. + +== Lint Mode + +LSP client can run lint cops by passing the following `lintMode` parameter in the `initialize` request +if you only want to enable the feature as a linter like `ruby -w`: + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "initialize", + "params": { + "initializationOptions": { + "lintMode": true + } + } +} +``` + +Furthermore, enabling autocorrect in a LSP client at the time of saving equates to the effect of `rubocop -l` option. + +For detailed instructions on setting the parameter, please refer to the configuration methods of your LSP client. + +NOTE: The `lintMode` parameter was introduced in RuboCop 1.55. + +== Layout Mode + +LSP client can run layout cops by passing the following `layoutMode` parameter in the `initialize` request +if you only want to enable the feature as a formatter: + +```json +{ + "jsonrpc": "2.0", + "id": 42, + "method": "initialize", + "params": { + "initializationOptions": { + "layoutMode": true + } + } +} +``` + +Furthermore, enabling autocorrect in a LSP client at the time of saving equates to the effect of `rubocop -x` option. + +For detailed instructions on setting the parameter, please refer to the configuration methods of your LSP client. + +NOTE: The `layoutMode` parameter was introduced in RuboCop 1.55. + +== Run as a Language Server + +Run `rubocop --lsp` command from LSP client. + +When the language server is started, the command displays the language server's PID: + +```console +$ ps aux | grep rubocop +user 17414 0.0 0.2 5557716 144376 ?? Ss 4:48PM 0:02.13 /Users/user/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/bin/rubocop --lsp +``` + +NOTE: `rubocop --lsp` is for starting LSP client, so users don't manually execute it. + +== Language Server Development + +RuboCop provides APIs for developers of original language server or tools analogous to LSP, using RuboCop as the backend, instead of the RuboCop's built-in LSP. + +- `RuboCop::LSP.enable` enables LSP mode, customizing for LSP-specific features such as autocorrection and short offense message. +- `RuboCop::LSP.disable` disables LSP mode, which can be particularly useful for testing. + +When implementing custom cops, `RuboCop::LSP.enabled?` can be used to achieve behavior that considers these states. diff --git a/lib/rubocop.rb b/lib/rubocop.rb index ee161a62a56..b5f498d713e 100644 --- a/lib/rubocop.rb +++ b/lib/rubocop.rb @@ -139,6 +139,7 @@ require_relative 'rubocop/cop/mixin/def_node' # relies on visibility_help require_relative 'rubocop/cop/utils/format_string' +require_relative 'rubocop/cop/utils/regexp_ranges' require_relative 'rubocop/cop/migration/department_name' @@ -161,6 +162,7 @@ require_relative 'rubocop/cop/correctors/unused_arg_corrector' require_relative 'rubocop/cop/bundler/duplicated_gem' +require_relative 'rubocop/cop/bundler/duplicated_group' require_relative 'rubocop/cop/bundler/gem_comment' require_relative 'rubocop/cop/bundler/gem_filename' require_relative 'rubocop/cop/bundler/gem_version' @@ -330,12 +332,15 @@ require_relative 'rubocop/cop/lint/ineffective_access_modifier' require_relative 'rubocop/cop/lint/inherit_exception' require_relative 'rubocop/cop/lint/interpolation_check' +require_relative 'rubocop/cop/lint/it_without_arguments_in_block' require_relative 'rubocop/cop/lint/lambda_without_literal_block' require_relative 'rubocop/cop/lint/literal_as_condition' +require_relative 'rubocop/cop/lint/literal_assignment_in_condition' require_relative 'rubocop/cop/lint/literal_in_interpolation' require_relative 'rubocop/cop/lint/loop' require_relative 'rubocop/cop/lint/missing_cop_enable_directive' require_relative 'rubocop/cop/lint/missing_super' +require_relative 'rubocop/cop/lint/mixed_case_range' require_relative 'rubocop/cop/lint/mixed_regexp_capture_types' require_relative 'rubocop/cop/lint/multiple_comparison' require_relative 'rubocop/cop/lint/nested_method_definition' @@ -358,6 +363,7 @@ require_relative 'rubocop/cop/lint/redundant_cop_disable_directive' require_relative 'rubocop/cop/lint/redundant_cop_enable_directive' require_relative 'rubocop/cop/lint/redundant_dir_glob_sort' +require_relative 'rubocop/cop/lint/redundant_regexp_quantifiers' require_relative 'rubocop/cop/lint/redundant_require_statement' require_relative 'rubocop/cop/lint/redundant_safe_navigation' require_relative 'rubocop/cop/lint/redundant_splat_expansion' @@ -450,6 +456,7 @@ require_relative 'rubocop/cop/style/and_or' require_relative 'rubocop/cop/style/arguments_forwarding' require_relative 'rubocop/cop/style/array_coercion' +require_relative 'rubocop/cop/style/array_first_last' require_relative 'rubocop/cop/style/array_intersect' require_relative 'rubocop/cop/style/array_join' require_relative 'rubocop/cop/style/ascii_comments' @@ -562,6 +569,7 @@ require_relative 'rubocop/cop/style/redundant_array_constructor' require_relative 'rubocop/cop/style/redundant_assignment' require_relative 'rubocop/cop/style/redundant_constant_base' +require_relative 'rubocop/cop/style/redundant_current_directory_in_path' require_relative 'rubocop/cop/style/redundant_double_splat_hash_braces' require_relative 'rubocop/cop/style/redundant_each' require_relative 'rubocop/cop/style/redundant_fetch_block' @@ -570,10 +578,12 @@ require_relative 'rubocop/cop/style/redundant_heredoc_delimiter_quotes' require_relative 'rubocop/cop/style/redundant_initialize' require_relative 'rubocop/cop/style/redundant_line_continuation' +require_relative 'rubocop/cop/style/redundant_regexp_argument' require_relative 'rubocop/cop/style/redundant_regexp_constructor' require_relative 'rubocop/cop/style/redundant_self_assignment' require_relative 'rubocop/cop/style/redundant_self_assignment_branch' require_relative 'rubocop/cop/style/require_order' +require_relative 'rubocop/cop/style/single_line_do_end_block' require_relative 'rubocop/cop/style/sole_nested_conditional' require_relative 'rubocop/cop/style/static_class' require_relative 'rubocop/cop/style/map_compact_with_conditional_block' @@ -648,6 +658,7 @@ require_relative 'rubocop/cop/style/rescue_modifier' require_relative 'rubocop/cop/style/rescue_standard_error' require_relative 'rubocop/cop/style/return_nil' +require_relative 'rubocop/cop/style/return_nil_in_predicate_method_definition' require_relative 'rubocop/cop/style/safe_navigation' require_relative 'rubocop/cop/style/sample' require_relative 'rubocop/cop/style/select_by_regexp' @@ -670,6 +681,7 @@ require_relative 'rubocop/cop/style/string_methods' require_relative 'rubocop/cop/style/strip' require_relative 'rubocop/cop/style/struct_inheritance' +require_relative 'rubocop/cop/style/super_with_args_parentheses' require_relative 'rubocop/cop/style/swap_values' require_relative 'rubocop/cop/style/symbol_array' require_relative 'rubocop/cop/style/symbol_literal' @@ -694,6 +706,7 @@ require_relative 'rubocop/cop/style/while_until_do' require_relative 'rubocop/cop/style/while_until_modifier' require_relative 'rubocop/cop/style/word_array' +require_relative 'rubocop/cop/style/yaml_file_read' require_relative 'rubocop/cop/style/yoda_condition' require_relative 'rubocop/cop/style/yoda_expression' require_relative 'rubocop/cop/style/zero_length_predicate' diff --git a/lib/rubocop/cli.rb b/lib/rubocop/cli.rb index e595149cbac..18b818bfabf 100644 --- a/lib/rubocop/cli.rb +++ b/lib/rubocop/cli.rb @@ -11,8 +11,8 @@ class CLI STATUS_ERROR = 2 STATUS_INTERRUPTED = Signal.list['INT'] + 128 DEFAULT_PARALLEL_OPTIONS = %i[ - color debug display_style_guide display_time display_only_fail_level_offenses - display_only_failed except extra_details fail_level fix_layout format + color config debug display_style_guide display_time display_only_fail_level_offenses + display_only_failed editor_mode except extra_details fail_level fix_layout format ignore_disable_comments lint only only_guide_cops require safe autocorrect safe_autocorrect autocorrect_all ].freeze @@ -151,6 +151,7 @@ def parallel_by_default! def act_on_options set_options_to_config_loader + handle_editor_mode @config_store.options_config = @options[:config] if @options[:config] @config_store.force_default_config! if @options[:force_default_config] @@ -174,6 +175,10 @@ def set_options_to_config_loader ConfigLoader.ignore_unrecognized_cops = @options[:ignore_unrecognized_cops] end + def handle_editor_mode + RuboCop::LSP.enable if @options[:editor_mode] + end + # rubocop:disable Metrics/CyclomaticComplexity def handle_exiting_options return unless Options::EXITING_OPTIONS.any? { |o| @options.key? o } diff --git a/lib/rubocop/cli/command/auto_generate_config.rb b/lib/rubocop/cli/command/auto_generate_config.rb index 8b5954bea64..91066ed1d1d 100644 --- a/lib/rubocop/cli/command/auto_generate_config.rb +++ b/lib/rubocop/cli/command/auto_generate_config.rb @@ -10,6 +10,7 @@ class AutoGenerateConfig < Base AUTO_GENERATED_FILE = '.rubocop_todo.yml' YAML_OPTIONAL_DOC_START = /\A---(\s+#|\s*\z)/.freeze + PLACEHOLDER = '###rubocop:inherit_here' PHASE_1 = 'Phase 1 of 2: run Layout/LineLength cop' PHASE_2 = 'Phase 2 of 2: run all cops' @@ -125,15 +126,19 @@ def add_inheritance_from_auto_generated_file(config_file) def existing_configuration(config_file) File.read(config_file, encoding: Encoding::UTF_8) - .sub(/^inherit_from: *[^\n]+/, '') - .sub(/^inherit_from: *(\n *- *[^\n]+)+/, '') + .sub(/^inherit_from: *[^\n]+/, PLACEHOLDER) + .sub(/^inherit_from: *(\n *- *[^\n]+)+/, PLACEHOLDER) end def write_config_file(file_name, file_string, rubocop_yml_contents) lines = /\S/.match?(rubocop_yml_contents) ? rubocop_yml_contents.split("\n", -1) : [] - doc_start_index = lines.index { |line| YAML_OPTIONAL_DOC_START.match?(line) } || -1 - lines.insert(doc_start_index + 1, "inherit_from:#{file_string}\n") - File.write(file_name, lines.join("\n")) + unless rubocop_yml_contents&.include?(PLACEHOLDER) + doc_start_index = lines.index { |line| YAML_OPTIONAL_DOC_START.match?(line) } || -1 + lines.insert(doc_start_index + 1, PLACEHOLDER) + end + File.write(file_name, lines.join("\n") + .sub(/#{PLACEHOLDER}\n*/o, "inherit_from:#{file_string}\n\n") + .sub(/\n\n+\Z/, "\n")) end def relative_path_to_todo_from_options_config diff --git a/lib/rubocop/cli/command/lsp.rb b/lib/rubocop/cli/command/lsp.rb index ff208a4c07c..c4eb17103e1 100644 --- a/lib/rubocop/cli/command/lsp.rb +++ b/lib/rubocop/cli/command/lsp.rb @@ -7,11 +7,11 @@ class CLI module Command # Start Language Server Protocol of RuboCop. # @api private - class Lsp < Base + class LSP < Base self.command_name = :lsp def run - RuboCop::Lsp::Server.new(@config_store).start + RuboCop::LSP::Server.new(@config_store).start end end end diff --git a/lib/rubocop/config.rb b/lib/rubocop/config.rb index dcac75dcee2..76625303177 100644 --- a/lib/rubocop/config.rb +++ b/lib/rubocop/config.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'pathname' - # FIXME: Moving Rails department code to RuboCop Rails will remove # the following rubocop:disable comment. # rubocop:disable Metrics/ClassLength diff --git a/lib/rubocop/config_finder.rb b/lib/rubocop/config_finder.rb index c990969f197..96a9df2dd7d 100644 --- a/lib/rubocop/config_finder.rb +++ b/lib/rubocop/config_finder.rb @@ -17,8 +17,8 @@ class << self attr_writer :project_root def find_config_path(target_dir) - find_project_dotfile(target_dir) || find_user_dotfile || find_user_xdg_config || - DEFAULT_FILE + find_project_dotfile(target_dir) || find_project_root_dot_config || + find_user_dotfile || find_user_xdg_config || DEFAULT_FILE end # Returns the path RuboCop inferred as the root of the project. No file @@ -41,19 +41,29 @@ def find_project_dotfile(target_dir) find_file_upwards(DOTFILE, target_dir, project_root) end + def find_project_root_dot_config + return unless project_root + + dotfile = File.join(project_root, '.config', DOTFILE) + return dotfile if File.exist?(dotfile) + + xdg_config = File.join(project_root, '.config', 'rubocop', XDG_CONFIG) + xdg_config if File.exist?(xdg_config) + end + def find_user_dotfile return unless ENV.key?('HOME') file = File.join(Dir.home, DOTFILE) - return file if File.exist?(file) + file if File.exist?(file) end def find_user_xdg_config xdg_config_home = expand_path(ENV.fetch('XDG_CONFIG_HOME', '~/.config')) xdg_config = File.join(xdg_config_home, 'rubocop', XDG_CONFIG) - return xdg_config if File.exist?(xdg_config) + xdg_config if File.exist?(xdg_config) end def expand_path(path) diff --git a/lib/rubocop/config_loader.rb b/lib/rubocop/config_loader.rb index d6a81011006..b7c6eee5460 100644 --- a/lib/rubocop/config_loader.rb +++ b/lib/rubocop/config_loader.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require 'erb' -require 'pathname' require 'yaml' require_relative 'config_finder' diff --git a/lib/rubocop/config_loader_resolver.rb b/lib/rubocop/config_loader_resolver.rb index 045171950fb..5e433c3d35e 100644 --- a/lib/rubocop/config_loader_resolver.rb +++ b/lib/rubocop/config_loader_resolver.rb @@ -33,7 +33,7 @@ def resolve_inheritance(path, hash, file, debug) # rubocop:disable Metrics/Metho inherit_mode: determine_inherit_mode(hash, k)) end hash[k] = v - fix_include_paths(base_config.loaded_path, hash, k, v) if v.key?('Include') + fix_include_paths(base_config.loaded_path, hash, path, k, v) if v.key?('Include') end end end @@ -42,12 +42,13 @@ def resolve_inheritance(path, hash, file, debug) # rubocop:disable Metrics/Metho # base configuration are relative to the directory where the base configuration file is. For the # derived configuration, we need to make those paths relative to where the derived configuration # file is. - def fix_include_paths(base_config_path, hash, key, value) + def fix_include_paths(base_config_path, hash, path, key, value) return unless File.basename(base_config_path).start_with?('.rubocop') base_dir = File.dirname(base_config_path) + derived_dir = File.dirname(path) hash[key]['Include'] = value['Include'].map do |include_path| - PathUtil.relative_path(File.join(base_dir, include_path), Dir.pwd) + PathUtil.relative_path(File.join(base_dir, include_path), derived_dir) end end diff --git a/lib/rubocop/config_obsoletion.rb b/lib/rubocop/config_obsoletion.rb index 0788c4b9593..c8e97b99379 100644 --- a/lib/rubocop/config_obsoletion.rb +++ b/lib/rubocop/config_obsoletion.rb @@ -15,6 +15,8 @@ class ConfigObsoletion 'changed_parameters' => ChangedParameter, 'changed_enforced_styles' => ChangedEnforcedStyles }.freeze + LOAD_RULES_CACHE = {} # rubocop:disable Style/MutableConstant + private_constant :LOAD_RULES_CACHE attr_reader :rules, :warnings @@ -48,16 +50,17 @@ def reject_obsolete! # Default rules for obsoletions are in config/obsoletion.yml # Additional rules files can be added with `RuboCop::ConfigObsoletion.files << filename` def load_rules # rubocop:disable Metrics/AbcSize - rules = self.class.files.each_with_object({}) do |filename, hash| - hash.merge!(YAML.safe_load(File.read(filename))) do |_key, first, second| - case first - when Hash - first.merge(second) - when Array - first.concat(second) + rules = LOAD_RULES_CACHE[self.class.files] ||= + self.class.files.each_with_object({}) do |filename, hash| + hash.merge!(YAML.safe_load(File.read(filename))) do |_key, first, second| + case first + when Hash + first.merge(second) + when Array + first.concat(second) + end end end - end cop_rules = rules.slice(*COP_RULE_CLASSES.keys) parameter_rules = rules.slice(*PARAMETER_RULE_CLASSES.keys) diff --git a/lib/rubocop/config_obsoletion/parameter_rule.rb b/lib/rubocop/config_obsoletion/parameter_rule.rb index f2d742a1a8c..8df4655b9e5 100644 --- a/lib/rubocop/config_obsoletion/parameter_rule.rb +++ b/lib/rubocop/config_obsoletion/parameter_rule.rb @@ -19,7 +19,7 @@ def parameter_rule? end def violated? - config[cop]&.key?(parameter) + applies_to_current_ruby_version? && config[cop]&.key?(parameter) end def warning? @@ -28,6 +28,14 @@ def warning? private + def applies_to_current_ruby_version? + minimum_ruby_version = metadata['minimum_ruby_version'] + + return true unless minimum_ruby_version + + config.target_ruby_version >= minimum_ruby_version + end + def alternative metadata['alternative'] end diff --git a/lib/rubocop/config_validator.rb b/lib/rubocop/config_validator.rb index a3fd71ea08a..a2d8e95cf9c 100644 --- a/lib/rubocop/config_validator.rb +++ b/lib/rubocop/config_validator.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'pathname' - module RuboCop # Handles validation of configuration, for example cop names, parameter # names, and Ruby versions. @@ -20,6 +18,7 @@ class ConfigValidator # @api private CONFIG_CHECK_KEYS = %w[Enabled Safe SafeAutoCorrect AutoCorrect].to_set.freeze CONFIG_CHECK_DEPARTMENTS = %w[pending override_department].freeze + CONFIG_CHECK_AUTOCORRECTS = %w[always contextual disabled].freeze private_constant :CONFIG_CHECK_KEYS, :CONFIG_CHECK_DEPARTMENTS def_delegators :@config, :smart_loaded_path, :for_all_cops @@ -250,23 +249,31 @@ def reject_conflicting_safe_settings end end + # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity def check_cop_config_value(hash, parent = nil) hash.each do |key, value| check_cop_config_value(value, key) if value.is_a?(Hash) next unless CONFIG_CHECK_KEYS.include?(key) && value.is_a?(String) - next if key == 'Enabled' && CONFIG_CHECK_DEPARTMENTS.include?(value) + if key == 'Enabled' && !CONFIG_CHECK_DEPARTMENTS.include?(value) + supposed_values = 'a boolean' + elsif key == 'AutoCorrect' && !CONFIG_CHECK_AUTOCORRECTS.include?(value) + supposed_values = '`always`, `contextual`, `disabled`, or a boolean' + else + next + end - raise ValidationError, msg_not_boolean(parent, key, value) + raise ValidationError, param_error_message(parent, key, value, supposed_values) end end + # rubocop:enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity # FIXME: Handling colors in exception messages like this is ugly. - def msg_not_boolean(parent, key, value) + def param_error_message(parent, key, value, supposed_values) "#{Rainbow('').reset}" \ - "Property #{Rainbow(key).yellow} of cop #{Rainbow(parent).yellow} " \ - "is supposed to be a boolean and #{Rainbow(value).yellow} is not." + "Property #{Rainbow(key).yellow} of #{Rainbow(parent).yellow} cop " \ + "is supposed to be #{supposed_values} and #{Rainbow(value).yellow} is not." end end end diff --git a/lib/rubocop/cop/autocorrect_logic.rb b/lib/rubocop/cop/autocorrect_logic.rb index a645ff5fe0b..6afab6b3989 100644 --- a/lib/rubocop/cop/autocorrect_logic.rb +++ b/lib/rubocop/cop/autocorrect_logic.rb @@ -32,7 +32,12 @@ def autocorrect_enabled? # allow turning off autocorrect on a cop by cop basis return true unless cop_config - return false if cop_config['AutoCorrect'] == false + # `false` is the same as `disabled` for backward compatibility. + return false if ['disabled', false].include?(cop_config['AutoCorrect']) + + # When LSP is enabled, it is considered as editing source code, + # and autocorrection with `AutoCorrect: contextual` will not be performed. + return false if contextual_autocorrect? && LSP.enabled? # :safe_autocorrect is a derived option based on several command-line # arguments - see RuboCop::Options#add_autocorrection_options @@ -82,7 +87,9 @@ def surrounding_percent_array(offense_range) node.array_type? && node.percent_literal? end - percent_array.map(&:source_range).find { |range| range.overlaps?(offense_range) } + percent_array.map(&:source_range).find do |range| + offense_range.begin_pos > range.begin_pos && range.overlaps?(offense_range) + end end def range_of_first_line(range) diff --git a/lib/rubocop/cop/base.rb b/lib/rubocop/cop/base.rb index 0c1afbd6e6d..0b99eddd23b 100644 --- a/lib/rubocop/cop/base.rb +++ b/lib/rubocop/cop/base.rb @@ -53,7 +53,7 @@ class Base # rubocop:disable Metrics/ClassLength # List of cops that should not try to autocorrect at the same # time as this cop # - # @return [Array] + # @return [Array] # # @api public def self.autocorrect_incompatible_with @@ -305,6 +305,17 @@ def begin_investigation(processed_source, offset: 0, original: processed_source) @current_original = original end + # @api private + def always_autocorrect? + # `true` is the same as `'always'` for backward compatibility. + ['always', true].include?(cop_config.fetch('AutoCorrect', 'always')) + end + + # @api private + def contextual_autocorrect? + cop_config.fetch('AutoCorrect', 'always') == 'contextual' + end + def inspect # :nodoc: "#<#{self.class.name}:#{object_id} @config=#{@config} @options=#{@options}>" end @@ -389,7 +400,7 @@ def correct(range) def use_corrector(range, corrector) if autocorrect? attempt_correction(range, corrector) - elsif corrector && cop_config.fetch('AutoCorrect', true) + elsif corrector && (always_autocorrect? || (contextual_autocorrect? && !LSP.enabled?)) :uncorrected else :unsupported diff --git a/lib/rubocop/cop/bundler/duplicated_gem.rb b/lib/rubocop/cop/bundler/duplicated_gem.rb index eca53159355..2efa8d4a00d 100644 --- a/lib/rubocop/cop/bundler/duplicated_gem.rb +++ b/lib/rubocop/cop/bundler/duplicated_gem.rb @@ -4,6 +4,7 @@ module RuboCop module Cop module Bundler # A Gem's requirements should be listed only once in a Gemfile. + # # @example # # bad # gem 'rubocop' diff --git a/lib/rubocop/cop/bundler/duplicated_group.rb b/lib/rubocop/cop/bundler/duplicated_group.rb new file mode 100644 index 00000000000..a2ffe8ebb8d --- /dev/null +++ b/lib/rubocop/cop/bundler/duplicated_group.rb @@ -0,0 +1,127 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Bundler + # A Gem group, or a set of groups, should be listed only once in a Gemfile. + # + # For example, if the values of `source`, `git`, `platforms`, or `path` + # surrounding `group` are different, no offense will be registered: + # + # [source,ruby] + # ----- + # platforms :ruby do + # group :default do + # gem 'openssl' + # end + # end + # + # platforms :jruby do + # group :default do + # gem 'jruby-openssl' + # end + # end + # ----- + # + # @example + # # bad + # group :development do + # gem 'rubocop' + # end + # + # group :development do + # gem 'rubocop-rails' + # end + # + # # bad (same set of groups declared twice) + # group :development, :test do + # gem 'rubocop' + # end + # + # group :test, :development do + # gem 'rspec' + # end + # + # # good + # group :development do + # gem 'rubocop' + # end + # + # group :development, :test do + # gem 'rspec' + # end + # + # # good + # gem 'rubocop', groups: [:development, :test] + # gem 'rspec', groups: [:development, :test] + # + class DuplicatedGroup < Base + include RangeHelp + + MSG = 'Gem group `%s` already defined on line ' \ + '%d of the Gemfile.' + SOURCE_BLOCK_NAMES = %i[source git platforms path].freeze + + # @!method group_declarations(node) + def_node_search :group_declarations, '(send nil? :group ...)' + + def on_new_investigation + return if processed_source.blank? + + duplicated_group_nodes.each do |nodes| + nodes[1..].each do |node| + group_name = node.arguments.map(&:source).join(', ') + + register_offense(node, group_name, nodes.first.first_line) + end + end + end + + private + + def duplicated_group_nodes + group_declarations = group_declarations(processed_source.ast) + group_keys = group_declarations.group_by do |node| + source_key = find_source_key(node) + group_attributes = group_attributes(node).sort.join + + "#{source_key}#{group_attributes}" + end + + group_keys.values.select { |nodes| nodes.size > 1 } + end + + def register_offense(node, group_name, line_of_first_occurrence) + line_range = node.loc.column...node.loc.last_column + offense_location = source_range(processed_source.buffer, node.first_line, line_range) + message = format( + MSG, + group_name: group_name, + line_of_first_occurrence: line_of_first_occurrence + ) + add_offense(offense_location, message: message) + end + + def find_source_key(node) + source_block = node.each_ancestor(:block).find do |block_node| + SOURCE_BLOCK_NAMES.include?(block_node.method_name) + end + + return unless source_block + + "#{source_block.method_name}#{source_block.send_node.first_argument&.source}" + end + + def group_attributes(node) + node.arguments.map do |argument| + if argument.hash_type? + argument.pairs.map(&:source).sort.join(', ') + else + argument.respond_to?(:value) ? argument.value.to_s : argument.source + end + end + end + end + end + end +end diff --git a/lib/rubocop/cop/bundler/gem_comment.rb b/lib/rubocop/cop/bundler/gem_comment.rb index 590244a1fd7..f14e60d75a2 100644 --- a/lib/rubocop/cop/bundler/gem_comment.rb +++ b/lib/rubocop/cop/bundler/gem_comment.rb @@ -150,7 +150,7 @@ def version_specified_gem?(node) # Version specifications that restrict all updates going forward. This excludes versions # like ">= 1.0" or "!= 2.0.3". def restrictive_version_specified_gem?(node) - return unless version_specified_gem?(node) + return false unless version_specified_gem?(node) node.arguments[1..] .any? { |arg| arg&.str_type? && RESTRICTIVE_VERSION_PATTERN.match?(arg.value) } @@ -161,9 +161,9 @@ def contains_checked_options?(node) end def gem_options(node) - return [] unless node.arguments.last&.type == :hash + return [] unless node.last_argument&.type == :hash - node.arguments.last.keys.map(&:value) + node.last_argument.keys.map(&:value) end end end diff --git a/lib/rubocop/cop/bundler/gem_version.rb b/lib/rubocop/cop/bundler/gem_version.rb index dfe8f2ab645..d5992af88dd 100644 --- a/lib/rubocop/cop/bundler/gem_version.rb +++ b/lib/rubocop/cop/bundler/gem_version.rb @@ -105,13 +105,13 @@ def offense?(node) end def required_offense?(node) - return unless required_style? + return false unless required_style? !includes_version_specification?(node) && !includes_commit_reference?(node) end def forbidden_offense?(node) - return unless forbidden_style? + return false unless forbidden_style? includes_version_specification?(node) || includes_commit_reference?(node) end diff --git a/lib/rubocop/cop/bundler/ordered_gems.rb b/lib/rubocop/cop/bundler/ordered_gems.rb index 4b60ba70a96..305c8e5f212 100644 --- a/lib/rubocop/cop/bundler/ordered_gems.rb +++ b/lib/rubocop/cop/bundler/ordered_gems.rb @@ -19,7 +19,15 @@ module Bundler # # gem 'rspec' # - # # good only if TreatCommentsAsGroupSeparators is true + # @example TreatCommentsAsGroupSeparators: true (default) + # # good + # # For code quality + # gem 'rubocop' + # # For tests + # gem 'rspec' + # + # @example TreatCommentsAsGroupSeparators: false + # # bad # # For code quality # gem 'rubocop' # # For tests diff --git a/lib/rubocop/cop/correctors/each_to_for_corrector.rb b/lib/rubocop/cop/correctors/each_to_for_corrector.rb index 4763a491c8f..e464a558f37 100644 --- a/lib/rubocop/cop/correctors/each_to_for_corrector.rb +++ b/lib/rubocop/cop/correctors/each_to_for_corrector.rb @@ -34,18 +34,14 @@ def correction end def offending_range + begin_range = block_node.source_range.begin + if block_node.arguments? - replacement_range(argument_node.source_range.end_pos) + begin_range.join(argument_node.source_range.end) else - replacement_range(block_node.loc.begin.end_pos) + begin_range.join(block_node.loc.begin.end) end end - - def replacement_range(end_pos) - Parser::Source::Range.new(block_node.source_range.source_buffer, - block_node.source_range.begin_pos, - end_pos) - end end end end diff --git a/lib/rubocop/cop/correctors/for_to_each_corrector.rb b/lib/rubocop/cop/correctors/for_to_each_corrector.rb index 4f711c49bc5..275aa1269e7 100644 --- a/lib/rubocop/cop/correctors/for_to_each_corrector.rb +++ b/lib/rubocop/cop/correctors/for_to_each_corrector.rb @@ -15,6 +15,8 @@ def initialize(for_node) end def call(corrector) + offending_range = for_node.source_range.begin.join(end_range) + corrector.replace(offending_range, correction) end @@ -40,11 +42,11 @@ def requires_parentheses? collection_node.range_type? || collection_node.or_type? || collection_node.and_type? end - def end_position + def end_range if for_node.do? - keyword_begin.end_pos + keyword_begin.end else - collection_end.end_pos + collection_end.end end end @@ -59,16 +61,6 @@ def collection_end collection_node.source_range end end - - def offending_range - replacement_range(end_position) - end - - def replacement_range(end_pos) - Parser::Source::Range.new(for_node.source_range.source_buffer, - for_node.source_range.begin_pos, - end_pos) - end end end end diff --git a/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb b/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb index 2ee0b879b2b..6d690736deb 100644 --- a/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb +++ b/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb @@ -14,12 +14,15 @@ def call(corrector) # Check for unparenthesized args' preceding and trailing whitespaces. remove_unparenthesized_whitespace(corrector) - # Avoid correcting to `lambdado` by inserting whitespace - # if none exists before or after the lambda arguments. - insert_separating_space(corrector) + if block_node.block_type? + # Avoid correcting to `lambdado` by inserting whitespace + # if none exists before or after the lambda arguments. + insert_separating_space(corrector) + + remove_arguments(corrector) + end replace_selector(corrector) - remove_arguments(corrector) replace_delimiters(corrector) diff --git a/lib/rubocop/cop/exclude_limit.rb b/lib/rubocop/cop/exclude_limit.rb index 6d2ff8ae3ff..913019eac63 100644 --- a/lib/rubocop/cop/exclude_limit.rb +++ b/lib/rubocop/cop/exclude_limit.rb @@ -8,7 +8,7 @@ module ExcludeLimit # The parameter name given is transformed into a method name (eg. `Max` # becomes `self.max=` and `MinDigits` becomes `self.min_digits=`). def exclude_limit(parameter_name, method_name: transform(parameter_name)) - define_method("#{method_name}=") do |value| + define_method(:"#{method_name}=") do |value| cfg = config_to_allow_offenses cfg[:exclude_limit] ||= {} current_max = cfg[:exclude_limit][parameter_name] diff --git a/lib/rubocop/cop/gemspec/dependency_version.rb b/lib/rubocop/cop/gemspec/dependency_version.rb index 679eaf5311b..f238aa13ac8 100644 --- a/lib/rubocop/cop/gemspec/dependency_version.rb +++ b/lib/rubocop/cop/gemspec/dependency_version.rb @@ -126,13 +126,13 @@ def offense?(node) end def required_offense?(node) - return unless required_style? + return false unless required_style? !includes_version_specification?(node) && !includes_commit_reference?(node) end def forbidden_offense?(node) - return unless forbidden_style? + return false unless forbidden_style? includes_version_specification?(node) || includes_commit_reference?(node) end diff --git a/lib/rubocop/cop/gemspec/deprecated_attribute_assignment.rb b/lib/rubocop/cop/gemspec/deprecated_attribute_assignment.rb index cf292473d8e..7ab262e8ac8 100644 --- a/lib/rubocop/cop/gemspec/deprecated_attribute_assignment.rb +++ b/lib/rubocop/cop/gemspec/deprecated_attribute_assignment.rb @@ -43,7 +43,7 @@ class DeprecatedAttributeAssignment < Base def on_block(block_node) return unless gem_specification(block_node) - block_parameter = block_node.arguments.first.source + block_parameter = block_node.first_argument.source assignment = block_node.descendants.detect do |node| use_deprecated_attributes?(node, block_parameter) @@ -65,7 +65,7 @@ def node_and_method_name(node, attribute) lhs, _op, _rhs = *node [lhs, attribute] else - [node, "#{attribute}=".to_sym] + [node, :"#{attribute}="] end end diff --git a/lib/rubocop/cop/gemspec/ordered_dependencies.rb b/lib/rubocop/cop/gemspec/ordered_dependencies.rb index 79663ce3a94..0c9f43c9a4c 100644 --- a/lib/rubocop/cop/gemspec/ordered_dependencies.rb +++ b/lib/rubocop/cop/gemspec/ordered_dependencies.rb @@ -45,7 +45,15 @@ module Gemspec # # spec.add_runtime_dependency 'rspec' # - # # good only if TreatCommentsAsGroupSeparators is true + # @example TreatCommentsAsGroupSeparators: true (default) + # # good + # # For code quality + # spec.add_dependency 'rubocop' + # # For tests + # spec.add_dependency 'rspec' + # + # @example TreatCommentsAsGroupSeparators: false + # # bad # # For code quality # spec.add_dependency 'rubocop' # # For tests diff --git a/lib/rubocop/cop/generator/require_file_injector.rb b/lib/rubocop/cop/generator/require_file_injector.rb index 1facbc9cdfd..2a097ef5bd7 100644 --- a/lib/rubocop/cop/generator/require_file_injector.rb +++ b/lib/rubocop/cop/generator/require_file_injector.rb @@ -67,7 +67,7 @@ def injectable_require_directive def require_path path = source_path.relative_path_from(root_file_path.dirname) - path.to_s.sub('.rb', '') + path.to_s.delete_suffix('.rb') end end end diff --git a/lib/rubocop/cop/internal_affairs.rb b/lib/rubocop/cop/internal_affairs.rb index 504a73fba3d..6a2b399db3a 100644 --- a/lib/rubocop/cop/internal_affairs.rb +++ b/lib/rubocop/cop/internal_affairs.rb @@ -12,6 +12,7 @@ require_relative 'internal_affairs/method_name_end_with' require_relative 'internal_affairs/method_name_equal' require_relative 'internal_affairs/node_destructuring' +require_relative 'internal_affairs/node_first_or_last_argument' require_relative 'internal_affairs/node_matcher_directive' require_relative 'internal_affairs/node_type_predicate' require_relative 'internal_affairs/numblock_handler' @@ -19,6 +20,7 @@ require_relative 'internal_affairs/processed_source_buffer_name' require_relative 'internal_affairs/redundant_context_config_parameter' require_relative 'internal_affairs/redundant_described_class_as_subject' +require_relative 'internal_affairs/redundant_expect_offense_arguments' require_relative 'internal_affairs/redundant_let_rubocop_config_new' require_relative 'internal_affairs/redundant_location_argument' require_relative 'internal_affairs/redundant_message_argument' diff --git a/lib/rubocop/cop/internal_affairs/example_description.rb b/lib/rubocop/cop/internal_affairs/example_description.rb index 2de112afbcc..c42c57d3320 100644 --- a/lib/rubocop/cop/internal_affairs/example_description.rb +++ b/lib/rubocop/cop/internal_affairs/example_description.rb @@ -26,9 +26,7 @@ module InternalAffairs # expect_no_offenses('...') # end class ExampleDescription < Base - class << self - attr_accessor :descriptions - end + extend AutoCorrector MSG = 'Description does not match use of `%s`.' @@ -39,26 +37,36 @@ class << self expect_no_corrections ].to_set.freeze - EXPECT_NO_OFFENSES_INCORRECT_DESCRIPTIONS = [ - /^(adds|registers|reports|finds) (an? )?offense/, - /^(flags|handles|works)\b/ - ].freeze + EXPECT_NO_OFFENSES_DESCRIPTION_MAPPING = { + /\A(adds|registers|reports|finds) (an? )?offense/ => 'does not register an offense', + /\A(flags|handles|works)\b/ => 'does not register' + }.freeze + + EXPECT_OFFENSE_DESCRIPTION_MAPPING = { + /\A(does not|doesn't) (register|find|flag|report)/ => 'registers', + /\A(does not|doesn't) add (a|an|any )?offense/ => 'registers an offense', + /\Aaccepts\b/ => 'registers' + }.freeze - EXPECT_OFFENSE_INCORRECT_DESCRIPTIONS = [ - /^(does not|doesn't) (register|find|flag|report)/, - /^(does not|doesn't) add (a|an|any )?offense/ - ].freeze + EXPECT_NO_CORRECTIONS_DESCRIPTION_MAPPING = { + /\A(auto[- ]?)?correct/ => 'does not correct' + }.freeze - EXPECT_NO_CORRECTIONS_INCORRECT_DESCRIPTIONS = [/^(auto[- ]?)?correct/].freeze + EXPECT_CORRECTION_DESCRIPTION_MAPPING = { + /\b(does not|doesn't) (auto[- ]?)?correct/ => 'autocorrects' + }.freeze - EXPECT_CORRECTION_INCORRECT_DESCRIPTIONS = [ - /\b(does not|doesn't) (auto[- ]?)?correct/ - ].freeze + EXAMPLE_DESCRIPTION_MAPPING = { + expect_no_offenses: EXPECT_NO_OFFENSES_DESCRIPTION_MAPPING, + expect_offense: EXPECT_OFFENSE_DESCRIPTION_MAPPING, + expect_no_corrections: EXPECT_NO_CORRECTIONS_DESCRIPTION_MAPPING, + expect_correction: EXPECT_CORRECTION_DESCRIPTION_MAPPING + }.freeze - # @!method offense_example?(node) - def_node_matcher :offense_example?, <<~PATTERN + # @!method offense_example(node) + def_node_matcher :offense_example, <<~PATTERN (block - (send _ {:it :specify} $_description) + (send _ {:it :specify} $...) _args `(send nil? %RESTRICT_ON_SEND ...) ) @@ -66,21 +74,34 @@ class << self def on_send(node) parent = node.each_ancestor(:block).first - return unless parent && (description = offense_example?(parent)) + return unless parent && (current_description = offense_example(parent)&.first) method_name = node.method_name message = format(MSG, method_name: method_name) - regexp_group = self.class.const_get("#{method_name}_incorrect_descriptions".upcase) - check_description(description, regexp_group, message) + description_map = EXAMPLE_DESCRIPTION_MAPPING[method_name] + check_description(current_description, description_map, message) end private - def check_description(description, regexps, message) - return unless regexps.any? { |regexp| regexp.match?(string_contents(description)) } + def check_description(current_description, description_map, message) + description_text = string_contents(current_description) + return unless (new_description = correct_description(description_text, description_map)) + + add_offense(current_description, message: message) do |corrector| + corrector.replace(current_description, "'#{new_description}'") + end + end + + def correct_description(current_description, description_map) + description_map.each do |incorrect_description_pattern, preferred_description| + if incorrect_description_pattern.match?(current_description) + return current_description.gsub(incorrect_description_pattern, preferred_description) + end + end - add_offense(description, message: message) + nil end def string_contents(node) diff --git a/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb b/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb index d2345f78df5..ca0621e2fd1 100644 --- a/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb +++ b/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb @@ -51,7 +51,9 @@ def on_send(node) def extract_receiver(node) receiver = node.receiver - receiver = receiver.receiver if receiver.method?(:loc) || receiver.method?(:source_range) + if receiver.send_type? && (receiver.method?(:loc) || receiver.method?(:source_range)) + receiver = receiver.receiver + end receiver.source end end diff --git a/lib/rubocop/cop/internal_affairs/method_name_end_with.rb b/lib/rubocop/cop/internal_affairs/method_name_end_with.rb index 18b4fa04423..648f61eda29 100644 --- a/lib/rubocop/cop/internal_affairs/method_name_end_with.rb +++ b/lib/rubocop/cop/internal_affairs/method_name_end_with.rb @@ -30,6 +30,7 @@ class MethodNameEndWith < Base extend AutoCorrector MSG = 'Use `%s` instead of `%s`.' + RESTRICT_ON_SEND = %i[end_with?].freeze SUGGEST_METHOD_FOR_SUFFIX = { '=' => 'assignment_method?', '!' => 'bang_method?', @@ -51,14 +52,15 @@ class MethodNameEndWith < Base def on_send(node) method_name_end_with?(node) do |method_name_node, end_with_arg| + next unless method_name_node.receiver + + preferred_method = SUGGEST_METHOD_FOR_SUFFIX[end_with_arg.value] range = range(method_name_node, node) - message = format( - MSG, - method_name: SUGGEST_METHOD_FOR_SUFFIX[end_with_arg.value], - method_suffix: range.source - ) + message = format(MSG, method_name: preferred_method, method_suffix: range.source) - add_offense(range, message: message) + add_offense(range, message: message) do |corrector| + corrector.replace(range, preferred_method) + end end end alias on_csend on_send diff --git a/lib/rubocop/cop/internal_affairs/method_name_equal.rb b/lib/rubocop/cop/internal_affairs/method_name_equal.rb index da6388d8d6c..ea3f56ec74c 100644 --- a/lib/rubocop/cop/internal_affairs/method_name_equal.rb +++ b/lib/rubocop/cop/internal_affairs/method_name_equal.rb @@ -12,38 +12,37 @@ module InternalAffairs # # good # node.method?(:do_something) # + # # bad + # node.method_name != :do_something + # + # # good + # !node.method?(:do_something) + # class MethodNameEqual < Base - include RangeHelp extend AutoCorrector - MSG = 'Use `method?(%s)` instead of `method_name == %s`.' - RESTRICT_ON_SEND = %i[==].freeze + MSG = 'Use `%s` instead.' + RESTRICT_ON_SEND = %i[== !=].freeze - # @!method method_name?(node) - def_node_matcher :method_name?, <<~PATTERN + # @!method method_name(node) + def_node_matcher :method_name, <<~PATTERN (send - $(send - (...) :method_name) :== - $...) + (send + (...) :method_name) {:== :!=} + $_) PATTERN def on_send(node) - method_name?(node) do |method_name_node, method_name_arg| - message = format(MSG, method_name: method_name_arg.first.source) + method_name(node) do |method_name_arg| + bang = node.method?(:!=) ? '!' : '' + prefer = "#{bang}#{node.receiver.receiver.source}.method?(#{method_name_arg.source})" + message = format(MSG, prefer: prefer) - range = range(method_name_node, node) - - add_offense(range, message: message) do |corrector| - corrector.replace(range, "method?(#{method_name_arg.first.source})") + add_offense(node, message: message) do |corrector| + corrector.replace(node, prefer) end end end - - private - - def range(method_name_node, node) - range_between(method_name_node.loc.selector.begin_pos, node.source_range.end_pos) - end end end end diff --git a/lib/rubocop/cop/internal_affairs/node_first_or_last_argument.rb b/lib/rubocop/cop/internal_affairs/node_first_or_last_argument.rb new file mode 100644 index 00000000000..63395afc588 --- /dev/null +++ b/lib/rubocop/cop/internal_affairs/node_first_or_last_argument.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module InternalAffairs + # Checks for the use of `node.arguments.first` or `node.arguments.last` and + # suggests the use of `node.first_argument` or `node.last_argument` instead. + # + # @example + # # bad + # node.arguments.first + # node.arguments[0] + # node.arguments.last + # node.arguments[-1] + # + # # good + # node.first_argument + # node.last_argument + # + class NodeFirstOrLastArgument < Base + extend AutoCorrector + include RangeHelp + + MSG = 'Use `#%s` instead of `#%s`.' + RESTRICT_ON_SEND = %i[arguments].freeze + + # @!method arguments_first_or_last?(node) + def_node_matcher :arguments_first_or_last?, <<~PATTERN + { + (send (send !nil? :arguments) ${:first :last}) + (send (send !nil? :arguments) :[] (int ${0 -1})) + } + PATTERN + + def on_send(node) + arguments_first_or_last?(node.parent) do |end_or_index| + range = range_between(node.loc.selector.begin_pos, node.parent.source_range.end_pos) + correct = case end_or_index + when :first, 0 then 'first_argument' + when :last, -1 then 'last_argument' + else raise "Unknown end_or_index: #{end_or_index}" + end + message = format(MSG, correct: correct, incorrect: range.source) + + add_offense(range, message: message) do |corrector| + corrector.replace(range, correct) + end + end + end + end + end + end +end diff --git a/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb b/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb index 1f7c74c2c28..980b489bbb5 100644 --- a/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb +++ b/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb @@ -40,7 +40,7 @@ def on_send(node) return if node.arguments.none? return unless valid_method_name?(node) - actual_name = node.arguments.first.value + actual_name = node.first_argument.value directives = method_directives(node) return too_many_directives(node) if directives.size > 1 @@ -53,7 +53,7 @@ def on_send(node) private def valid_method_name?(node) - node.arguments.first.str_type? || node.arguments.first.sym_type? + node.first_argument.str_type? || node.first_argument.sym_type? end def method_directives(node) @@ -117,11 +117,11 @@ def pattern_arguments(pattern) def add_newline?(node) # Determine if a blank line should be inserted before the new directive # in order to spread out pattern matchers - return if node.sibling_index&.zero? - return unless node.parent + return false if node.sibling_index&.zero? + return false unless node.parent prev_sibling = node.parent.child_nodes[node.sibling_index - 1] - return unless prev_sibling && pattern_matcher?(prev_sibling) + return false unless prev_sibling && pattern_matcher?(prev_sibling) node.loc.line == last_line(prev_sibling) + 1 end diff --git a/lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb b/lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb new file mode 100644 index 00000000000..4424cb07c49 --- /dev/null +++ b/lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module InternalAffairs + # Checks for redundant arguments of `RuboCop::RSpec::ExpectOffense`'s methods. + # + # @example + # + # # bad + # expect_no_offenses('code', keyword: keyword) + # + # # good + # expect_no_offenses('code') + # + class RedundantExpectOffenseArguments < Base + extend AutoCorrector + + MSG = 'Remove the redundant arguments.' + RESTRICT_ON_SEND = %i[expect_no_offenses].freeze + + def on_send(node) + return if node.arguments.one? || !node.arguments[1]&.hash_type? + + range = node.first_argument.source_range.end.join(node.last_argument.source_range.end) + + add_offense(range) do |corrector| + corrector.remove(range) + end + end + end + end + end +end diff --git a/lib/rubocop/cop/internal_affairs/redundant_method_dispatch_node.rb b/lib/rubocop/cop/internal_affairs/redundant_method_dispatch_node.rb index b7af63dcd91..edadd0c6583 100644 --- a/lib/rubocop/cop/internal_affairs/redundant_method_dispatch_node.rb +++ b/lib/rubocop/cop/internal_affairs/redundant_method_dispatch_node.rb @@ -14,6 +14,12 @@ module InternalAffairs # node.method_name # # # bad + # node.send_node.method?(:method_name) + # + # # good + # node.method?(:method_name) + # + # # bad # node.send_node.receiver # # # good @@ -24,11 +30,14 @@ class RedundantMethodDispatchNode < Base extend AutoCorrector MSG = 'Remove the redundant `send_node`.' - RESTRICT_ON_SEND = %i[method_name receiver].freeze + RESTRICT_ON_SEND = %i[method_name method? receiver].freeze # @!method dispatch_method(node) def_node_matcher :dispatch_method, <<~PATTERN - (send $(send _ :send_node) _) + { + (send $(send _ :send_node) {:method_name :receiver}) + (send $(send _ :send_node) :method? _) + } PATTERN def on_send(node) diff --git a/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb b/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb index 5c6f25faec5..c31a4b571a6 100644 --- a/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb +++ b/lib/rubocop/cop/internal_affairs/useless_message_assertion.rb @@ -27,6 +27,8 @@ class UselessMessageAssertion < Base PATTERN def on_new_investigation + return if processed_source.blank? + assertions_using_described_class_msg.each { |node| add_offense(node) } end diff --git a/lib/rubocop/cop/layout/argument_alignment.rb b/lib/rubocop/cop/layout/argument_alignment.rb index 80e8459e283..4c4016c0f40 100644 --- a/lib/rubocop/cop/layout/argument_alignment.rb +++ b/lib/rubocop/cop/layout/argument_alignment.rb @@ -79,7 +79,7 @@ def flattened_arguments(node) def arguments_with_last_arg_pairs(node) items = node.arguments[0..-2] - last_arg = node.arguments.last + last_arg = node.last_argument if last_arg.hash_type? && !last_arg.braces? items += last_arg.pairs diff --git a/lib/rubocop/cop/layout/class_structure.rb b/lib/rubocop/cop/layout/class_structure.rb index 3013a2e44d8..0156bc8e2f3 100644 --- a/lib/rubocop/cop/layout/class_structure.rb +++ b/lib/rubocop/cop/layout/class_structure.rb @@ -68,6 +68,13 @@ module Layout # - extend # ---- # + # @safety + # Autocorrection is unsafe because class methods and module inclusion + # can behave differently, based on which methods or constants have + # already been defined. + # + # Constants will only be moved when they are assigned with literals. + # # @example # # bad # # Expect extend be before constant diff --git a/lib/rubocop/cop/layout/closing_heredoc_indentation.rb b/lib/rubocop/cop/layout/closing_heredoc_indentation.rb index 13a3d2d7de0..74525ecb4a9 100644 --- a/lib/rubocop/cop/layout/closing_heredoc_indentation.rb +++ b/lib/rubocop/cop/layout/closing_heredoc_indentation.rb @@ -72,7 +72,7 @@ def opening_indentation(node) end def argument_indentation_correct?(node) - return unless node.argument? || node.chained? + return false unless node.argument? || node.chained? opening_indentation( find_node_used_heredoc_argument(node.parent) diff --git a/lib/rubocop/cop/layout/dot_position.rb b/lib/rubocop/cop/layout/dot_position.rb index e731c51002a..5a14850a070 100644 --- a/lib/rubocop/cop/layout/dot_position.rb +++ b/lib/rubocop/cop/layout/dot_position.rb @@ -32,7 +32,7 @@ def self.autocorrect_incompatible_with end def on_send(node) - return unless node.dot? || ampersand_dot?(node) + return unless node.dot? || node.safe_navigation? return correct_style_detected if proper_dot_position?(node) @@ -133,10 +133,6 @@ def selector_range(node) # l.(1) has no selector, so we use the opening parenthesis instead node.loc.selector || node.loc.begin end - - def ampersand_dot?(node) - node.loc.respond_to?(:dot) && node.loc.dot && node.loc.dot.is?('&.') - end end end end diff --git a/lib/rubocop/cop/layout/empty_line_after_guard_clause.rb b/lib/rubocop/cop/layout/empty_line_after_guard_clause.rb index 048547e5c29..b309c3df825 100644 --- a/lib/rubocop/cop/layout/empty_line_after_guard_clause.rb +++ b/lib/rubocop/cop/layout/empty_line_after_guard_clause.rb @@ -3,7 +3,23 @@ module RuboCop module Cop module Layout - # Enforces empty line after guard clause + # Enforces empty line after guard clause. + # + # This cop allows `# :nocov:` directive after guard clause because + # SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`: + # + # [source,ruby] + # ---- + # def foo + # # :nocov: + # return if condition + # # :nocov: + # bar + # end + # ---- + # + # Refer to SimpleCov's documentation for more details: + # https://github.com/simplecov-ruby/simplecov#ignoringskipping-code # # @example # @@ -42,19 +58,22 @@ class EmptyLineAfterGuardClause < Base MSG = 'Add empty line after guard clause.' END_OF_HEREDOC_LINE = 1 + SIMPLE_DIRECTIVE_COMMENT_PATTERN = /\A# *:nocov:\z/.freeze def on_if(node) return if correct_style?(node) return if multiple_statements_on_line?(node) if node.modifier_form? && (heredoc_node = last_heredoc_argument(node)) - return if next_line_empty_or_enable_directive_comment?(heredoc_line(node, heredoc_node)) + if next_line_empty_or_allowed_directive_comment?(heredoc_line(node, heredoc_node)) + return + end add_offense(heredoc_node.loc.heredoc_end) do |corrector| autocorrect(corrector, heredoc_node) end else - return if next_line_empty_or_enable_directive_comment?(node.last_line) + return if next_line_empty_or_allowed_directive_comment?(node.last_line) add_offense(offense_location(node)) { |corrector| autocorrect(corrector, node) } end @@ -70,7 +89,7 @@ def autocorrect(corrector, node) end next_line = node_range.last_line + 1 - if next_line_enable_directive_comment?(next_line) + if next_line_allowed_directive_comment?(next_line) node_range = processed_source.comment_at_line(next_line) end @@ -88,21 +107,21 @@ def contains_guard_clause?(node) node.if_branch&.guard_clause? end - def next_line_empty_or_enable_directive_comment?(line) + def next_line_empty_or_allowed_directive_comment?(line) return true if next_line_empty?(line) next_line = line + 1 - next_line_enable_directive_comment?(next_line) && next_line_empty?(next_line) + next_line_allowed_directive_comment?(next_line) && next_line_empty?(next_line) end def next_line_empty?(line) processed_source[line].blank? end - def next_line_enable_directive_comment?(line) + def next_line_allowed_directive_comment?(line) return false unless (comment = processed_source.comment_at_line(line)) - DirectiveComment.new(comment).enabled? + DirectiveComment.new(comment).enabled? || simplecov_directive_comment?(comment) end def next_line_rescue_or_ensure?(node) @@ -137,7 +156,7 @@ def last_heredoc_argument(node) return node if node end - return last_heredoc_argument(n.receiver) if n.respond_to?(:receiver) + last_heredoc_argument(n.receiver) if n.respond_to?(:receiver) end def last_heredoc_argument_node(node) @@ -145,6 +164,8 @@ def last_heredoc_argument_node(node) if node.if_branch.and_type? node.if_branch.children.first + elsif use_heredoc_in_condition?(node.condition) + node.condition else node.if_branch.children.last end @@ -161,6 +182,12 @@ def heredoc?(node) node.respond_to?(:heredoc?) && node.heredoc? end + def use_heredoc_in_condition?(condition) + condition.descendants.any? do |descendant| + descendant.respond_to?(:heredoc?) && descendant.heredoc? + end + end + def offense_location(node) if node.loc.respond_to?(:end) && node.loc.end node.loc.end @@ -175,6 +202,12 @@ def multiple_statements_on_line?(node) parent.begin_type? && parent.single_line? end + + # SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`: + # https://github.com/simplecov-ruby/simplecov#ignoringskipping-code + def simplecov_directive_comment?(comment) + SIMPLE_DIRECTIVE_COMMENT_PATTERN.match?(comment.text) + end end end end diff --git a/lib/rubocop/cop/layout/empty_line_between_defs.rb b/lib/rubocop/cop/layout/empty_line_between_defs.rb index 715a609e74d..21be7ca7c9f 100644 --- a/lib/rubocop/cop/layout/empty_line_between_defs.rb +++ b/lib/rubocop/cop/layout/empty_line_between_defs.rb @@ -135,7 +135,8 @@ def check_defs(nodes) return if nodes.all?(&:single_line?) && cop_config['AllowAdjacentOneLineDefs'] correction_node = nodes.last - location = correction_node.loc.keyword.join(correction_node.loc.name) + + location = def_location(correction_node) add_offense(location, message: message(correction_node, count: count)) do |corrector| autocorrect(corrector, *nodes, count) end @@ -159,10 +160,28 @@ def autocorrect(corrector, prev_def, node, count) private + def def_location(correction_node) + if correction_node.block_type? + correction_node.source_range.join(correction_node.children.first.source_range) + else + correction_node.loc.keyword.join(correction_node.loc.name) + end + end + def candidate?(node) - return unless node + return false unless node - method_candidate?(node) || class_candidate?(node) || module_candidate?(node) + method_candidate?(node) || class_candidate?(node) || module_candidate?(node) || + macro_candidate?(node) + end + + def empty_line_between_macros + cop_config.fetch('DefLikeMacros', []).map(&:to_sym) + end + + def macro_candidate?(node) + node.block_type? && node.children.first.macro? && + empty_line_between_macros.include?(node.children.first.method_name) end def method_candidate?(node) @@ -226,7 +245,11 @@ def lines_between_defs(first_def_node, second_def_node) end def def_start(node) - node.loc.keyword.line + if node.block_type? && node.children.first.send_type? + node.source_range.line + else + node.loc.keyword.line + end end def def_end(node) diff --git a/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb b/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb index 89efc887379..ea1d4917d22 100644 --- a/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb +++ b/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb @@ -68,6 +68,8 @@ def on_def(node) check_body(node.body, node.loc.line) end alias on_defs on_def + alias on_block on_def + alias on_numblock on_def def on_kwbegin(node) body, = *node diff --git a/lib/rubocop/cop/layout/end_alignment.rb b/lib/rubocop/cop/layout/end_alignment.rb index 6e75b78593a..4c2eac3c796 100644 --- a/lib/rubocop/cop/layout/end_alignment.rb +++ b/lib/rubocop/cop/layout/end_alignment.rb @@ -20,7 +20,9 @@ module Layout # This `Layout/EndAlignment` cop aligns with keywords (e.g. `if`, `while`, `case`) # by default. On the other hand, `Layout/BeginEndAlignment` cop aligns with # `EnforcedStyleAlignWith: start_of_line` by default due to `||= begin` tends - # to align with the start of the line. These style can be configured by each cop. + # to align with the start of the line. `Layout/DefEndAlignment` cop also aligns with + # `EnforcedStyleAlignWith: start_of_line` by default. + # These style can be configured by each cop. # # @example EnforcedStyleAlignWith: keyword (default) # # bad @@ -83,7 +85,11 @@ def on_class(node) end def on_sclass(node) - check_other_alignment(node) + if node.parent&.assignment? + check_asgn_alignment(node.parent, node) + else + check_other_alignment(node) + end end def on_module(node) @@ -163,7 +169,13 @@ def alignment_node(node) when :keyword node when :variable - alignment_node_for_variable_style(node) + align_to = alignment_node_for_variable_style(node) + + while (parent = align_to.parent) && parent.send_type? && same_line?(align_to, parent) + align_to = parent + end + + align_to else start_line_range(node) end diff --git a/lib/rubocop/cop/layout/extra_spacing.rb b/lib/rubocop/cop/layout/extra_spacing.rb index 2281542a5fb..16cd665ab51 100644 --- a/lib/rubocop/cop/layout/extra_spacing.rb +++ b/lib/rubocop/cop/layout/extra_spacing.rb @@ -49,19 +49,13 @@ def on_new_investigation private - def aligned_locations(locs) # rubocop:disable Metrics/AbcSize + def aligned_locations(locs) return [] if locs.empty? - aligned = Set[locs.first.line, locs.last.line] - locs.each_cons(3) do |before, loc, after| - col = loc.column - aligned << loc.line if col == before.column || col == after.column + aligned = Set.new + locs.each_cons(2) do |loc1, loc2| + aligned << loc1.line << loc2.line if loc1.column == loc2.column end - - # if locs.size > 2 and the size of variable `aligned` - # has not increased from its initial value, there are not aligned lines. - return [] if locs.size > 2 && aligned.size == 2 - aligned end diff --git a/lib/rubocop/cop/layout/first_array_element_indentation.rb b/lib/rubocop/cop/layout/first_array_element_indentation.rb index 9c309d2e2dc..c45e7661c42 100644 --- a/lib/rubocop/cop/layout/first_array_element_indentation.rb +++ b/lib/rubocop/cop/layout/first_array_element_indentation.rb @@ -5,7 +5,10 @@ module Cop module Layout # Checks the indentation of the first element in an array literal # where the opening bracket and the first element are on separate lines. - # The other elements' indentations are handled by the ArrayAlignment cop. + # The other elements' indentations are handled by `Layout/ArrayAlignment` cop. + # + # This cop will respect `Layout/ArrayAlignment` and will not work when + # `EnforcedStyle: with_fixed_indentation` is specified for `Layout/ArrayAlignment`. # # By default, array literals that are arguments in a method call with # parentheses, and where the opening square bracket of the array is on the @@ -25,7 +28,7 @@ module Layout # # element are on separate lines is indented one step (two spaces) more # # than the position inside the opening parenthesis. # - # #bad + # # bad # array = [ # :value # ] @@ -33,7 +36,7 @@ module Layout # :no_difference # ]) # - # #good + # # good # array = [ # :value # ] @@ -47,7 +50,7 @@ module Layout # # separate lines is indented the same as an array literal which is not # # defined inside a method call. # - # #bad + # # bad # # consistent # array = [ # :value @@ -56,7 +59,7 @@ module Layout # :its_like_this # ]) # - # #good + # # good # array = [ # :value # ] @@ -68,13 +71,13 @@ module Layout # # The `align_brackets` style enforces that the opening and closing # # brackets are indented to the same position. # - # #bad + # # bad # # align_brackets # and_now_for_something = [ # :completely_different # ] # - # #good + # # good # # align_brackets # and_now_for_something = [ # :completely_different @@ -93,6 +96,8 @@ def on_array(node) end def on_send(node) + return if style != :consistent && enforce_first_argument_with_fixed_indentation? + each_argument_node(node, :array) do |array_node, left_parenthesis| check(array_node, left_parenthesis) end @@ -174,6 +179,16 @@ def message_for_right_bracket(indent_base_type) 'where the left bracket is.' end end + + def enforce_first_argument_with_fixed_indentation? + return false unless array_alignment_config['Enabled'] + + array_alignment_config['EnforcedStyle'] == 'with_fixed_indentation' + end + + def array_alignment_config + config.for_cop('Layout/ArrayAlignment') + end end end end diff --git a/lib/rubocop/cop/layout/first_parameter_indentation.rb b/lib/rubocop/cop/layout/first_parameter_indentation.rb index dfec906f0b4..1f1c2b55327 100644 --- a/lib/rubocop/cop/layout/first_parameter_indentation.rb +++ b/lib/rubocop/cop/layout/first_parameter_indentation.rb @@ -72,7 +72,7 @@ def check(def_node) return if ignored_node?(def_node) left_parenthesis = def_node.arguments.loc.begin - first_elem = def_node.arguments.first + first_elem = def_node.first_argument return unless first_elem return if same_line?(first_elem, left_parenthesis) diff --git a/lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb b/lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb index 546c14cc9af..b4b42846174 100644 --- a/lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb +++ b/lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb @@ -182,7 +182,7 @@ def fix_closing_parenthesis(node, corrector) end def add_correct_closing_paren(node, corrector) - corrector.insert_after(node.arguments.last, ')') + corrector.insert_after(node.last_argument, ')') end def remove_incorrect_closing_paren(node, corrector) @@ -271,7 +271,7 @@ def fix_external_trailing_comma(node, corrector) def add_correct_external_trailing_comma(node, corrector) return unless external_trailing_comma?(node) - corrector.insert_after(node.arguments.last, ',') + corrector.insert_after(node.last_argument, ',') end def remove_incorrect_external_trailing_comma(node, corrector) diff --git a/lib/rubocop/cop/layout/heredoc_indentation.rb b/lib/rubocop/cop/layout/heredoc_indentation.rb index eb6d382fa74..d76f5b8d52a 100644 --- a/lib/rubocop/cop/layout/heredoc_indentation.rb +++ b/lib/rubocop/cop/layout/heredoc_indentation.rb @@ -8,7 +8,7 @@ module Layout # # Note: When ``Layout/LineLength``'s `AllowHeredoc` is false (not default), # this cop does not add any offenses for long here documents to - # avoid `Layout/LineLength`'s offenses. + # avoid ``Layout/LineLength``'s offenses. # # @example # # bad @@ -25,6 +25,9 @@ class HeredocIndentation < Base include Alignment include Heredoc extend AutoCorrector + extend TargetRubyVersion + + minimum_target_ruby_version 2.3 TYPE_MSG = 'Use %d spaces for indentation in a ' \ 'heredoc by using `<<~` instead of `%s`.' diff --git a/lib/rubocop/cop/layout/indentation_style.rb b/lib/rubocop/cop/layout/indentation_style.rb index 73a674db0a8..e2b936f733a 100644 --- a/lib/rubocop/cop/layout/indentation_style.rb +++ b/lib/rubocop/cop/layout/indentation_style.rb @@ -76,7 +76,7 @@ def find_offense(line, lineno) def autocorrect_lambda_for_tabs(corrector, range) spaces = ' ' * configured_indentation_width - corrector.replace(range, range.source.gsub(/\t/, spaces)) + corrector.replace(range, range.source.gsub("\t", spaces)) end def autocorrect_lambda_for_spaces(corrector, range) diff --git a/lib/rubocop/cop/layout/indentation_width.rb b/lib/rubocop/cop/layout/indentation_width.rb index 2cfcc46df50..415f2311b20 100644 --- a/lib/rubocop/cop/layout/indentation_width.rb +++ b/lib/rubocop/cop/layout/indentation_width.rb @@ -354,7 +354,7 @@ def skip_check?(base_loc, body_node) # Don't check indentation if the line doesn't start with the body. # For example, lines like "else do_something". first_char_pos_on_line = body_node.source_range.source_line =~ /\S/ - return true unless body_node.loc.column == first_char_pos_on_line + body_node.loc.column != first_char_pos_on_line end def offending_range(body_node, indentation) @@ -366,10 +366,10 @@ def offending_range(body_node, indentation) end def starts_with_access_modifier?(body_node) - return unless body_node.begin_type? + return false unless body_node.begin_type? starting_node = body_node.children.first - return unless starting_node + return false unless starting_node starting_node.send_type? && starting_node.bare_access_modifier? end diff --git a/lib/rubocop/cop/layout/leading_comment_space.rb b/lib/rubocop/cop/layout/leading_comment_space.rb index 9ea0ca0e419..c1035029bd5 100644 --- a/lib/rubocop/cop/layout/leading_comment_space.rb +++ b/lib/rubocop/cop/layout/leading_comment_space.rb @@ -57,7 +57,7 @@ class LeadingCommentSpace < Base def on_new_investigation processed_source.comments.each do |comment| - next unless /\A#+[^#\s=+-]/.match?(comment.text) + next unless /\A(?!#\+\+|#--)(#+[^#\s=])/.match?(comment.text) next if comment.loc.line == 1 && allowed_on_first_line?(comment) next if doxygen_comment_style?(comment) next if gemfile_ruby_comment?(comment) diff --git a/lib/rubocop/cop/layout/line_continuation_leading_space.rb b/lib/rubocop/cop/layout/line_continuation_leading_space.rb index b642087a162..afa297a2b34 100644 --- a/lib/rubocop/cop/layout/line_continuation_leading_space.rb +++ b/lib/rubocop/cop/layout/line_continuation_leading_space.rb @@ -57,16 +57,13 @@ def on_dstr(node) end_of_first_line = node.source_range.begin_pos - node.source_range.column - raw_lines(node).each_cons(2) do |raw_line_one, raw_line_two| + lines = raw_lines(node) + lines.each_cons(2).with_index(node.first_line) do |(raw_line_one, raw_line_two), line_num| end_of_first_line += raw_line_one.length - next unless continuation?(raw_line_one) + next unless continuation?(raw_line_one, line_num, node) - if enforced_style_leading? - investigate_leading_style(raw_line_one, raw_line_two, end_of_first_line) - else - investigate_trailing_style(raw_line_one, raw_line_two, end_of_first_line) - end + investigate(raw_line_one, raw_line_two, end_of_first_line) end end @@ -76,6 +73,14 @@ def raw_lines(node) processed_source.raw_source.lines[node.first_line - 1, line_range(node).size] end + def investigate(first_line, second_line, end_of_first_line) + if enforced_style_leading? + investigate_leading_style(first_line, second_line, end_of_first_line) + else + investigate_trailing_style(first_line, second_line, end_of_first_line) + end + end + def investigate_leading_style(first_line, second_line, end_of_first_line) matches = first_line.match(LEADING_STYLE_OFFENSE) return if matches.nil? @@ -98,8 +103,11 @@ def investigate_trailing_style(first_line, second_line, end_of_first_line) end end - def continuation?(line) - line.end_with?("\\\n") + def continuation?(line, line_num, node) + return false unless line.end_with?("\\\n") + + # Ensure backslash isn't part of a token spanning to the next line. + node.children.none? { |c| (c.first_line...c.last_line).cover?(line_num) && c.multiline? } end def autocorrect(corrector, offense_range, insert_pos, spaces) diff --git a/lib/rubocop/cop/layout/line_continuation_spacing.rb b/lib/rubocop/cop/layout/line_continuation_spacing.rb index 536b4448fbc..f400b01bfb4 100644 --- a/lib/rubocop/cop/layout/line_continuation_spacing.rb +++ b/lib/rubocop/cop/layout/line_continuation_spacing.rb @@ -109,7 +109,7 @@ def ignored_literal_ranges(ast) # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def comment_ranges(comments) - comments.map(&:loc).map(&:expression) + comments.map(&:source_range) end def last_line(processed_source) diff --git a/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb b/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb index d78dcb0757c..aa445ad6a9b 100644 --- a/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb +++ b/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb @@ -84,6 +84,8 @@ def on_dstr(node) return unless strings_concatenated_with_backslash?(node) children = node.children + return if children.empty? + if style == :aligned && !always_indented?(node) check_aligned(children, 1) else diff --git a/lib/rubocop/cop/layout/multiline_method_call_indentation.rb b/lib/rubocop/cop/layout/multiline_method_call_indentation.rb index a82640fae8d..aa6c1c723ab 100644 --- a/lib/rubocop/cop/layout/multiline_method_call_indentation.rb +++ b/lib/rubocop/cop/layout/multiline_method_call_indentation.rb @@ -75,7 +75,7 @@ def relevant_node?(send_node) def right_hand_side(send_node) dot = send_node.loc.dot selector = send_node.loc.selector - if send_node.dot? && selector && same_line?(dot, selector) + if (send_node.dot? || send_node.safe_navigation?) && selector && same_line?(dot, selector) dot.join(selector) elsif selector selector @@ -179,10 +179,10 @@ def syntactic_alignment_base(lhs, rhs) # a.b # .c def semantic_alignment_base(node, rhs) - return unless rhs.source.start_with?('.') + return unless rhs.source.start_with?('.', '&.') node = semantic_alignment_node(node) - return unless node&.loc&.selector + return unless node&.loc&.selector && node.loc.dot node.loc.dot.join(node.loc.selector) end @@ -204,6 +204,10 @@ def semantic_alignment_node(node) dot_right_above = get_dot_right_above(node) return dot_right_above if dot_right_above + if (multiline_block_chain_node = find_multiline_block_chain_node(node)) + return multiline_block_chain_node + end + node = first_call_has_a_dot(node) return if node.loc.dot.line != node.first_line @@ -219,6 +223,17 @@ def get_dot_right_above(node) end end + def find_multiline_block_chain_node(node) + return unless (block_node = node.each_descendant(:block, :numblock).first) + return unless block_node.multiline? && block_node.parent.call_type? + + if node.receiver.call_type? + node.receiver + else + block_node.parent + end + end + def first_call_has_a_dot(node) # descend to root of method chain node = node.receiver while node.receiver diff --git a/lib/rubocop/cop/layout/redundant_line_break.rb b/lib/rubocop/cop/layout/redundant_line_break.rb index 6d029e92f8e..c6406ed3410 100644 --- a/lib/rubocop/cop/layout/redundant_line_break.rb +++ b/lib/rubocop/cop/layout/redundant_line_break.rb @@ -48,6 +48,10 @@ class RedundantLineBreak < Base MSG = 'Redundant line break detected.' + def on_lvasgn(node) + super unless end_with_percent_blank_string?(processed_source) + end + def on_send(node) # Include "the whole expression". node = node.parent while node.parent&.send_type? || @@ -58,9 +62,14 @@ def on_send(node) register_offense(node) end + alias on_csend on_send private + def end_with_percent_blank_string?(processed_source) + processed_source.buffer.source.end_with?("%\n\n") + end + def check_assignment(node, _rhs) return unless offense?(node) @@ -76,7 +85,13 @@ def register_offense(node) def offense?(node) node.multiline? && !too_long?(node) && suitable_as_single_line?(node) && - !configured_to_not_be_inspected?(node) + !index_access_call_chained?(node) && !configured_to_not_be_inspected?(node) + end + + def index_access_call_chained?(node) + return false unless node.send_type? && node.method?(:[]) + + node.children.first.send_type? && node.children.first.method?(:[]) end def configured_to_not_be_inspected?(node) @@ -98,9 +113,9 @@ def single_line_block_chain_enabled? def suitable_as_single_line?(node) !comment_within?(node) && - node.each_descendant(:if, :case, :kwbegin, :def).none? && + node.each_descendant(:if, :case, :kwbegin, :def, :defs).none? && node.each_descendant(:dstr, :str).none? { |n| n.heredoc? || n.value.include?("\n") } && - node.each_descendant(:begin).none? { |b| !b.single_line? } + node.each_descendant(:begin, :sym).none? { |b| !b.single_line? } end def convertible_block?(node) @@ -110,7 +125,9 @@ def convertible_block?(node) end def comment_within?(node) - processed_source.comments.map(&:loc).map(&:line).any? do |comment_line_number| + comment_line_numbers = processed_source.comments.map { |comment| comment.loc.line } + + comment_line_numbers.any? do |comment_line_number| comment_line_number >= node.first_line && comment_line_number <= node.last_line end end @@ -125,7 +142,7 @@ def to_single_line(source) .gsub(/" *\\\n\s*'/, %q(" + ')) # Double quote, backslash, and then single quote .gsub(/' *\\\n\s*"/, %q(' + ")) # Single quote, backslash, and then double quote .gsub(/(["']) *\\\n\s*\1/, '') # Double or single quote, backslash, then same quote - .gsub(/\n\s*(?=\.\w)/, '') # Extra space within method chaining + .gsub(/\n\s*(?=(&)?\.\w)/, '') # Extra space within method chaining which includes `&.` .gsub(/\s*\\?\n\s*/, ' ') # Any other line break, with or without backslash end diff --git a/lib/rubocop/cop/layout/rescue_ensure_alignment.rb b/lib/rubocop/cop/layout/rescue_ensure_alignment.rb index 3b8a741c7e5..23d7ea20a19 100644 --- a/lib/rubocop/cop/layout/rescue_ensure_alignment.rb +++ b/lib/rubocop/cop/layout/rescue_ensure_alignment.rb @@ -29,7 +29,7 @@ class RescueEnsureAlignment < Base MSG = '`%s` at %d, %d is not ' \ 'aligned with `%s` at ' \ '%d, %d.' - ANCESTOR_TYPES = %i[kwbegin def defs class module block].freeze + ANCESTOR_TYPES = %i[kwbegin def defs class module block numblock].freeze ANCESTOR_TYPES_WITH_ACCESS_MODIFIERS = %i[def defs].freeze ALTERNATIVE_ACCESS_MODIFIERS = %i[public_class_method private_class_method].freeze @@ -95,7 +95,7 @@ def format_message(alignment_node, alignment_loc, kw_loc) def alignment_source(node, starting_loc) ending_loc = case node.type - when :block, :kwbegin + when :block, :numblock, :kwbegin node.loc.begin when :def, :defs, :class, :module, :lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn @@ -104,8 +104,8 @@ def alignment_source(node, starting_loc) mlhs_node, = *node mlhs_node.source_range else - # It is a wrapper with access modifier. - node.child_nodes.first.loc.name + # It is a wrapper with receiver of object attribute or access modifier. + node.receiver&.source_range || node.child_nodes.first.loc.name end range_between(starting_loc.begin_pos, ending_loc.end_pos).source diff --git a/lib/rubocop/cop/layout/single_line_block_chain.rb b/lib/rubocop/cop/layout/single_line_block_chain.rb index d329df92a00..fecc79eda05 100644 --- a/lib/rubocop/cop/layout/single_line_block_chain.rb +++ b/lib/rubocop/cop/layout/single_line_block_chain.rb @@ -25,10 +25,15 @@ class SingleLineBlockChain < Base MSG = 'Put method call on a separate line if chained to a single line block.' + def self.autocorrect_incompatible_with + [Style::MapToHash] + end + def on_send(node) range = offending_range(node) add_offense(range) { |corrector| corrector.insert_before(range, "\n") } if range end + alias on_csend on_send private diff --git a/lib/rubocop/cop/layout/space_after_comma.rb b/lib/rubocop/cop/layout/space_after_comma.rb index 773ac114715..e51a26373ab 100644 --- a/lib/rubocop/cop/layout/space_after_comma.rb +++ b/lib/rubocop/cop/layout/space_after_comma.rb @@ -24,7 +24,15 @@ def space_style_before_rcurly end def kind(token) - 'comma' if token.comma? + 'comma' if token.comma? && !before_semicolon?(token) + end + + private + + def before_semicolon?(token) + tokens = processed_source.tokens + + tokens[tokens.index(token) + 1].semicolon? end end end diff --git a/lib/rubocop/cop/layout/space_after_not.rb b/lib/rubocop/cop/layout/space_after_not.rb index 41822579e1d..1f3fdaf1bb0 100644 --- a/lib/rubocop/cop/layout/space_after_not.rb +++ b/lib/rubocop/cop/layout/space_after_not.rb @@ -31,7 +31,7 @@ def on_send(node) private def whitespace_after_operator?(node) - node.receiver.loc.column - node.loc.column > 1 + node.receiver.source_range.begin_pos - node.source_range.begin_pos > 1 end end end diff --git a/lib/rubocop/cop/layout/space_around_method_call_operator.rb b/lib/rubocop/cop/layout/space_around_method_call_operator.rb index 319242c78de..03c088d1740 100644 --- a/lib/rubocop/cop/layout/space_around_method_call_operator.rb +++ b/lib/rubocop/cop/layout/space_around_method_call_operator.rb @@ -19,7 +19,7 @@ module Layout # foo &. bar # foo &. bar&. buzz # RuboCop:: Cop - # RuboCop:: Cop:: Cop + # RuboCop:: Cop:: Base # :: RuboCop::Cop # # # good @@ -31,7 +31,7 @@ module Layout # foo&.bar # foo&.bar&.buzz # RuboCop::Cop - # RuboCop::Cop::Cop + # RuboCop::Cop::Base # ::RuboCop::Cop # class SpaceAroundMethodCallOperator < Base diff --git a/lib/rubocop/cop/layout/space_around_operators.rb b/lib/rubocop/cop/layout/space_around_operators.rb index 207457bb48a..f00f02248ee 100644 --- a/lib/rubocop/cop/layout/space_around_operators.rb +++ b/lib/rubocop/cop/layout/space_around_operators.rb @@ -50,6 +50,20 @@ module Layout # # # good # a ** b + # + # @example EnforcedStyleForRationalLiterals: no_space (default) + # # bad + # 1 / 48r + # + # # good + # 1/48r + # + # @example EnforcedStyleForRationalLiterals: space + # # bad + # 1/48r + # + # # good + # 1 / 48r class SpaceAroundOperators < Base include PrecedingFollowingAlignment include RangeHelp @@ -64,7 +78,7 @@ def self.autocorrect_incompatible_with end def on_sclass(node) - check_operator(:sclass, node.loc.operator, node.source_range) + check_operator(:sclass, node.loc.operator, node) end def on_pair(node) @@ -72,14 +86,14 @@ def on_pair(node) return if hash_table_style? && !node.parent.pairs_on_same_line? - check_operator(:pair, node.loc.operator, node.source_range) + check_operator(:pair, node.loc.operator, node) end def on_if(node) return unless node.ternary? - check_operator(:if, node.loc.question, node.if_branch.source_range) - check_operator(:if, node.loc.colon, node.else_branch.source_range) + check_operator(:if, node.loc.question, node.if_branch) + check_operator(:if, node.loc.colon, node.else_branch) end def on_resbody(node) @@ -87,7 +101,7 @@ def on_resbody(node) _, variable, = *node - check_operator(:resbody, node.loc.assoc, variable.source_range) + check_operator(:resbody, node.loc.assoc, variable) end def on_send(node) @@ -96,7 +110,7 @@ def on_send(node) if node.setter_method? on_special_asgn(node) elsif regular_operator?(node) - check_operator(:send, node.loc.selector, node.first_argument.source_range) + check_operator(:send, node.loc.selector, node.first_argument) end end @@ -105,7 +119,7 @@ def on_assignment(node) return unless rhs - check_operator(:assignment, node.loc.operator, rhs.source_range) + check_operator(:assignment, node.loc.operator, rhs) end def on_casgn(node) @@ -113,7 +127,7 @@ def on_casgn(node) return unless right - check_operator(:assignment, node.loc.operator, right.source_range) + check_operator(:assignment, node.loc.operator, right) end def on_binary(node) @@ -121,7 +135,7 @@ def on_binary(node) return unless rhs - check_operator(:binary, node.loc.operator, rhs.source_range) + check_operator(:binary, node.loc.operator, rhs) end def on_special_asgn(node) @@ -129,13 +143,13 @@ def on_special_asgn(node) return unless right - check_operator(:special_asgn, node.loc.operator, right.source_range) + check_operator(:special_asgn, node.loc.operator, right) end def on_match_pattern(node) return if target_ruby_version < 3.0 - check_operator(:match_pattern, node.loc.operator, node.source_range) + check_operator(:match_pattern, node.loc.operator, node) end alias on_or on_binary @@ -153,7 +167,9 @@ def on_match_pattern(node) private def regular_operator?(send_node) - !send_node.unary_operation? && !send_node.dot? && operator_with_regular_syntax?(send_node) + return false if send_node.unary_operation? || send_node.dot? || send_node.double_colon? + + operator_with_regular_syntax?(send_node) end def operator_with_regular_syntax?(send_node) @@ -166,7 +182,7 @@ def check_operator(type, operator, right_operand) offense(type, operator, with_space, right_operand) do |msg| add_offense(operator, message: msg) do |corrector| - autocorrect(corrector, with_space) + autocorrect(corrector, with_space, right_operand) end end end @@ -176,11 +192,15 @@ def offense(type, operator, with_space, right_operand) yield msg if msg end - def autocorrect(corrector, range) - if range.source.include?('**') && !space_around_exponent_operator? + def autocorrect(corrector, range, right_operand) + range_source = range.source + + if range_source.include?('**') && !space_around_exponent_operator? corrector.replace(range, '**') - elsif range.source.end_with?("\n") - corrector.replace(range, " #{range.source.strip}\n") + elsif range_source.include?('/') && !space_around_slash_operator?(right_operand) + corrector.replace(range, '/') + elsif range_source.end_with?("\n") + corrector.replace(range, " #{range_source.strip}\n") else enclose_operator_with_space(corrector, range) end @@ -200,14 +220,14 @@ def enclose_operator_with_space(corrector, range) end def offense_message(type, operator, with_space, right_operand) - if should_not_have_surrounding_space?(operator) + if should_not_have_surrounding_space?(operator, right_operand) return if with_space.is?(operator.source) "Space around operator `#{operator.source}` detected." elsif !/^\s.*\s$/.match?(with_space.source) "Surrounding space missing for operator `#{operator.source}`." elsif excess_leading_space?(type, operator, with_space) || - excess_trailing_space?(right_operand, with_space) + excess_trailing_space?(right_operand.source_range, with_space) "Operator `#{operator.source}` should be surrounded " \ 'by a single space.' end @@ -245,12 +265,24 @@ def space_around_exponent_operator? cop_config['EnforcedStyleForExponentOperator'] == 'space' end + def space_around_slash_operator?(right_operand) + return true unless right_operand.rational_type? + + cop_config['EnforcedStyleForRationalLiterals'] == 'space' + end + def force_equal_sign_alignment? config.for_cop('Layout/ExtraSpacing')['ForceEqualSignAlignment'] end - def should_not_have_surrounding_space?(operator) - operator.is?('**') ? !space_around_exponent_operator? : false + def should_not_have_surrounding_space?(operator, right_operand) + if operator.is?('**') + !space_around_exponent_operator? + elsif operator.is?('/') + !space_around_slash_operator?(right_operand) + else + false + end end end end diff --git a/lib/rubocop/cop/layout/space_inside_parens.rb b/lib/rubocop/cop/layout/space_inside_parens.rb index caeb3c244c9..2d577cf5e15 100644 --- a/lib/rubocop/cop/layout/space_inside_parens.rb +++ b/lib/rubocop/cop/layout/space_inside_parens.rb @@ -168,7 +168,7 @@ def can_be_ignored?(token1, token2) # follows, and that the rules for space inside don't apply. return true if token2.comment? - return true unless same_line?(token1, token2) && !token1.space_after? + !same_line?(token1, token2) || token1.space_after? end end end diff --git a/lib/rubocop/cop/layout/space_inside_range_literal.rb b/lib/rubocop/cop/layout/space_inside_range_literal.rb index 4419dba0fd7..bf85cd67a12 100644 --- a/lib/rubocop/cop/layout/space_inside_range_literal.rb +++ b/lib/rubocop/cop/layout/space_inside_range_literal.rb @@ -35,7 +35,7 @@ def on_erange(node) def check(node) expression = node.source op = node.loc.operator.source - escaped_op = op.gsub(/\./, '\.') + escaped_op = op.gsub('.', '\.') # account for multiline range literals expression.sub!(/#{escaped_op}\n\s*/, op) diff --git a/lib/rubocop/cop/layout/trailing_empty_lines.rb b/lib/rubocop/cop/layout/trailing_empty_lines.rb index 73f6c6a7ce9..dd76435ec4b 100644 --- a/lib/rubocop/cop/layout/trailing_empty_lines.rb +++ b/lib/rubocop/cop/layout/trailing_empty_lines.rb @@ -51,6 +51,7 @@ def on_new_investigation # there could be good reasons why it needs to end with a certain # number of newlines. return if ends_in_end?(processed_source) + return if end_with_percent_blank_string?(processed_source) whitespace_at_end = buffer.source[/\s*\Z/] blank_lines = whitespace_at_end.count("\n") - 1 @@ -86,6 +87,10 @@ def ends_in_end?(processed_source) extra&.strip&.start_with?('__END__') end + def end_with_percent_blank_string?(processed_source) + processed_source.buffer.source.end_with?("%\n\n") + end + def message(wanted_blank_lines, blank_lines) case blank_lines when -1 diff --git a/lib/rubocop/cop/lint/assignment_in_condition.rb b/lib/rubocop/cop/lint/assignment_in_condition.rb index 319f6c9ce0f..d90bd310617 100644 --- a/lib/rubocop/cop/lint/assignment_in_condition.rb +++ b/lib/rubocop/cop/lint/assignment_in_condition.rb @@ -17,24 +17,24 @@ module Lint # # @example # # bad - # if some_var = true + # if some_var = value # do_something # end # # # good - # if some_var == true + # if some_var == value # do_something # end # # @example AllowSafeAssignment: true (default) # # good - # if (some_var = true) + # if (some_var = value) # do_something # end # # @example AllowSafeAssignment: false # # bad - # if (some_var = true) + # if (some_var = value) # do_something # end # diff --git a/lib/rubocop/cop/lint/binary_operator_with_identical_operands.rb b/lib/rubocop/cop/lint/binary_operator_with_identical_operands.rb index 37732b1a8ad..dcd4cd09a21 100644 --- a/lib/rubocop/cop/lint/binary_operator_with_identical_operands.rb +++ b/lib/rubocop/cop/lint/binary_operator_with_identical_operands.rb @@ -6,10 +6,10 @@ module Lint # Checks for places where binary operator has identical operands. # # It covers arithmetic operators: `-`, `/`, `%`; - # comparison operators: `==`, `===`, `=~`, `>`, `>=`, `<`, `<=`; + # comparison operators: `==`, `===`, `=~`, `>`, `>=`, `<`, ``<=``; # bitwise operators: `|`, `^`, `&`; # boolean operators: `&&`, `||` - # and "spaceship" operator - `<=>`. + # and "spaceship" operator - ``<=>``. # # Simple arithmetic operations are allowed by this cop: `+`, `*`, `**`, `<<` and `>>`. # Although these can be rewritten in a different way, it should not be necessary to diff --git a/lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb b/lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb index 3dcbec2ec63..2256784149d 100644 --- a/lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb +++ b/lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb @@ -3,7 +3,7 @@ module RuboCop module Cop module Lint - # Checks for overwriting an exception with an exception result by use `rescue =>`. + # Checks for overwriting an exception with an exception result by use ``rescue =>``. # # You intended to write as `rescue StandardError`. # However, you have written `rescue => StandardError`. diff --git a/lib/rubocop/cop/lint/debugger.rb b/lib/rubocop/cop/lint/debugger.rb index 6cf1a13f2a3..f178d4828b4 100644 --- a/lib/rubocop/cop/lint/debugger.rb +++ b/lib/rubocop/cop/lint/debugger.rb @@ -66,12 +66,10 @@ module Lint # end class Debugger < Base MSG = 'Remove debugger entry point `%s`.' + BLOCK_TYPES = %i[block numblock kwbegin].freeze def on_send(node) - return unless debugger_method?(node) - - # Basically, debugger methods are not used as a method argument without arguments. - return if node.arguments.empty? && node.each_ancestor(:send, :csend).any? + return if !debugger_method?(node) || assumed_usage_context?(node) add_offense(node) end @@ -90,11 +88,21 @@ def debugger_methods end def debugger_method?(send_node) - return if send_node.parent&.send_type? && send_node.parent.receiver == send_node + return false if send_node.parent&.send_type? && send_node.parent.receiver == send_node debugger_methods.include?(chained_method_name(send_node)) end + def assumed_usage_context?(node) + # Basically, debugger methods are not used as a method argument without arguments. + return false unless node.arguments.empty? && node.each_ancestor(:send, :csend).any? + return true if assumed_argument?(node) + + node.each_ancestor.none? do |ancestor| + BLOCK_TYPES.include?(ancestor.type) || ancestor.lambda_or_proc? + end + end + def chained_method_name(send_node) chained_method_name = send_node.method_name.to_s receiver = send_node.receiver @@ -105,6 +113,12 @@ def chained_method_name(send_node) end chained_method_name end + + def assumed_argument?(node) + parent = node.parent + + parent.call_type? || parent.literal? || parent.pair_type? + end end end end diff --git a/lib/rubocop/cop/lint/duplicate_hash_key.rb b/lib/rubocop/cop/lint/duplicate_hash_key.rb index 8c572fcc894..e0b42e71f9b 100644 --- a/lib/rubocop/cop/lint/duplicate_hash_key.rb +++ b/lib/rubocop/cop/lint/duplicate_hash_key.rb @@ -4,6 +4,7 @@ module RuboCop module Cop module Lint # Checks for duplicated keys in hash literals. + # This cop considers both primitive types and constants for the hash keys. # # This cop mirrors a warning in Ruby 2.2. # @@ -24,7 +25,7 @@ class DuplicateHashKey < Base MSG = 'Duplicated key in hash literal.' def on_hash(node) - keys = node.keys.select(&:recursive_basic_literal?) + keys = node.keys.select { |key| key.recursive_basic_literal? || key.const_type? } return unless duplicates?(keys) diff --git a/lib/rubocop/cop/lint/duplicate_methods.rb b/lib/rubocop/cop/lint/duplicate_methods.rb index 12c4dd6003a..ffd584188ce 100644 --- a/lib/rubocop/cop/lint/duplicate_methods.rb +++ b/lib/rubocop/cop/lint/duplicate_methods.rb @@ -253,7 +253,7 @@ def possible_dsl?(node) # Assume that if a method definition is inside any block call which # we can't identify, it could be a DSL node.each_ancestor(:block).any? do |ancestor| - ancestor.method_name != :class_eval && !ancestor.class_constructor? + !ancestor.method?(:class_eval) && !ancestor.class_constructor? end end diff --git a/lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb b/lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb index c4f82a71359..7b6fec46e2d 100644 --- a/lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb +++ b/lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb @@ -24,6 +24,8 @@ class DuplicateRegexpCharacterClassElement < Base MSG_REPEATED_ELEMENT = 'Duplicate element inside regexp character class' + OCTAL_DIGITS_AFTER_ESCAPE = 2 + def on_regexp(node) each_repeated_character_class_element_loc(node) do |loc| add_offense(loc, message: MSG_REPEATED_ELEMENT) do |corrector| @@ -32,35 +34,57 @@ def on_regexp(node) end end - # rubocop:disable Metrics/AbcSize, Metrics/MethodLength def each_repeated_character_class_element_loc(node) node.parsed_tree&.each_expression do |expr| next if skip_expression?(expr) seen = Set.new - enum = expr.expressions.to_enum - expression_count = expr.expressions.count + group_expressions(node, expr.expressions) do |group| + group_source = group.map(&:to_s).join - expression_count.times do |current_number| - current_child = enum.next - next if within_interpolation?(node, current_child) + yield source_range(group) if seen.include?(group_source) - current_child_source = current_child.to_s - next_child = enum.peek if current_number + 1 < expression_count + seen << group_source + end + end + end - if seen.include?(current_child_source) - next if start_with_escaped_zero_number?(current_child_source, next_child.to_s) + private - yield current_child.expression - end + def group_expressions(node, expressions) + # Create a mutable list to simplify state tracking while we iterate. + expressions = expressions.to_a - seen << current_child_source - end + until expressions.empty? + # With we may need to compose a group of multiple expressions. + group = [expressions.shift] + next if within_interpolation?(node, group.first) + + # With regexp_parser < 2.7 escaped octal sequences may be up to 3 + # separate expressions ("\\0", "0", "1"). + pop_octal_digits(group, expressions) if escaped_octal?(group.first.to_s) + + yield(group) end end - # rubocop:enable Metrics/AbcSize, Metrics/MethodLength - private + def pop_octal_digits(current_child, expressions) + OCTAL_DIGITS_AFTER_ESCAPE.times do + next_child = expressions.first + break unless octal?(next_child.to_s) + + current_child << expressions.shift + end + end + + def source_range(children) + return children.first.expression if children.size == 1 + + range_between( + children.first.expression.begin_pos, + children.last.expression.begin_pos + children.last.to_s.length + ) + end def skip_expression?(expr) expr.type != :set || expr.token == :intersection @@ -75,9 +99,12 @@ def within_interpolation?(node, child) interpolation_locs(node).any? { |il| il.overlaps?(parse_tree_child_loc) } end - def start_with_escaped_zero_number?(current_child, next_child) - # Represents escaped code from `"\00"` (`"\u0000"`) to `"\07"` (`"\a"`). - current_child == '\\0' && next_child.match?(/[0-7]/) + def escaped_octal?(string) + string.length == 2 && string[0] == '\\' && octal?(string[1]) + end + + def octal?(char) + ('0'..'7').cover?(char) end def interpolation_locs(node) diff --git a/lib/rubocop/cop/lint/empty_block.rb b/lib/rubocop/cop/lint/empty_block.rb index b401efd5d02..87073ba113d 100644 --- a/lib/rubocop/cop/lint/empty_block.rb +++ b/lib/rubocop/cop/lint/empty_block.rb @@ -5,7 +5,7 @@ module Cop module Lint # Checks for blocks without a body. # Such empty blocks are typically an oversight or we should provide a comment - # be clearer what we're aiming for. + # to clarify what we're aiming for. # # Empty lambdas and procs are ignored by default. # diff --git a/lib/rubocop/cop/lint/empty_conditional_body.rb b/lib/rubocop/cop/lint/empty_conditional_body.rb index 97a7ca07857..39135a59e56 100644 --- a/lib/rubocop/cop/lint/empty_conditional_body.rb +++ b/lib/rubocop/cop/lint/empty_conditional_body.rb @@ -104,7 +104,7 @@ def remove_empty_branch(corrector, node) def correct_other_branches(corrector, node) return unless require_other_branches_correction?(node) - if node.else_branch&.if_type? + if node.else_branch&.if_type? && !node.else_branch.modifier_form? # Replace an orphaned `elsif` with `if` corrector.replace(node.else_branch.loc.keyword, 'if') else diff --git a/lib/rubocop/cop/lint/erb_new_arguments.rb b/lib/rubocop/cop/lint/erb_new_arguments.rb index 1a44130264b..6bfadbe57bc 100644 --- a/lib/rubocop/cop/lint/erb_new_arguments.rb +++ b/lib/rubocop/cop/lint/erb_new_arguments.rb @@ -106,7 +106,7 @@ def on_send(node) private def autocorrect(corrector, node) - str_arg = node.arguments[0].source + str_arg = node.first_argument.source kwargs = build_kwargs(node) overridden_kwargs = override_by_legacy_args(kwargs, node) @@ -121,11 +121,11 @@ def correct_arguments?(arguments) end def build_kwargs(node) - return [nil, nil] unless node.arguments.last.hash_type? + return [nil, nil] unless node.last_argument.hash_type? trim_mode_arg, eoutvar_arg = nil - node.arguments.last.pairs.each do |pair| + node.last_argument.pairs.each do |pair| case pair.key.source when 'trim_mode' trim_mode_arg = "trim_mode: #{pair.value.source}" diff --git a/lib/rubocop/cop/lint/float_comparison.rb b/lib/rubocop/cop/lint/float_comparison.rb index eacc56976bf..99cc78ccf8d 100644 --- a/lib/rubocop/cop/lint/float_comparison.rb +++ b/lib/rubocop/cop/lint/float_comparison.rb @@ -18,6 +18,10 @@ module Lint # # good - using BigDecimal # x.to_d == 0.1.to_d # + # # good - comparing against zero + # x == 0.0 + # x != 0.0 + # # # good # (x - 0.1).abs < Float::EPSILON # @@ -39,6 +43,8 @@ class FloatComparison < Base def on_send(node) lhs, _method, rhs = *node + return if literal_zero?(lhs) || literal_zero?(rhs) + add_offense(node) if float?(lhs) || float?(rhs) end @@ -59,6 +65,10 @@ def float?(node) end end + def literal_zero?(node) + node&.numeric_type? && node.value.zero? + end + # rubocop:disable Metrics/PerceivedComplexity def check_send(node) if node.arithmetic_operation? diff --git a/lib/rubocop/cop/lint/hash_compare_by_identity.rb b/lib/rubocop/cop/lint/hash_compare_by_identity.rb index 5305e48277d..8cb8661866e 100644 --- a/lib/rubocop/cop/lint/hash_compare_by_identity.rb +++ b/lib/rubocop/cop/lint/hash_compare_by_identity.rb @@ -35,12 +35,13 @@ class HashCompareByIdentity < Base # @!method id_as_hash_key?(node) def_node_matcher :id_as_hash_key?, <<~PATTERN - (send _ {:key? :has_key? :fetch :[] :[]=} (send _ :object_id) ...) + (call _ {:key? :has_key? :fetch :[] :[]=} (send _ :object_id) ...) PATTERN def on_send(node) add_offense(node) if id_as_hash_key?(node) end + alias on_csend on_send end end end diff --git a/lib/rubocop/cop/lint/heredoc_method_call_position.rb b/lib/rubocop/cop/lint/heredoc_method_call_position.rb index 0c3c5a2b307..5b423de9b76 100644 --- a/lib/rubocop/cop/lint/heredoc_method_call_position.rb +++ b/lib/rubocop/cop/lint/heredoc_method_call_position.rb @@ -65,7 +65,7 @@ def heredoc_node_descendent_receiver(node) end def send_node?(node) - return nil unless node + return false unless node node.call_type? end diff --git a/lib/rubocop/cop/lint/it_without_arguments_in_block.rb b/lib/rubocop/cop/lint/it_without_arguments_in_block.rb new file mode 100644 index 00000000000..1460457d10f --- /dev/null +++ b/lib/rubocop/cop/lint/it_without_arguments_in_block.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Lint + # Emulates the following Ruby warning in Ruby 3.3. + # + # [source,ruby] + # ---- + # $ ruby -e '0.times { it }' + # -e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; + # use it() or self.it + # ---- + # + # `it` calls without arguments will refer to the first block param in Ruby 3.4. + # So use `it()` or `self.it` to ensure compatibility. + # + # @example + # + # # bad + # do_something { it } + # + # # good + # do_something { it() } + # do_something { self.it } + # + class ItWithoutArgumentsInBlock < Base + include NodePattern::Macros + + MSG = '`it` calls without arguments will refer to the first block param in Ruby 3.4; ' \ + 'use `it()` or `self.it`.' + + def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler + return unless (body = node.body) + return unless node.arguments.empty_and_without_delimiters? + + if body.send_type? && deprecated_it_method?(body) + add_offense(body) + else + body.each_descendant(:send).each do |send_node| + next unless deprecated_it_method?(send_node) + + add_offense(send_node) + end + end + end + + def deprecated_it_method?(node) + return false unless node.method?(:it) + + !node.receiver && node.arguments.empty? && !node.parenthesized? && !node.block_literal? + end + end + end + end +end diff --git a/lib/rubocop/cop/lint/literal_assignment_in_condition.rb b/lib/rubocop/cop/lint/literal_assignment_in_condition.rb new file mode 100644 index 00000000000..a922ba916af --- /dev/null +++ b/lib/rubocop/cop/lint/literal_assignment_in_condition.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Lint + # Checks for literal assignments in the conditions of `if`, `while`, and `until`. + # It emulates the following Ruby warning: + # + # [source,console] + # ---- + # $ ruby -we 'if x = true; end' + # -e:1: warning: found `= literal' in conditional, should be == + # ---- + # + # As a lint cop, it cannot be determined if `==` is appropriate as intended, + # therefore this cop does not provide autocorrection. + # + # @example + # + # # bad + # if x = 42 + # do_something + # end + # + # # good + # if x == 42 + # do_something + # end + # + # # good + # if x = y + # do_something + # end + # + class LiteralAssignmentInCondition < Base + MSG = "Don't use literal assignment `= %s` in conditional, " \ + 'should be `==` or non-literal operand.' + + def on_if(node) + traverse_node(node.condition) do |asgn_node| + next unless asgn_node.loc.operator + + rhs = asgn_node.to_a.last + next if !all_literals?(rhs) || parallel_assignment_with_splat_operator?(rhs) + + range = offense_range(asgn_node, rhs) + + add_offense(range, message: format(MSG, literal: rhs.source)) + end + end + alias on_while on_if + alias on_until on_if + + private + + def traverse_node(node, &block) + yield node if AST::Node::EQUALS_ASSIGNMENTS.include?(node.type) + + node.each_child_node { |child| traverse_node(child, &block) } + end + + def all_literals?(node) + case node.type + when :dstr, :xstr + false + when :array + node.values.all? { |value| all_literals?(value) } + when :hash + (node.values + node.keys).all? { |item| all_literals?(item) } + else + node.respond_to?(:literal?) && node.literal? + end + end + + def parallel_assignment_with_splat_operator?(node) + node.array_type? && node.values.first&.splat_type? + end + + def offense_range(asgn_node, rhs) + asgn_node.loc.operator.join(rhs.source_range.end) + end + end + end + end +end diff --git a/lib/rubocop/cop/lint/literal_in_interpolation.rb b/lib/rubocop/cop/lint/literal_in_interpolation.rb index ab2e2539d06..e1d18ba8a91 100644 --- a/lib/rubocop/cop/lint/literal_in_interpolation.rb +++ b/lib/rubocop/cop/lint/literal_in_interpolation.rb @@ -34,7 +34,7 @@ def on_interpolation(begin_node) # interpolation should not be removed if the expanded value # contains a space character. expanded_value = autocorrected_value(final_node) - return if in_array_percent_literal?(begin_node) && /\s/.match?(expanded_value) + return if in_array_percent_literal?(begin_node) && /\s|\A\z/.match?(expanded_value) add_offense(final_node) do |corrector| return if final_node.dstr_type? # nested, fixed in next iteration diff --git a/lib/rubocop/cop/lint/missing_super.rb b/lib/rubocop/cop/lint/missing_super.rb index 8894a7059eb..52aec37ea8b 100644 --- a/lib/rubocop/cop/lint/missing_super.rb +++ b/lib/rubocop/cop/lint/missing_super.rb @@ -14,6 +14,13 @@ module Lint # Autocorrection is not supported because the position of `super` cannot be # determined automatically. # + # `Object` and `BasicObject` are allowed by this cop because of their + # stateless nature. However, sometimes you might want to allow other parent + # classes from this cop, for example in the case of an abstract class that is + # not meant to be called with `super`. In those cases, you can use the + # `AllowedParentClasses` option to specify which classes should be allowed + # *in addition to* `Object` and `BasicObject`. + # # @example # # bad # class Employee < Person @@ -60,6 +67,21 @@ module Lint # end # end # + # # good + # class ClassWithNoParent + # def initialize + # do_something + # end + # end + # + # @example AllowedParentClasses: [MyAbstractClass] + # # good + # class MyConcreteClass < MyAbstractClass + # def initialize + # do_something + # end + # end + # class MissingSuper < Base CONSTRUCTOR_MSG = 'Call `super` to initialize state of the parent class.' CALLBACK_MSG = 'Call `super` to invoke callback defined in the parent class.' @@ -103,7 +125,7 @@ def offender?(node) end def callback_method_def?(node) - return unless CALLBACKS.include?(node.method_name) + return false unless CALLBACKS.include?(node.method_name) node.each_ancestor(:class, :sclass, :module).first end @@ -116,16 +138,20 @@ def inside_class_with_stateful_parent?(node) if (block_node = node.each_ancestor(:block, :numblock).first) return false unless (super_class = class_new_block(block_node)) - !stateless_class?(super_class) + !allowed_class?(super_class) elsif (class_node = node.each_ancestor(:class).first) - class_node.parent_class && !stateless_class?(class_node.parent_class) + class_node.parent_class && !allowed_class?(class_node.parent_class) else false end end - def stateless_class?(node) - STATELESS_CLASSES.include?(node.const_name) + def allowed_class?(node) + allowed_classes.include?(node.const_name) + end + + def allowed_classes + @allowed_classes ||= STATELESS_CLASSES + cop_config.fetch('AllowedParentClasses', []) end end end diff --git a/lib/rubocop/cop/lint/mixed_case_range.rb b/lib/rubocop/cop/lint/mixed_case_range.rb new file mode 100644 index 00000000000..b7817981483 --- /dev/null +++ b/lib/rubocop/cop/lint/mixed_case_range.rb @@ -0,0 +1,111 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Lint + # Checks for mixed-case character ranges since they include likely unintended characters. + # + # Offenses are registered for regexp character classes like `/[A-z]/` + # as well as range objects like `('A'..'z')`. + # + # NOTE: Range objects cannot be autocorrected. + # + # @safety + # The cop autocorrects regexp character classes + # by replacing one character range with two: `A-z` becomes `A-Za-z`. + # In most cases this is probably what was originally intended + # but it changes the regexp to no longer match symbols it used to include. + # For this reason, this cop's autocorrect is unsafe (it will + # change the behavior of the code). + # + # @example + # + # # bad + # r = /[A-z]/ + # + # # good + # r = /[A-Za-z]/ + class MixedCaseRange < Base + extend AutoCorrector + include RangeHelp + + MSG = 'Ranges from upper to lower case ASCII letters may include unintended ' \ + 'characters. Instead of `A-z` (which also includes several symbols) ' \ + 'specify each range individually: `A-Za-z` and individually specify any symbols.' + RANGES = [('a'..'z').freeze, ('A'..'Z').freeze].freeze + + def on_irange(node) + return unless node.children.compact.all?(&:str_type?) + + range_start, range_end = node.children + + return if range_start.nil? || range_end.nil? + + add_offense(node) if unsafe_range?(range_start.value, range_end.value) + end + alias on_erange on_irange + + def on_regexp(node) + each_unsafe_regexp_range(node) do |loc| + add_offense(loc) do |corrector| + corrector.replace(loc, rewrite_regexp_range(loc.source)) + end + end + end + + def each_unsafe_regexp_range(node) + node.parsed_tree&.each_expression do |expr| + next if skip_expression?(expr) + + range_pairs(expr).reject do |range_start, range_end| + next if skip_range?(range_start, range_end) + + next unless unsafe_range?(range_start.text, range_end.text) + + yield(build_source_range(range_start, range_end)) + end + end + end + + private + + def build_source_range(range_start, range_end) + range_between(range_start.expression.begin_pos, range_end.expression.end_pos) + end + + def range_for(char) + RANGES.detect do |range| + range.include?(char) + end + end + + def range_pairs(expr) + RuboCop::Cop::Utils::RegexpRanges.new(expr).pairs + end + + def unsafe_range?(range_start, range_end) + return false if range_start.length != 1 || range_end.length != 1 + + range_for(range_start) != range_for(range_end) + end + + def skip_expression?(expr) + !(expr.type == :set && expr.token == :character) + end + + def skip_range?(range_start, range_end) + [range_start, range_end].any? do |bound| + bound.type != :literal + end + end + + def rewrite_regexp_range(source) + open, close = source.split('-') + first = [open, range_for(open).end] + second = [range_for(close).begin, close] + "#{first.uniq.join('-')}#{second.uniq.join('-')}" + end + end + end + end +end diff --git a/lib/rubocop/cop/lint/next_without_accumulator.rb b/lib/rubocop/cop/lint/next_without_accumulator.rb index da811e60ad0..383940a54bf 100644 --- a/lib/rubocop/cop/lint/next_without_accumulator.rb +++ b/lib/rubocop/cop/lint/next_without_accumulator.rb @@ -34,35 +34,20 @@ def on_block(node) add_offense(void_next) if void_next end end - - def on_numblock(node) - on_numblock_body_of_reduce(node) do |body| - void_next = body.each_node(:next).find do |n| - n.children.empty? && parent_numblock_node(n) == node - end - - add_offense(void_next) if void_next - end - end + alias on_numblock on_block private # @!method on_block_body_of_reduce(node) def_node_matcher :on_block_body_of_reduce, <<~PATTERN - (block (send _recv {:reduce :inject} !sym) _blockargs $(begin ...)) - PATTERN - - # @!method on_numblock_body_of_reduce(node) - def_node_matcher :on_numblock_body_of_reduce, <<~PATTERN - (numblock (send _recv {:reduce :inject} !sym) _argscount $(begin ...)) + { + (block (call _recv {:reduce :inject} !sym) _blockargs $(begin ...)) + (numblock (call _recv {:reduce :inject} !sym) _argscount $(begin ...)) + } PATTERN def parent_block_node(node) - node.each_ancestor(:block).first - end - - def parent_numblock_node(node) - node.each_ancestor(:numblock).first + node.each_ancestor(:block, :numblock).first end end end diff --git a/lib/rubocop/cop/lint/non_atomic_file_operation.rb b/lib/rubocop/cop/lint/non_atomic_file_operation.rb index 2a8bbdfbbd4..553287f3472 100644 --- a/lib/rubocop/cop/lint/non_atomic_file_operation.rb +++ b/lib/rubocop/cop/lint/non_atomic_file_operation.rb @@ -43,7 +43,6 @@ module Lint # class NonAtomicFileOperation < Base extend AutoCorrector - include Alignment MSG_REMOVE_FILE_EXIST_CHECK = 'Remove unnecessary existence check ' \ '`%s.%s`.' @@ -51,18 +50,20 @@ class NonAtomicFileOperation < Base MAKE_FORCE_METHODS = %i[makedirs mkdir_p mkpath].freeze MAKE_METHODS = %i[mkdir].freeze REMOVE_FORCE_METHODS = %i[rm_f rm_rf].freeze - REMOVE_METHODS = %i[remove remove_dir remove_entry remove_entry_secure - delete unlink remove_file rm rmdir safe_unlink].freeze - RESTRICT_ON_SEND = (MAKE_METHODS + MAKE_FORCE_METHODS + REMOVE_METHODS + - REMOVE_FORCE_METHODS).freeze + REMOVE_METHODS = %i[remove delete unlink remove_file rm rmdir safe_unlink].freeze + RECURSIVE_REMOVE_METHODS = %i[remove_dir remove_entry remove_entry_secure].freeze + RESTRICT_ON_SEND = ( + MAKE_METHODS + MAKE_FORCE_METHODS + REMOVE_METHODS + RECURSIVE_REMOVE_METHODS + + REMOVE_FORCE_METHODS + ).freeze # @!method send_exist_node(node) - def_node_search :send_exist_node, <<-PATTERN + def_node_search :send_exist_node, <<~PATTERN $(send (const nil? {:FileTest :File :Dir :Shell}) {:exist? :exists?} ...) PATTERN # @!method receiver_and_method_name(node) - def_node_matcher :receiver_and_method_name, <<-PATTERN + def_node_matcher :receiver_and_method_name, <<~PATTERN (send (const nil? $_) $_ ...) PATTERN @@ -140,6 +141,8 @@ def replacement_method(node) 'mkdir_p' elsif REMOVE_METHODS.include?(node.method_name) 'rm_f' + elsif RECURSIVE_REMOVE_METHODS.include?(node.method_name) + 'rm_rf' else node.method_name end diff --git a/lib/rubocop/cop/lint/non_deterministic_require_order.rb b/lib/rubocop/cop/lint/non_deterministic_require_order.rb index 6a5aeac60bc..eaade72b3e2 100644 --- a/lib/rubocop/cop/lint/non_deterministic_require_order.rb +++ b/lib/rubocop/cop/lint/non_deterministic_require_order.rb @@ -94,7 +94,7 @@ def on_block_pass(node) parent_node = node.parent add_offense(parent_node) do |corrector| - if parent_node.arguments.last&.block_pass_type? + if parent_node.last_argument&.block_pass_type? correct_block_pass(corrector, parent_node) else correct_block(corrector, parent_node) @@ -116,7 +116,7 @@ def correct_block(corrector, node) def correct_block_pass(corrector, node) if unsorted_dir_glob_pass?(node) - block_arg = node.arguments.last + block_arg = node.last_argument corrector.remove(last_arg_range(node)) corrector.insert_after(node, ".sort.each(#{block_arg.source})") @@ -130,9 +130,7 @@ def correct_block_pass(corrector, node) # @return [Parser::Source::Range] # def last_arg_range(node) - node.arguments.last.source_range.with( - begin_pos: node.arguments[-2].source_range.end_pos - ) + node.last_argument.source_range.with(begin_pos: node.arguments[-2].source_range.end_pos) end def unsorted_dir_loop?(node) diff --git a/lib/rubocop/cop/lint/number_conversion.rb b/lib/rubocop/cop/lint/number_conversion.rb index b966ab4db69..73880285a1f 100644 --- a/lib/rubocop/cop/lint/number_conversion.rb +++ b/lib/rubocop/cop/lint/number_conversion.rb @@ -9,7 +9,7 @@ module Lint # # Conversion with `Integer`, `Float`, etc. will raise an `ArgumentError` # if given input that is not numeric (eg. an empty string), whereas - # `to_i`, etc. will try to convert regardless of input (`''.to_i => 0`). + # `to_i`, etc. will try to convert regardless of input (``''.to_i => 0``). # As such, this cop is disabled by default because it's not necessarily # always correct to raise if a value is not numeric. # @@ -91,19 +91,24 @@ class NumberConversion < Base # @!method to_method(node) def_node_matcher :to_method, <<~PATTERN - (send $_ ${#{METHODS}}) + (call $_ ${#{METHODS}}) PATTERN # @!method to_method_symbol(node) def_node_matcher :to_method_symbol, <<~PATTERN - {(send _ $_ ${(sym ${#{METHODS}})} ...) - (send _ $_ ${(block_pass (sym ${#{METHODS}}))} ...)} + (call _ $_ ${ + { + (sym ${#{METHODS}}) + (block_pass (sym ${#{METHODS}})) + } + } ...) PATTERN def on_send(node) handle_conversion_method(node) handle_as_symbol(node) end + alias on_csend on_send private diff --git a/lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb b/lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb new file mode 100644 index 00000000000..82e8fbcad97 --- /dev/null +++ b/lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb @@ -0,0 +1,130 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Lint + # Checks for redundant quantifiers inside Regexp literals. + # + # It is always allowed when interpolation is used in a regexp literal, + # because it's unknown what kind of string will be expanded as a result: + # + # [source,ruby] + # ---- + # /(?:a*#{interpolation})?/x + # ---- + # + # @example + # # bad + # /(?:x+)+/ + # + # # good + # /(?:x)+/ + # + # # good + # /(?:x+)/ + # + # # bad + # /(?:x+)?/ + # + # # good + # /(?:x)*/ + # + # # good + # /(?:x*)/ + class RedundantRegexpQuantifiers < Base + include RangeHelp + extend AutoCorrector + + MSG_REDUNDANT_QUANTIFIER = 'Replace redundant quantifiers ' \ + '`%s` and `%s` ' \ + 'with a single `%s`.' + + def on_regexp(node) + return if node.interpolation? + + each_redundantly_quantified_pair(node) do |group, child| + replacement = merged_quantifier(group, child) + add_offense( + quantifier_range(group, child), + message: message(group, child, replacement) + ) do |corrector| + # drop outer quantifier + corrector.replace(group.loc.quantifier, '') + # replace inner quantifier + corrector.replace(child.loc.quantifier, replacement) + end + end + end + + private + + def each_redundantly_quantified_pair(node) + seen = Set.new + node.parsed_tree&.each_expression do |(expr)| + next if seen.include?(expr) || !redundant_group?(expr) || !mergeable_quantifier(expr) + + expr.each_expression do |(subexp)| + seen << subexp + break unless redundantly_quantifiable?(subexp) + + yield(expr, subexp) if mergeable_quantifier(subexp) + end + end + end + + def redundant_group?(expr) + expr.is?(:passive, :group) && expr.count { |child| child.type != :free_space } == 1 + end + + def redundantly_quantifiable?(node) + redundant_group?(node) || character_set?(node) || node.terminal? + end + + def character_set?(expr) + expr.is?(:character, :set) + end + + def mergeable_quantifier(expr) + # Merging reluctant or possessive quantifiers would be more complex, + # and Ruby does not emit warnings for these cases. + return unless expr.quantifier&.greedy? + + # normalize quantifiers, e.g. "{1,}" => "+" + case expr.quantity + when [0, -1] + '*' + when [0, 1] + '?' + when [1, -1] + '+' + end + end + + def merged_quantifier(exp1, exp2) + quantifier1 = mergeable_quantifier(exp1) + quantifier2 = mergeable_quantifier(exp2) + if quantifier1 == quantifier2 + # (?:a+)+ equals (?:a+) ; (?:a*)* equals (?:a*) ; # (?:a?)? equals (?:a?) + quantifier1 + else + # (?:a+)*, (?:a+)?, (?:a*)+, (?:a*)?, (?:a?)+, (?:a?)* - all equal (?:a*) + '*' + end + end + + def quantifier_range(group, child) + range_between(child.loc.quantifier.begin_pos, group.loc.quantifier.end_pos) + end + + def message(group, child, replacement) + format( + MSG_REDUNDANT_QUANTIFIER, + inner_quantifier: child.quantifier.to_s, + outer_quantifier: group.quantifier.to_s, + replacement: replacement + ) + end + end + end + end +end diff --git a/lib/rubocop/cop/lint/redundant_require_statement.rb b/lib/rubocop/cop/lint/redundant_require_statement.rb index 1777024059b..95133baf5c1 100644 --- a/lib/rubocop/cop/lint/redundant_require_statement.rb +++ b/lib/rubocop/cop/lint/redundant_require_statement.rb @@ -24,6 +24,10 @@ module Lint # # This cop target those features. # + # @safety + # This cop's autocorrection is unsafe because if `require 'pp'` is removed from one file, + # `NameError` can be encountered when another file uses `PP.pp`. + # # @example # # bad # require 'unloaded_feature' @@ -49,6 +53,11 @@ class RedundantRequireStatement < Base (str #redundant_feature?)) PATTERN + # @!method pp_const?(node) + def_node_matcher :pp_const?, <<~PATTERN + (const {nil? cbase} :PP) + PATTERN + def on_send(node) return unless redundant_require_statement?(node) @@ -72,16 +81,16 @@ def redundant_feature?(feature_name) feature_name == 'enumerator' || (target_ruby_version >= 2.1 && feature_name == 'thread') || (target_ruby_version >= 2.2 && RUBY_22_LOADED_FEATURES.include?(feature_name)) || - (target_ruby_version >= 2.5 && feature_name == 'pp' && !use_pretty_print_method?) || + (target_ruby_version >= 2.5 && feature_name == 'pp' && !need_to_require_pp?) || (target_ruby_version >= 2.7 && feature_name == 'ruby2_keywords') || (target_ruby_version >= 3.1 && feature_name == 'fiber') || (target_ruby_version >= 3.2 && feature_name == 'set') end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity - def use_pretty_print_method? + def need_to_require_pp? processed_source.ast.each_descendant(:send).any? do |node| - PRETTY_PRINT_METHODS.include?(node.method_name) + pp_const?(node.receiver) || PRETTY_PRINT_METHODS.include?(node.method_name) end end end diff --git a/lib/rubocop/cop/lint/redundant_safe_navigation.rb b/lib/rubocop/cop/lint/redundant_safe_navigation.rb index 349e3bd29b7..0c49dbe16a9 100644 --- a/lib/rubocop/cop/lint/redundant_safe_navigation.rb +++ b/lib/rubocop/cop/lint/redundant_safe_navigation.rb @@ -4,8 +4,13 @@ module RuboCop module Cop module Lint # Checks for redundant safe navigation calls. - # `instance_of?`, `kind_of?`, `is_a?`, `eql?`, `respond_to?`, and `equal?` methods - # are checked by default. These are customizable with `AllowedMethods` option. + # Use cases where a constant, named in camel case for classes and modules is `nil` are rare, + # and an offense is not detected when the receiver is a constant. The detection also applies + # to literal receivers, except for `nil`. + # + # For all receivers, the `instance_of?`, `kind_of?`, `is_a?`, `eql?`, `respond_to?`, + # and `equal?` methods are checked by default. + # These are customizable with `AllowedMethods` option. # # The `AllowedMethods` option specifies nil-safe methods, # in other words, it is a method that is allowed to skip safe navigation. @@ -22,6 +27,9 @@ module Lint # # @example # # bad + # CamelCaseConst&.do_something + # + # # bad # do_something if attrs&.respond_to?(:[]) # # # good @@ -33,6 +41,9 @@ module Lint # end # # # good + # CamelCaseConst.do_something + # + # # good # while node.is_a?(BeginNode) # node = node.parent # end @@ -40,6 +51,22 @@ module Lint # # good - without `&.` this will always return `true` # foo&.respond_to?(:to_a) # + # # bad - for `nil`s conversion methods return default values for the type + # foo&.to_h || {} + # foo&.to_h { |k, v| [k, v] } || {} + # foo&.to_a || [] + # foo&.to_i || 0 + # foo&.to_f || 0.0 + # foo&.to_s || '' + # + # # good + # foo.to_h + # foo.to_h { |k, v| [k, v] } + # foo.to_a + # foo.to_i + # foo.to_f + # foo.to_s + # # @example AllowedMethods: [nil_safe_method] # # bad # do_something if attrs&.nil_safe_method(:[]) @@ -50,28 +77,65 @@ module Lint # class RedundantSafeNavigation < Base include AllowedMethods - include RangeHelp extend AutoCorrector - MSG = 'Redundant safe navigation detected.' + MSG = 'Redundant safe navigation detected, use `.` instead.' + MSG_LITERAL = 'Redundant safe navigation with default literal detected.' NIL_SPECIFIC_METHODS = (nil.methods - Object.new.methods).to_set.freeze + SNAKE_CASE = /\A[[:digit:][:upper:]_]+\z/.freeze + # @!method respond_to_nil_specific_method?(node) def_node_matcher :respond_to_nil_specific_method?, <<~PATTERN (csend _ :respond_to? (sym %NIL_SPECIFIC_METHODS)) PATTERN + # @!method conversion_with_default?(node) + def_node_matcher :conversion_with_default?, <<~PATTERN + { + (or $(csend _ :to_h) (hash)) + (or (block $(csend _ :to_h) ...) (hash)) + (or $(csend _ :to_a) (array)) + (or $(csend _ :to_i) (int 0)) + (or $(csend _ :to_f) (float 0.0)) + (or $(csend _ :to_s) (str empty?)) + } + PATTERN + + # rubocop:disable Metrics/AbcSize def on_csend(node) - return unless check?(node) && allowed_method?(node.method_name) - return if respond_to_nil_specific_method?(node) + unless assume_receiver_instance_exists?(node.receiver) + return unless check?(node) && allowed_method?(node.method_name) + return if respond_to_nil_specific_method?(node) + end - range = range_between(node.loc.dot.begin_pos, node.source_range.end_pos) - add_offense(range) { |corrector| corrector.replace(node.loc.dot, '.') } + range = node.loc.dot + add_offense(range) { |corrector| corrector.replace(range, '.') } end + def on_or(node) + conversion_with_default?(node) do |send_node| + range = send_node.loc.dot.begin.join(node.source_range.end) + + add_offense(range, message: MSG_LITERAL) do |corrector| + corrector.replace(send_node.loc.dot, '.') + + range_with_default = node.lhs.source_range.end.begin.join(node.source_range.end) + corrector.remove(range_with_default) + end + end + end + # rubocop:enable Metrics/AbcSize + private + def assume_receiver_instance_exists?(receiver) + return true if receiver.const_type? && !receiver.source.match?(SNAKE_CASE) + + receiver.literal? && !receiver.nil_type? + end + def check?(node) parent = node.parent return false unless parent diff --git a/lib/rubocop/cop/lint/redundant_with_index.rb b/lib/rubocop/cop/lint/redundant_with_index.rb index 229963dba42..cee5b1d969c 100644 --- a/lib/rubocop/cop/lint/redundant_with_index.rb +++ b/lib/rubocop/cop/lint/redundant_with_index.rb @@ -56,10 +56,10 @@ def on_block(node) def_node_matcher :redundant_with_index?, <<~PATTERN { (block - $(send _ {:each_with_index :with_index} ...) + $(call _ {:each_with_index :with_index} ...) (args (arg _)) ...) (numblock - $(send _ {:each_with_index :with_index} ...) 1 ...) + $(call _ {:each_with_index :with_index} ...) 1 ...) } PATTERN diff --git a/lib/rubocop/cop/lint/redundant_with_object.rb b/lib/rubocop/cop/lint/redundant_with_object.rb index 39aa24e0d7b..18dd7106bc5 100644 --- a/lib/rubocop/cop/lint/redundant_with_object.rb +++ b/lib/rubocop/cop/lint/redundant_with_object.rb @@ -56,9 +56,9 @@ def on_block(node) def_node_matcher :redundant_with_object?, <<~PATTERN { (block - $(send _ {:each_with_object :with_object} _) (args (arg _)) ...) + $(call _ {:each_with_object :with_object} _) (args (arg _)) ...) (numblock - $(send _ {:each_with_object :with_object} _) 1 ...) + $(call _ {:each_with_object :with_object} _) 1 ...) } PATTERN diff --git a/lib/rubocop/cop/lint/rescue_type.rb b/lib/rubocop/cop/lint/rescue_type.rb index 0fed979a607..67db9926ba5 100644 --- a/lib/rubocop/cop/lint/rescue_type.rb +++ b/lib/rubocop/cop/lint/rescue_type.rb @@ -59,9 +59,7 @@ def on_resbody(node) def autocorrect(corrector, node) rescued, _, _body = *node - range = Parser::Source::Range.new(node.source_range.source_buffer, - node.loc.keyword.end_pos, - rescued.source_range.end_pos) + range = node.loc.keyword.end.join(rescued.source_range.end) corrector.replace(range, correction(*rescued)) end diff --git a/lib/rubocop/cop/lint/safe_navigation_chain.rb b/lib/rubocop/cop/lint/safe_navigation_chain.rb index 3134ca64c80..e08fb9ccf75 100644 --- a/lib/rubocop/cop/lint/safe_navigation_chain.rb +++ b/lib/rubocop/cop/lint/safe_navigation_chain.rb @@ -45,10 +45,9 @@ def on_send(node) bad_method?(node) do |safe_nav, method| return if nil_methods.include?(method) || PLUS_MINUS_METHODS.include?(node.method_name) - location = - Parser::Source::Range.new(node.source_range.source_buffer, - safe_nav.source_range.end_pos, - node.source_range.end_pos) + begin_range = node.loc.dot || safe_nav.source_range.end + location = begin_range.join(node.source_range.end) + add_offense(location) do |corrector| autocorrect(corrector, offense_range: location, send_node: node) end @@ -82,16 +81,23 @@ def add_safe_navigation_operator(offense_range:, send_node:) def autocorrect(corrector, offense_range:, send_node:) corrector.replace( offense_range, - add_safe_navigation_operator( - offense_range: offense_range, - send_node: send_node - ) + add_safe_navigation_operator(offense_range: offense_range, send_node: send_node) ) + + corrector.wrap(send_node, '(', ')') if require_parentheses?(send_node) end def brackets?(send_node) send_node.method?(:[]) || send_node.method?(:[]=) end + + def require_parentheses?(send_node) + return false unless send_node.comparison_method? + return false unless (node = send_node.parent) + + (node.respond_to?(:logical_operator?) && node.logical_operator?) || + (node.respond_to?(:comparison_method?) && node.comparison_method?) + end end end end diff --git a/lib/rubocop/cop/lint/script_permission.rb b/lib/rubocop/cop/lint/script_permission.rb index d724220f939..03477e614be 100644 --- a/lib/rubocop/cop/lint/script_permission.rb +++ b/lib/rubocop/cop/lint/script_permission.rb @@ -46,14 +46,14 @@ def on_new_investigation message = format_message_from(processed_source) add_offense(comment, message: message) do - autocorrect(comment) if autocorrect_requested? + autocorrect if autocorrect_requested? end end private - def autocorrect(comment) - FileUtils.chmod('+x', comment.source_range.source_buffer.name) + def autocorrect + FileUtils.chmod('+x', processed_source.file_path) end def executable?(processed_source) diff --git a/lib/rubocop/cop/lint/self_assignment.rb b/lib/rubocop/cop/lint/self_assignment.rb index dc484340481..2c1c44ab4b3 100644 --- a/lib/rubocop/cop/lint/self_assignment.rb +++ b/lib/rubocop/cop/lint/self_assignment.rb @@ -10,11 +10,18 @@ module Lint # foo = foo # foo, bar = foo, bar # Foo = Foo + # hash['foo'] = hash['foo'] + # obj.attr = obj.attr # # # good # foo = bar # foo, bar = bar, foo # Foo = Bar + # hash['foo'] = hash['bar'] + # obj.attr = obj.attr2 + # + # # good (method calls possibly can return different results) + # hash[foo] = hash[foo] # class SelfAssignment < Base MSG = 'Self-assignment detected.' @@ -26,6 +33,15 @@ class SelfAssignment < Base gvasgn: :gvar }.freeze + def on_send(node) + if node.method?(:[]=) + handle_key_assignment(node) if node.arguments.size == 2 + elsif node.assignment_method? + handle_attribute_assignment(node) if node.arguments.size == 1 + end + end + alias on_csend on_send + def on_lvasgn(node) lhs, rhs = *node return unless rhs @@ -72,6 +88,28 @@ def rhs_matches_lhs?(rhs, lhs) rhs.type == ASSIGNMENT_TYPE_TO_RHS_TYPE[lhs.type] && rhs.children.first == lhs.children.first end + + def handle_key_assignment(node) + value_node = node.arguments[1] + + if value_node.send_type? && value_node.method?(:[]) && + node.receiver == value_node.receiver && + !node.first_argument.call_type? && + node.first_argument == value_node.first_argument + add_offense(node) + end + end + + def handle_attribute_assignment(node) + first_argument = node.first_argument + return unless first_argument.respond_to?(:arguments) && first_argument.arguments.empty? + + if first_argument.call_type? && + node.receiver == first_argument.receiver && + first_argument.method_name.to_s == node.method_name.to_s.delete_suffix('=') + add_offense(node) + end + end end end end diff --git a/lib/rubocop/cop/lint/shadowed_argument.rb b/lib/rubocop/cop/lint/shadowed_argument.rb index 9cd9a744b32..26f19c09d21 100644 --- a/lib/rubocop/cop/lint/shadowed_argument.rb +++ b/lib/rubocop/cop/lint/shadowed_argument.rb @@ -123,6 +123,7 @@ def assignment_without_argument_usage(argument) # Shorthand assignments always use their arguments next false if assignment_node.shorthand_asgn? + next false unless assignment_node.parent node_within_block_or_conditional = node_within_block_or_conditional?(assignment_node.parent, argument.scope.node) diff --git a/lib/rubocop/cop/lint/shadowing_outer_local_variable.rb b/lib/rubocop/cop/lint/shadowing_outer_local_variable.rb index 8207a2b8da2..b58e799d20e 100644 --- a/lib/rubocop/cop/lint/shadowing_outer_local_variable.rb +++ b/lib/rubocop/cop/lint/shadowing_outer_local_variable.rb @@ -68,7 +68,7 @@ def before_declaring_variable(variable, variable_table) def same_conditions_node_different_branch?(variable, outer_local_variable) variable_node = variable_node(variable) - return false unless variable_node.conditional? + return false unless node_or_its_ascendant_conditional?(variable_node) outer_local_variable_node = find_conditional_node_from_ascendant(outer_local_variable.declaration_node) @@ -96,6 +96,12 @@ def find_conditional_node_from_ascendant(node) find_conditional_node_from_ascendant(parent) end + + def node_or_its_ascendant_conditional?(node) + return true if node.conditional? + + !!find_conditional_node_from_ascendant(node) + end end end end diff --git a/lib/rubocop/cop/lint/struct_new_override.rb b/lib/rubocop/cop/lint/struct_new_override.rb index e74ea6243fb..f08129c73c4 100644 --- a/lib/rubocop/cop/lint/struct_new_override.rb +++ b/lib/rubocop/cop/lint/struct_new_override.rb @@ -32,25 +32,25 @@ class StructNewOverride < Base # @!method struct_new(node) def_node_matcher :struct_new, <<~PATTERN (send - (const ${nil? cbase} :Struct) :new ...) + (const {nil? cbase} :Struct) :new ...) PATTERN def on_send(node) - return unless struct_new(node) do - node.arguments.each_with_index do |arg, index| - # Ignore if the first argument is a class name - next if index.zero? && arg.str_type? + return unless struct_new(node) - # Ignore if the argument is not a member name - next unless STRUCT_MEMBER_NAME_TYPES.include?(arg.type) + node.arguments.each_with_index do |arg, index| + # Ignore if the first argument is a class name + next if index.zero? && arg.str_type? - member_name = arg.value + # Ignore if the argument is not a member name + next unless STRUCT_MEMBER_NAME_TYPES.include?(arg.type) - next unless STRUCT_METHOD_NAMES.include?(member_name.to_sym) + member_name = arg.value - message = format(MSG, member_name: member_name.inspect, method_name: member_name.to_s) - add_offense(arg, message: message) - end + next unless STRUCT_METHOD_NAMES.include?(member_name.to_sym) + + message = format(MSG, member_name: member_name.inspect, method_name: member_name.to_s) + add_offense(arg, message: message) end end end diff --git a/lib/rubocop/cop/lint/suppressed_exception.rb b/lib/rubocop/cop/lint/suppressed_exception.rb index d2872d928bb..33a1170191e 100644 --- a/lib/rubocop/cop/lint/suppressed_exception.rb +++ b/lib/rubocop/cop/lint/suppressed_exception.rb @@ -117,9 +117,9 @@ def on_resbody(node) def comment_between_rescue_and_end?(node) ancestor = node.each_ancestor(:kwbegin, :def, :defs, :block, :numblock).first - return unless ancestor + return false unless ancestor - end_line = ancestor.loc.end.line + end_line = ancestor.loc.end&.line || ancestor.loc.last_line processed_source[node.first_line...end_line].any? { |line| comment_line?(line) } end diff --git a/lib/rubocop/cop/lint/symbol_conversion.rb b/lib/rubocop/cop/lint/symbol_conversion.rb index 67d1d29bf9e..6553389a869 100644 --- a/lib/rubocop/cop/lint/symbol_conversion.rb +++ b/lib/rubocop/cop/lint/symbol_conversion.rb @@ -19,6 +19,7 @@ module Lint # 'underscored_string'.to_sym # :'underscored_symbol' # 'hyphenated-string'.to_sym + # "string_#{interpolation}".to_sym # # # good # :string @@ -26,6 +27,7 @@ module Lint # :underscored_string # :underscored_symbol # :'hyphenated-string' + # :"string_#{interpolation}" # # @example EnforcedStyle: strict (default) # @@ -75,9 +77,12 @@ class SymbolConversion < Base def on_send(node) return unless node.receiver - return unless node.receiver.str_type? || node.receiver.sym_type? - register_offense(node, correction: node.receiver.value.to_sym.inspect) + if node.receiver.str_type? || node.receiver.sym_type? + register_offense(node, correction: node.receiver.value.to_sym.inspect) + elsif node.receiver.dstr_type? + register_offense(node, correction: ":\"#{node.receiver.value.to_sym}\"") + end end def on_sym(node) @@ -124,7 +129,7 @@ def properly_quoted?(source, value) source == value || # `Symbol#inspect` uses double quotes, but allow single-quoted # symbols to work as well. - source.tr("'", '"') == value + source.gsub('"', '\"').tr("'", '"') == value end def requires_quotes?(sym_node) diff --git a/lib/rubocop/cop/lint/syntax.rb b/lib/rubocop/cop/lint/syntax.rb index 457fac1c6e4..6b7a2df71ba 100644 --- a/lib/rubocop/cop/lint/syntax.rb +++ b/lib/rubocop/cop/lint/syntax.rb @@ -17,9 +17,12 @@ def on_other_file private def add_offense_from_diagnostic(diagnostic, ruby_version) - message = - "#{diagnostic.message}\n(Using Ruby #{ruby_version} parser; " \ - 'configure using `TargetRubyVersion` parameter, under `AllCops`)' + message = if LSP.enabled? + diagnostic.message + else + "#{diagnostic.message}\n(Using Ruby #{ruby_version} parser; " \ + 'configure using `TargetRubyVersion` parameter, under `AllCops`)' + end add_offense(diagnostic.location, message: message, severity: diagnostic.level) end diff --git a/lib/rubocop/cop/lint/to_enum_arguments.rb b/lib/rubocop/cop/lint/to_enum_arguments.rb index 8269cf22faf..3d360ebc4db 100644 --- a/lib/rubocop/cop/lint/to_enum_arguments.rb +++ b/lib/rubocop/cop/lint/to_enum_arguments.rb @@ -74,7 +74,7 @@ def arguments_match?(arguments, def_node) end end - # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity + # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength def argument_match?(send_arg, def_arg) def_arg_name = def_arg.children[0] @@ -87,12 +87,14 @@ def argument_match?(send_arg, def_arg) send_arg.hash_type? && send_arg.pairs.any? { |pair| passing_keyword_arg?(pair, def_arg_name) } when :kwrestarg - send_arg.each_child_node(:kwsplat).any? { |child| child.source == def_arg.source } + send_arg.each_child_node(:kwsplat, :forwarded_kwrestarg).any? do |child| + child.source == def_arg.source + end when :forward_arg send_arg.forwarded_args_type? end end - # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity + # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength end end end diff --git a/lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb b/lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb index 5f2d6084b91..aae8a8716a0 100644 --- a/lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb +++ b/lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb @@ -34,7 +34,7 @@ class TrailingCommaInAttributeDeclaration < Base MSG = 'Avoid leaving a trailing comma in attribute declarations.' def on_send(node) - return unless node.attribute_accessor? && node.arguments.last.def_type? + return unless node.attribute_accessor? && node.last_argument.def_type? trailing_comma = trailing_comma_range(node) diff --git a/lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb b/lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb index 59de1c3786b..24fa303d413 100644 --- a/lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb +++ b/lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb @@ -69,8 +69,8 @@ class UnmodifiedReduceAccumulator < Base # @!method reduce_with_block?(node) def_node_matcher :reduce_with_block?, <<~PATTERN { - (block (send _recv {:reduce :inject} ...) args ...) - (numblock (send _recv {:reduce :inject} ...) ...) + (block (call _recv {:reduce :inject} ...) args ...) + (numblock (call _recv {:reduce :inject} ...) ...) } PATTERN diff --git a/lib/rubocop/cop/lint/useless_access_modifier.rb b/lib/rubocop/cop/lint/useless_access_modifier.rb index b89a9d178a9..f916dcf4733 100644 --- a/lib/rubocop/cop/lint/useless_access_modifier.rb +++ b/lib/rubocop/cop/lint/useless_access_modifier.rb @@ -256,7 +256,7 @@ def method_definition?(child) def any_method_definition?(child) cop_config.fetch('MethodCreatingMethods', []).any? do |m| - matcher_name = "#{m}_method?".to_sym + matcher_name = :"#{m}_method?" unless respond_to?(matcher_name) self.class.def_node_matcher matcher_name, <<~PATTERN {def (send nil? :#{m} ...)} @@ -279,7 +279,7 @@ def eval_call?(child) def any_context_creating_methods?(child) cop_config.fetch('ContextCreatingMethods', []).any? do |m| - matcher_name = "#{m}_block?".to_sym + matcher_name = :"#{m}_block?" unless respond_to?(matcher_name) self.class.def_node_matcher matcher_name, <<~PATTERN ({block numblock} (send {nil? const} {:#{m}} ...) ...) diff --git a/lib/rubocop/cop/lint/useless_assignment.rb b/lib/rubocop/cop/lint/useless_assignment.rb index 83902ad6570..c006f2d624e 100644 --- a/lib/rubocop/cop/lint/useless_assignment.rb +++ b/lib/rubocop/cop/lint/useless_assignment.rb @@ -7,12 +7,18 @@ module Lint # scope. # The basic idea for this cop was from the warning of `ruby -cw`: # - # assigned but unused variable - foo + # [source,console] + # ---- + # assigned but unused variable - foo + # ---- # # Currently this cop has advanced logic that detects unreferenced # reassignments and properly handles varied cases such as branch, loop, # rescue, ensure, etc. # + # NOTE: Given the assignment `foo = 1, bar = 2`, removing unused variables + # can lead to a syntax error, so this case is not autocorrected. + # # @safety # This cop's autocorrection is unsafe because removing assignment from # operator assignment can cause NameError if this assignment has been used to declare @@ -51,25 +57,24 @@ def after_leaving_scope(scope, _variable_table) scope.variables.each_value { |variable| check_for_unused_assignments(variable) } end + # rubocop:disable Metrics/AbcSize def check_for_unused_assignments(variable) return if variable.should_be_unused? variable.assignments.each do |assignment| - next if assignment.used? + next if assignment.used? || part_of_ignored_node?(assignment.node) message = message_for_useless_assignment(assignment) + range = offense_range(assignment) - location = if assignment.regexp_named_capture? - assignment.node.children.first.source_range - else - assignment.node.loc.name - end - - add_offense(location, message: message) do |corrector| - autocorrect(corrector, assignment) + add_offense(range, message: message) do |corrector| + autocorrect(corrector, assignment) unless sequential_assignment?(assignment.node) end + + ignore_node(assignment.node) if chained_assignment?(assignment.node) end end + # rubocop:enable Metrics/AbcSize def message_for_useless_assignment(assignment) variable = assignment.variable @@ -77,6 +82,28 @@ def message_for_useless_assignment(assignment) format(MSG, variable: variable.name) + message_specification(assignment, variable).to_s end + def offense_range(assignment) + if assignment.regexp_named_capture? + assignment.node.children.first.source_range + else + assignment.node.loc.name + end + end + + def sequential_assignment?(node) + if node.lvasgn_type? && node.expression&.array_type? && + node.each_descendant.any?(&:assignment?) + return true + end + return false unless node.parent + + sequential_assignment?(node.parent) + end + + def chained_assignment?(node) + node.respond_to?(:expression) && node.expression&.lvasgn_type? + end + def message_specification(assignment, variable) if assignment.multiple_assignment? multiple_assignment_message(variable.name) @@ -96,8 +123,7 @@ def operator_assignment_message(scope, assignment) return_value_node = return_value_node_of_scope(scope) return unless assignment.meta_assignment_node.equal?(return_value_node) - " Use `#{assignment.operator.sub(/=$/, '')}` " \ - "instead of `#{assignment.operator}`." + " Use `#{assignment.operator.delete_suffix('=')}` instead of `#{assignment.operator}`." end def similar_name_message(variable) diff --git a/lib/rubocop/cop/lint/useless_times.rb b/lib/rubocop/cop/lint/useless_times.rb index bde3385f4cf..e51d8360717 100644 --- a/lib/rubocop/cop/lint/useless_times.rb +++ b/lib/rubocop/cop/lint/useless_times.rb @@ -4,7 +4,7 @@ module RuboCop module Cop module Lint # Checks for uses of `Integer#times` that will never yield - # (when the integer <= 0) or that will only ever yield once + # (when the integer ``<= 0``) or that will only ever yield once # (`1.times`). # # @safety diff --git a/lib/rubocop/cop/lint/void.rb b/lib/rubocop/cop/lint/void.rb index 9e1af8f966b..82eabb9b2fc 100644 --- a/lib/rubocop/cop/lint/void.rb +++ b/lib/rubocop/cop/lint/void.rb @@ -6,6 +6,16 @@ module Lint # Checks for operators, variables, literals, lambda, proc and nonmutating # methods used in void context. # + # `each` blocks are allowed to prevent false positives. + # For example, the expression inside the `each` block below. + # It's not void, especially when the receiver is an `Enumerator`: + # + # [source,ruby] + # ---- + # enumerator = [1, 2, 3].filter + # enumerator.each { |item| item >= 2 } #=> [2, 3] + # ---- + # # @example CheckForMethodsWithNoSideEffects: false (default) # # bad # def some_method @@ -47,6 +57,7 @@ class Void < Base OP_MSG = 'Operator `%s` used in void context.' VAR_MSG = 'Variable `%s` used in void context.' + CONST_MSG = 'Constant `%s` used in void context.' LIT_MSG = 'Literal `%s` used in void context.' SELF_MSG = '`self` used in void context.' EXPRESSION_MSG = '`%s` used in void context.' @@ -72,6 +83,7 @@ def on_block(node) return unless node.body && !node.body.begin_type? return unless in_void_context?(node.body) + check_void_op(node.body) { node.method?(:each) } check_expression(node.body) end @@ -87,11 +99,18 @@ def on_begin(node) def check_begin(node) expressions = *node expressions.pop unless in_void_context?(node) - expressions.each { |expr| check_expression(expr) } + expressions.each do |expr| + check_void_op(expr) do + block_node = node.each_ancestor(:block).first + + block_node&.method?(:each) + end + + check_expression(expr) + end end def check_expression(expr) - check_void_op(expr) check_literal(expr) check_var(expr) check_self(expr) @@ -101,8 +120,9 @@ def check_expression(expr) check_nonmutating(expr) end - def check_void_op(node) + def check_void_op(node, &block) return unless node.send_type? && OPERATORS.include?(node.method_name) + return if block && yield(node) add_offense(node.loc.selector, message: format(OP_MSG, op: node.method_name)) do |corrector| @@ -113,17 +133,26 @@ def check_void_op(node) def check_var(node) return unless node.variable? || node.const_type? - add_offense(node.loc.name, - message: format(VAR_MSG, var: node.loc.name.source)) do |corrector| - autocorrect_void_var(corrector, node) + if node.const_type? + template = node.special_keyword? ? VAR_MSG : CONST_MSG + + offense_range = node + message = format(template, var: node.source) + else + offense_range = node.loc.name + message = format(VAR_MSG, var: node.loc.name.source) + end + + add_offense(offense_range, message: message) do |corrector| + autocorrect_void_expression(corrector, node) end end def check_literal(node) - return if !node.literal? || node.xstr_type? || node.range_type? + return if !entirely_literal?(node) || node.xstr_type? || node.range_type? add_offense(node, message: format(LIT_MSG, lit: node.source)) do |corrector| - autocorrect_void_literal(corrector, node) + autocorrect_void_expression(corrector, node) end end @@ -131,7 +160,7 @@ def check_self(node) return unless node.self_type? add_offense(node, message: SELF_MSG) do |corrector| - autocorrect_void_self(corrector, node) + autocorrect_void_expression(corrector, node) end end @@ -144,7 +173,7 @@ def check_void_expression(node) end def check_nonmutating(node) - return unless node.respond_to?(:method_name) + return if !node.send_type? && !node.block_type? && !node.numblock_type? method_name = node.method_name return unless NONMUTATING_METHODS.include?(method_name) @@ -181,18 +210,6 @@ def autocorrect_void_op(corrector, node) end end - def autocorrect_void_var(corrector, node) - corrector.remove(range_with_surrounding_space(range: node.loc.name, side: :left)) - end - - def autocorrect_void_literal(corrector, node) - corrector.remove(range_with_surrounding_space(range: node.source_range, side: :left)) - end - - def autocorrect_void_self(corrector, node) - corrector.remove(range_with_surrounding_space(range: node.source_range, side: :left)) - end - def autocorrect_void_expression(corrector, node) corrector.remove(range_with_surrounding_space(range: node.source_range, side: :left)) end @@ -205,6 +222,19 @@ def autocorrect_nonmutating_send(corrector, node, suggestion) end corrector.replace(send_node.loc.selector, suggestion) end + + def entirely_literal?(node) + case node.type + when :array + node.each_value.all? { |value| entirely_literal?(value) } + when :hash + return false unless node.each_key.all? { |key| entirely_literal?(key) } + + node.each_value.all? { |value| entirely_literal?(value) } + else + node.literal? + end + end end end end diff --git a/lib/rubocop/cop/metrics/abc_size.rb b/lib/rubocop/cop/metrics/abc_size.rb index fc623fad0a1..970aff5f9fb 100644 --- a/lib/rubocop/cop/metrics/abc_size.rb +++ b/lib/rubocop/cop/metrics/abc_size.rb @@ -10,9 +10,9 @@ module Metrics # # Interpreting ABC size: # - # * <= 17 satisfactory - # * 18..30 unsatisfactory - # * > 30 dangerous + # * ``<= 17`` satisfactory + # * `18..30` unsatisfactory + # * `>` 30 dangerous # # You can have repeated "attributes" calls count as a single "branch". # For this purpose, attributes are any method with no argument; no attempt diff --git a/lib/rubocop/cop/metrics/block_length.rb b/lib/rubocop/cop/metrics/block_length.rb index 11c9957cff3..29c413ddb8a 100644 --- a/lib/rubocop/cop/metrics/block_length.rb +++ b/lib/rubocop/cop/metrics/block_length.rb @@ -12,6 +12,7 @@ module Metrics # Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct # will be counted as one line regardless of its actual size. # + # NOTE: This cop does not apply for `Struct` definitions. # # NOTE: The `ExcludedMethods` configuration is deprecated and only kept # for backwards compatibility. Please use `AllowedMethods` and `AllowedPatterns` @@ -40,7 +41,6 @@ module Metrics # ) # end # 6 points # - # NOTE: This cop does not apply for `Struct` definitions. class BlockLength < Base include CodeLength include AllowedMethods diff --git a/lib/rubocop/cop/metrics/class_length.rb b/lib/rubocop/cop/metrics/class_length.rb index 3aedb63a4fb..f58f55616f1 100644 --- a/lib/rubocop/cop/metrics/class_length.rb +++ b/lib/rubocop/cop/metrics/class_length.rb @@ -11,6 +11,8 @@ module Metrics # Available are: 'array', 'hash', 'heredoc', and 'method_call'. Each construct # will be counted as one line regardless of its actual size. # + # NOTE: This cop also applies for `Struct` definitions. + # # @example CountAsOne: ['array', 'heredoc', 'method_call'] # # class Foo @@ -34,15 +36,18 @@ module Metrics # ) # end # 6 points # - # - # NOTE: This cop also applies for `Struct` definitions. class ClassLength < Base include CodeLength def on_class(node) check_code_length(node) end - alias on_sclass on_class + + def on_sclass(node) + return if node.each_ancestor(:class).any? + + on_class(node) + end def on_casgn(node) parent = node.parent diff --git a/lib/rubocop/cop/metrics/method_length.rb b/lib/rubocop/cop/metrics/method_length.rb index 17133269c52..6ea2a85a592 100644 --- a/lib/rubocop/cop/metrics/method_length.rb +++ b/lib/rubocop/cop/metrics/method_length.rb @@ -54,7 +54,7 @@ def on_def(node) alias on_defs on_def def on_block(node) - return unless node.send_node.method?(:define_method) + return unless node.method?(:define_method) check_code_length(node) end diff --git a/lib/rubocop/cop/metrics/utils/code_length_calculator.rb b/lib/rubocop/cop/metrics/utils/code_length_calculator.rb index de94a0ea603..2ae7897d0da 100644 --- a/lib/rubocop/cop/metrics/utils/code_length_calculator.rb +++ b/lib/rubocop/cop/metrics/utils/code_length_calculator.rb @@ -10,7 +10,7 @@ class CodeLengthCalculator include Util FOLDABLE_TYPES = %i[array hash heredoc send csend].freeze - CLASSLIKE_TYPES = %i[class module sclass].freeze + CLASSLIKE_TYPES = %i[class module].freeze private_constant :FOLDABLE_TYPES, :CLASSLIKE_TYPES def initialize(node, processed_source, count_comments: false, foldable_types: []) @@ -63,7 +63,7 @@ def normalize_foldable_types(types) types end - def code_length(node) + def code_length(node) # rubocop:disable Metrics/MethodLength if classlike_node?(node) classlike_code_length(node) elsif heredoc_node?(node) @@ -72,7 +72,14 @@ def code_length(node) body = extract_body(node) return 0 unless body - body.source.each_line.count { |line| !irrelevant_line?(line) } + source = + if node_with_heredoc?(body) + source_from_node_with_heredoc(body) + else + body.source.lines + end + + source.count { |line| !irrelevant_line?(line) } end end @@ -138,7 +145,7 @@ def foldable_node?(node) def extract_body(node) case node.type - when :class, :module, :block, :numblock, :def, :defs + when :class, :module, :sclass, :block, :numblock, :def, :defs node.body when :casgn _scope, _name, value = *node @@ -175,6 +182,27 @@ def parenthesized?(node) def another_args?(node) node.call_type? && node.arguments.count > 1 end + + def node_with_heredoc?(node) + node.each_descendant(:str, :dstr).any? { |descendant| heredoc_node?(descendant) } + end + + def source_from_node_with_heredoc(node) + last_line = -1 + node.each_descendant do |descendant| + next unless descendant.source + + descendant_last_line = + if heredoc_node?(descendant) + descendant.loc.heredoc_end.line + else + descendant.last_line + end + + last_line = [last_line, descendant_last_line].max + end + @processed_source[(node.first_line - 1)..(last_line - 1)] + end end end end diff --git a/lib/rubocop/cop/migration/department_name.rb b/lib/rubocop/cop/migration/department_name.rb index a8428b06d4c..7a91ae15553 100644 --- a/lib/rubocop/cop/migration/department_name.rb +++ b/lib/rubocop/cop/migration/department_name.rb @@ -16,7 +16,7 @@ class DepartmentName < Base # The token that makes up a disable comment. # The allowed specification for comments after `# rubocop: disable` is # `DepartmentName/CopName` or` all`. - DISABLING_COPS_CONTENT_TOKEN = %r{[A-z]+/[A-z]+|all}.freeze + DISABLING_COPS_CONTENT_TOKEN = %r{[A-Za-z]+/[A-Za-z]+|all}.freeze def on_new_investigation processed_source.comments.each do |comment| @@ -67,7 +67,7 @@ def valid_content_token?(content_token) end def contain_unexpected_character_for_department_name?(name) - name.match?(%r{[^A-z/, ]}) + name.match?(%r{[^A-Za-z/, ]}) end def qualified_legacy_cop_name(cop_name) diff --git a/lib/rubocop/cop/mixin/check_line_breakable.rb b/lib/rubocop/cop/mixin/check_line_breakable.rb index 34c5325b286..edbeb82223d 100644 --- a/lib/rubocop/cop/mixin/check_line_breakable.rb +++ b/lib/rubocop/cop/mixin/check_line_breakable.rb @@ -218,7 +218,7 @@ def process_args(args) # @api private def already_on_multiple_lines?(node) - return node.first_line != node.arguments.last.last_line if node.def_type? + return node.first_line != node.last_argument.last_line if node.def_type? !node.single_line? end diff --git a/lib/rubocop/cop/mixin/comments_help.rb b/lib/rubocop/cop/mixin/comments_help.rb index 7db370aac87..701c486582f 100644 --- a/lib/rubocop/cop/mixin/comments_help.rb +++ b/lib/rubocop/cop/mixin/comments_help.rb @@ -25,7 +25,7 @@ def comments_in_range(node) def comments_contain_disables?(node, cop_name) disabled_ranges = processed_source.disabled_line_ranges[cop_name] - return unless disabled_ranges + return false unless disabled_ranges node_range = node.source_range.line...find_end_line(node) @@ -62,25 +62,29 @@ def buffer # Returns the end line of a node, which might be a comment and not part of the AST # End line is considered either the line at which another node starts, or # the line at which the parent node ends. - # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity, Lint/DuplicateBranch + # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity def find_end_line(node) - if node.if_type? && node.else? - node.loc.else.line - elsif node.if_type? && node.ternary? - node.else_branch.loc.line - elsif node.if_type? && node.elsif? - node.each_ancestor(:if).find(&:if?).loc.end.line + if node.if_type? + if node.else? + node.loc.else.line + elsif node.ternary? + node.else_branch.loc.line + elsif node.elsif? + node.each_ancestor(:if).find(&:if?).loc.end.line + end elsif node.block_type? || node.numblock_type? node.loc.end.line elsif (next_sibling = node.right_sibling) && next_sibling.is_a?(AST::Node) next_sibling.loc.line elsif (parent = node.parent) - parent.loc.respond_to?(:end) && parent.loc.end ? parent.loc.end.line : parent.loc.line - else - node.loc.end.line - end + if parent.loc.respond_to?(:end) && parent.loc.end + parent.loc.end.line + else + parent.loc.line + end + end || node.loc.end.line end - # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity, Lint/DuplicateBranch + # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity end end end diff --git a/lib/rubocop/cop/mixin/configurable_formatting.rb b/lib/rubocop/cop/mixin/configurable_formatting.rb index 43f06b3408d..0022a76ae9f 100644 --- a/lib/rubocop/cop/mixin/configurable_formatting.rb +++ b/lib/rubocop/cop/mixin/configurable_formatting.rb @@ -18,6 +18,7 @@ def report_opposing_styles(node, name) alternative_styles.each do |alternative| return unexpected_style_detected(alternative) if valid_name?(node, name, alternative) end + unrecognized_style_detected end def valid_name?(node, name, given_style = style) diff --git a/lib/rubocop/cop/mixin/def_node.rb b/lib/rubocop/cop/mixin/def_node.rb index 9d385e421d3..9d98b0aabd2 100644 --- a/lib/rubocop/cop/mixin/def_node.rb +++ b/lib/rubocop/cop/mixin/def_node.rb @@ -19,7 +19,7 @@ def preceding_non_public_modifier?(node) # @!method non_public_modifier?(node) def_node_matcher :non_public_modifier?, <<~PATTERN - (send nil? {:private :protected} ({def defs} ...)) + (send nil? {:private :protected :private_class_method} ({def defs} ...)) PATTERN end end diff --git a/lib/rubocop/cop/mixin/end_keyword_alignment.rb b/lib/rubocop/cop/mixin/end_keyword_alignment.rb index bb5150a37c4..a8e90b086a8 100644 --- a/lib/rubocop/cop/mixin/end_keyword_alignment.rb +++ b/lib/rubocop/cop/mixin/end_keyword_alignment.rb @@ -67,7 +67,7 @@ def style_parameter_name end def variable_alignment?(whole_expression, rhs, end_alignment_style) - return if end_alignment_style == :keyword + return false if end_alignment_style == :keyword !line_break_before_keyword?(whole_expression, rhs) end diff --git a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb index 651af331fdd..b2c888d85bc 100644 --- a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb +++ b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb @@ -48,18 +48,21 @@ def on_pair(node) def register_offense(node, message, replacement) # rubocop:disable Metrics/AbcSize add_offense(node.value, message: message) do |corrector| - if (def_node = def_node_that_require_parentheses(node)) - last_argument = def_node.last_argument - if last_argument.nil? || !last_argument.hash_type? - next corrector.replace(node, replacement) - end - - white_spaces = range_between(def_node.selector.end_pos, - def_node.first_argument.source_range.begin_pos) - corrector.replace(white_spaces, '(') - corrector.insert_after(last_argument, ')') if node == last_argument.pairs.last - end corrector.replace(node, replacement) + + next unless (def_node = def_node_that_require_parentheses(node)) + + last_argument = def_node.last_argument + if last_argument.nil? || !last_argument.hash_type? + next corrector.replace(node, replacement) + end + + white_spaces = range_between(def_node.selector.end_pos, + def_node.first_argument.source_range.begin_pos) + next if node.parent.braces? + + corrector.replace(white_spaces, '(') + corrector.insert_after(last_argument, ')') if node == last_argument.pairs.last end end diff --git a/lib/rubocop/cop/mixin/heredoc.rb b/lib/rubocop/cop/mixin/heredoc.rb index 2ed16bb661b..52f64f5cd7d 100644 --- a/lib/rubocop/cop/mixin/heredoc.rb +++ b/lib/rubocop/cop/mixin/heredoc.rb @@ -26,11 +26,15 @@ def indent_level(str) end def delimiter_string(node) - node.source.match(OPENING_DELIMITER).captures[1] + return '' unless (match = node.source.match(OPENING_DELIMITER)) + + match.captures[1] end def heredoc_type(node) - node.source.match(OPENING_DELIMITER).captures[0] + return '' unless (match = node.source.match(OPENING_DELIMITER)) + + match.captures[0] end end end diff --git a/lib/rubocop/cop/mixin/multiline_expression_indentation.rb b/lib/rubocop/cop/mixin/multiline_expression_indentation.rb index fee6dd7fcf6..cd33bdbf927 100644 --- a/lib/rubocop/cop/mixin/multiline_expression_indentation.rb +++ b/lib/rubocop/cop/mixin/multiline_expression_indentation.rb @@ -20,16 +20,17 @@ def on_send(node) range = offending_range(node, lhs, rhs, style) check(range, node, lhs, rhs) end + alias on_csend on_send private - # In a chain of method calls, we regard the top send node as the base + # In a chain of method calls, we regard the top call node as the base # for indentation of all lines following the first. For example: # a. # b c { block }. <-- b is indented relative to a # d <-- d is indented relative to a def left_hand_side(lhs) - while lhs.parent&.send_type? && lhs.parent.loc.dot && !lhs.parent.assignment_method? + while lhs.parent&.call_type? && lhs.parent.loc.dot && !lhs.parent.assignment_method? lhs = lhs.parent end lhs diff --git a/lib/rubocop/cop/mixin/percent_literal.rb b/lib/rubocop/cop/mixin/percent_literal.rb index 48f9fb19999..b3881459278 100644 --- a/lib/rubocop/cop/mixin/percent_literal.rb +++ b/lib/rubocop/cop/mixin/percent_literal.rb @@ -9,7 +9,7 @@ module PercentLiteral private def percent_literal?(node) - return unless (begin_source = begin_source(node)) + return false unless (begin_source = begin_source(node)) begin_source.start_with?('%') end diff --git a/lib/rubocop/cop/mixin/preceding_following_alignment.rb b/lib/rubocop/cop/mixin/preceding_following_alignment.rb index d7a30d42bdd..790968e2512 100644 --- a/lib/rubocop/cop/mixin/preceding_following_alignment.rb +++ b/lib/rubocop/cop/mixin/preceding_following_alignment.rb @@ -75,21 +75,19 @@ def aligned_comment_lines end def aligned_token?(range, line) - aligned_words?(range, line) || - aligned_char?(range, line) || - aligned_assignment?(range, line) + aligned_words?(range, line) || aligned_assignment?(range, line) end def aligned_operator?(range, line) - (aligned_identical?(range, line) || aligned_assignment?(range, line)) + aligned_identical?(range, line) || aligned_assignment?(range, line) end def aligned_words?(range, line) - /\s\S/.match?(line[range.column - 1, 2]) - end + left_edge = range.column + return true if /\s\S/.match?(line[left_edge - 1, 2]) - def aligned_char?(range, line) - line[range.column] == range.source[0] + token = range.source + token == line[left_edge, token.length] end def aligned_assignment?(range, line) diff --git a/lib/rubocop/cop/mixin/space_before_punctuation.rb b/lib/rubocop/cop/mixin/space_before_punctuation.rb index ecf1d49b0ab..830cf67144c 100644 --- a/lib/rubocop/cop/mixin/space_before_punctuation.rb +++ b/lib/rubocop/cop/mixin/space_before_punctuation.rb @@ -36,7 +36,7 @@ def space_missing?(token1, token2) end def space_required_after?(token) - token.left_curly_brace? && space_required_after_lcurly? + (token.left_curly_brace? || token.type == :tLAMBEG) && space_required_after_lcurly? end def space_required_after_lcurly? diff --git a/lib/rubocop/cop/mixin/string_help.rb b/lib/rubocop/cop/mixin/string_help.rb index 60bcb716cad..d8f4c8ebec8 100644 --- a/lib/rubocop/cop/mixin/string_help.rb +++ b/lib/rubocop/cop/mixin/string_help.rb @@ -30,8 +30,10 @@ def on_regexp(node) private def inside_interpolation?(node) - # A :begin node inside a :dstr node is an interpolation. - node.ancestors.drop_while { |a| !a.begin_type? }.any?(&:dstr_type?) + # A :begin node inside a :dstr, :dsym, or :regexp node is an interpolation. + node.ancestors + .drop_while { |a| !a.begin_type? } + .any? { |a| a.dstr_type? || a.dsym_type? || a.regexp_type? } end end end diff --git a/lib/rubocop/cop/mixin/trailing_comma.rb b/lib/rubocop/cop/mixin/trailing_comma.rb index 79554e8f176..4d6b04c715e 100644 --- a/lib/rubocop/cop/mixin/trailing_comma.rb +++ b/lib/rubocop/cop/mixin/trailing_comma.rb @@ -106,7 +106,7 @@ def allowed_multiline_argument?(node) end def elements(node) - return node.children unless %i[csend send].include?(node.type) + return node.children unless node.call_type? node.arguments.flat_map do |argument| # For each argument, if it is a multi-line hash without braces, diff --git a/lib/rubocop/cop/naming/block_forwarding.rb b/lib/rubocop/cop/naming/block_forwarding.rb index 83b9eb25b1b..b314e2a41f5 100644 --- a/lib/rubocop/cop/naming/block_forwarding.rb +++ b/lib/rubocop/cop/naming/block_forwarding.rb @@ -48,24 +48,32 @@ class BlockForwarding < Base MSG = 'Use %