Skip to content

Instantly share code, notes, and snippets.

@botanicus
Last active June 11, 2018 20:04
Show Gist options
  • Save botanicus/40da4532046d65318f860bff115db603 to your computer and use it in GitHub Desktop.
Save botanicus/40da4532046d65318f860bff115db603 to your computer and use it in GitHub Desktop.
Post-commit hook to fix files with Rubocop.

Installation

gem install refined-refinements
git clone https://gist.github.com/40da4532046d65318f860bff115db603.git
cp 40da4532046d65318f860bff115db603/pre-commit 40da4532046d65318f860bff115db603/post-commit your_repo/.git/hooks

Features

  • Fail if trying to commit to the master branch.
  • Run rubocop --auto-correct on the changed files.
  • Automatically push to origin, even if the branch is not there yet.
  • Sets the upstream, so git pull -r will work as expected.

Caveats

  • Disable for one commit with git commit --no-verify.
#!/bin/sh
BRANCH_NAME=$(git symbolic-ref --short HEAD)
git push -u origin $BRANCH_NAME
#!/usr/bin/env ruby
begin
require 'refined-refinements/colours'
rescue LoadError
abort "Run gem install refined-refinements."
end
using RR::ColouredTerminal
# Do not allow commiting to master.
if `git symbolic-ref --short HEAD`.chomp == 'master'
abort("<red>Error:</red> You're on master, y'know?")
end
# Format with Rubocop.
NONSTANDARD_RUBY_FILES = %w(Gemfile Guardfile Rakefile .pryrc)
changed_files = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
changed_ruby_files = changed_files.select do |path|
path.end_with?('.rb') || NONSTANDARD_RUBY_FILES.include?(path)
end
# Stage Rubocop changes.
unless changed_ruby_files.empty?
puts "<bold>~</bold> <green>Changed Ruby files:</green> #{changed_ruby_files.map { |file| "<bright_black>#{file}</bright_black>" }}"
puts "<bold>~</bold> <green>Running Rubocop.</green>"
system("bundle exec rubocop --auto-correct #{changed_ruby_files.join(' ')}")
system("git add #{changed_ruby_files.join(' ')}")
end
# Crystal lang version:
#
#!/usr/bin/env zsh
#
#crystal tool format
#git diff --cached --name-only --diff-filter=ACM | egrep '\.cr$' | xargs git add
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment