Is there a way to do incremental linting with RuboCop?

Viewed 789

I have a Ruby code base which has been maintained for many years. When I use RuboCop to check the code-style, it will give me thousands of offenses. Is there a way use RuboCop to check only the new added code or new modified code, and only report offenses for that code?

2 Answers

There are a couple of ways in which Rubocop can help you.

If you run

rubocop --auto-gen-config

Rubocop will generate two configuration files for you: a mostly empty .rubocop.yml, which only contains one key:

inherit_from: .rubocop_todo.yml

And a .rubocop_todo.yml which disables every offense found in your codebase on a per-file basis:

# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2020-09-11 06:20:56 UTC using RuboCop version 0.90.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 1
# Cop supports --auto-correct.
Layout/SpaceAfterMethodName:
  Exclude:
    - 'test.rb'

# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods.
Lint/UnusedMethodArgument:
  Exclude:
    - 'test.rb'

This file is used for two things:

  • If your organization's style guide differs from the default Rubocop config, you can cut&paste the offense from the TODO into the "real" config file and disable it permanently and globally.

  • You can use the TODO file as an actual TODO list, and remove the exclusions one-by-one and fix the offenses one-by-one whenever you have time to do them.

Note, however, that exclusions are file-based, not line-based, so you can only disable cops globally or per-file. When you make changes to an existing file, your newly added code will also have those cops disabled, so it is a good idea to enable linting of the file first and fix all existing offenses.

Also note that you will probably have to use the --exclude-limit COUNT option, because if there are more than COUNT files with the same offense, Rubocop will just disable it globally. The default is 15, so you should set it to a value that is higher than the total number of files in your project.

Another helpful parameter is

rubocop --safe-auto-correct --disable-uncorrectable

Which will safely auto correct all safely auto correctable offenses, and add comments to disable cops for non-correctable offenses.

However, I would argue that this is not actually Rubocop's job in the first place. Your reporting system should have a way of recording a "baseline", and only report deviations from that baseline.

Related