-
-
Save ut/f95c7f1cb2a0a4d55e47620bcc505c39 to your computer and use it in GitHub Desktop.
Rubocop pre-commit hook (Slight variation from andrewpage/pre-commit.rb)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'colorize' | |
| # Grab a list of staged changed files | |
| changed_files = `git diff --name-only HEAD`.split("\n") | |
| should_fail, broken_files = false, [] | |
| changed_files.each do |file| | |
| return if File.extname(file) != '.rb' | |
| return if File.basename(file) == 'schema.rb' | |
| return if File.dirname(file).match('db') | |
| # Run static code analysis on changed file | |
| output = `rubocop #{file} --format simple` | |
| # Get exit code of Robocop. Returns a non-zero exit code if it fails. | |
| exit_code = $?.to_i | |
| # If Rubocop is not installed, handle gracefully. | |
| if exit_code == 127 | |
| puts 'It appears that Rubocop is not installed. Please run `bundle install` or `gem install rubocop.`'.yellow | |
| exit 0 | |
| end | |
| # Grab all lines of the output. | |
| lines = output.split("\n") | |
| # 2nd through -3rd line are the actual errors | |
| errors = lines[1..-3] | |
| unless exit_code == 0 | |
| # The commit will fail | |
| should_fail = true | |
| broken_files << { | |
| path: file, | |
| errors: errors | |
| } | |
| end | |
| end | |
| if should_fail | |
| puts 'Static Code Analysis Failed'.red | |
| puts '---------------------------'.red | |
| error_count = 0 | |
| # Produce a nice output for the user. | |
| broken_files.each do |f| | |
| puts " - #{f[:path]}".yellow | |
| f[:errors].each do |error| | |
| error_count += 1 | |
| puts " #{error}".red | |
| end | |
| print "\n" | |
| end | |
| puts "Detected #{error_count} errors in #{broken_files.count} files.".red | |
| # Do not allow them to commit. | |
| exit 1 | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setup in your local git repository: