Skip to content

Instantly share code, notes, and snippets.

@samzhab
Forked from mpeteuil/rubocop_pre_commit_hook
Created March 16, 2021 15:50
Show Gist options
  • Save samzhab/d7fdcd27ec819860629c490a05018e0e to your computer and use it in GitHub Desktop.
Save samzhab/d7fdcd27ec819860629c490a05018e0e to your computer and use it in GitHub Desktop.
Ruby style guide git pre-commit hook using Rubocop as the style guide checker. Only runs on staged ruby files that have been added and/or modified.
#!/usr/bin/env ruby
require 'English'
require 'rubocop'
ADDED_OR_MODIFIED = /A|AM|^M/.freeze
changed_files = `git status --porcelain`.split(/\n/).
select { |file_name_with_status|
file_name_with_status =~ ADDED_OR_MODIFIED
}.
map { |file_name_with_status|
file_name_with_status.split(' ')[1]
}.
select { |file_name|
File.extname(file_name) == '.rb'
}.join(' ')
system("rubocop #{changed_files}") unless changed_files.empty?
exit $CHILD_STATUS.to_s[-1].to_i
@samzhab
Copy link
Author

samzhab commented Mar 16, 2021

  1. find 'hooks' folder in '.git' under project
  2. rename 'pre-commit.sample' to 'pre-commit'
  3. replace contents of file with contents of this gist
  4. now rubocop will run everytime before you commit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment