DEV Community 👩‍💻👨‍💻


Posted on

Run Rubcop on changed files with Git Status

Here me out before you think this is just another post which runs rubocop only on changed files. There's four things different here

  1. We run rubocop on newly added and renamed files as well. No need to stage them.(I found a few tutorials online that don't consider this)
  2. Skip deleted files
  3. Works on both staged and unstaged files with same code
  4. We use Git Status instead, for the sake of first point.

First let me give the command to you straight

git status --porcelain | grep -E -v '^(D| D|RD)' | awk '{ print $NF }' | xargs rubocop 
Enter fullscreen mode Exit fullscreen mode

Lets break this down

git status --porcelain

This gets all the files that have been changed, added or deleted. --porcelain is a easy to parse output format

grep -E -v '^(D| D|RD)'

We remove all deleted files and renamed+deleted files if any. We dont want to run rubocop on our deleted files

awk '{ print $NF }'

This one is useful for one edge case. When we rename a staged file. For example if we rename a controller , the output of git status --porcelain is as follows

R  app/controllers/home_controller.rb -> app/controllers/house_controller.rb
Enter fullscreen mode Exit fullscreen mode

The awk command with NF fetches only the last column

xargs rubocop

xargs run the rubocop command on each file

Alias it

Adding alias requires a small modification to the script. This is because we dont want $NF to be expanded on declaration.

alias rubogit="git status --porcelain |  grep -E -v '^(D| D|RD)' | awk '{ print \$NF }' | xargs rubocop "
Enter fullscreen mode Exit fullscreen mode

Let me know if you had any edge case that didn't work with this command

Latest comments (0)

Update Your DEV Experience Level:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠