Introduction
Git hooks are super powerful for automating tasks and enforcing coding standards in a Git repository. One common use case for Git hooks is to run automated tests and code analysis tools before allowing a commit to proceed. In this article we’ll cover pre-commit hooks, how to skip them and how to set up a pre-commit hook to run Rubocop, a Ruby code analysis tool.
What is Rubocop?
Rubocop is a static code analysis tool for Ruby that checks code for style and security issues. It’s a popular tool among Ruby developers to ensure their code follows the Ruby style guide and best practices. Rubocop can be run manually but integrating it with a pre-commit hook ensures code is checked automatically before each commit.
Copy this into .git/hooks/pre-commit (remove .sample)
#!/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.exitstatus
Make it executable
$ chmod +x .git/hooks/pre-commit
You're good to go, from now it'd run rubocop against your changes and prevents from commiting unless you fix the offences.
How to skip pre-commit? just pass -n to git commit
$ git commit -n -m "[hotfix] blah blah"
What is a Pre-Commit Hook?
A pre-commit hook is a client-side Git hook that runs before a commit is created. It’s a script that can do various things like run automated tests, check code style or enforce coding standards. If the pre-commit hook fails the commit is aborted and you have to fix the issues before committing again.
Why Run Rubocop Before Commit
Running Rubocop before commit has several advantages:
- Code quality: Rubocop checks code for style and security issues so the codebase is consistent and secure.
- Time saver: By running Rubocop automatically before commit you can catch issues early and avoid wasting time debugging later.
- Collaboration: By enforcing coding standards pre-commit hooks promote collaboration and consistency among team members.
How to set up a pre-commit hook
- Install Rubocop and the pre-commit hook tool of your choice (e.g., Husky or Pre-commit).
- Create a new file in the .git/hooks directory called pre-commit.
- Add the Rubocop command to the pre-commit file, e.g., rubocop -a.
- Make the pre-commit file executable by running chmod +x .git/hooks/pre-commit.
- Test the pre-commit hook by running git commit -m “Test commit”
Note: If you want to skip the pre-commit hook temporarily you can use the –no-verify option with the git commit command, e.g., git commit -m “Test commit” –no-verify.