DEV Community

Risa Fujii
Risa Fujii

Posted on

Running RuboCop only on modified files, in a project with no RuboCop

I like using RuboCop. I think using a linter is a good idea, especially for team projects.

However, I ran into a situation where the people I was working with had opinions against installing RuboCop in the Rails project, and asked me to use it locally for my own code if I wanted.

I couldn't run RuboCop on the entire project, because it would try to fix a mountain of errors for existing unlinted code. So I ended up installing the relevant gems into my system, and running a command that only checks modified files. Here are the steps involved.

1. Install gems with gem install

Since we can't add the gems to the Gemfile, install the necessary gems into your system with gem install instead.

gem install rubocop rubocop-performance rubocop-rails
Enter fullscreen mode Exit fullscreen mode

2. Create .rubocop.yml in the home directory

Usually, the config file is placed in the project root folder to be shared by everyone in the dev team. In our case, we can create one in the home directory instead: ~/.rubocop.yml.

Docs: https://docs.rubocop.org/rubocop/configuration.html

The behavior of RuboCop can be controlled via the .rubocop.yml configuration file. It makes it possible to enable/disable certain cops (checks) and to alter their behavior if they accept any parameters. The file can be placed in your home directory, XDG config directory, or in some project directory.

Go ahead and configure the YML file as you normally would. Configuration instructions can be found in the docs linked above.

3. Run RuboCop on modified files

We can run the following command to run RuboCop on unstaged changes.

git add -N .; git diff --name-only | xargs rubocop
Enter fullscreen mode Exit fullscreen mode
  • git add -N . is necessary for including new files that are not tracked by git
  • git diff --name-only gives you a list of files with changes
  • xargs rubocop runs RuboCop on those files

[Optional]
Since the line above is a lot to type, I added it to my git aliases. Now, I can just run cop in my command line.

# ~/.gitconfig
alias cop="git add -N .; git diff --name-only | xargs rubocop"
Enter fullscreen mode Exit fullscreen mode

Thank you for reading!

Top comments (3)

Collapse
 
cseeman profile image
christine

Awesome! Always looking for a good option to add to my git alias file

Collapse
 
fredyn profile image
Alfred Nfor

Thanks Risa!

Collapse
 
danman01 profile image
D

Very useful! I did a similar alias, and found it useful to add -A so rubocop will autocorrect