DEV Community

VISHAL DEEPAK
VISHAL DEEPAK

Posted on

3 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs