Here me out before you think this is just another post which runs rubocop only on changed files. There's four things different here
- 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)
- Skip deleted files
- Works on both staged and unstaged files with same code
- 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
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
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 "
Let me know if you had any edge case that didn't work with this command
Top comments (0)