]> git.openstreetmap.org Git - chef.git/commitdiff
Add a pre-commit hook to run rubocop
authorTom Hughes <tom@compton.nu>
Wed, 4 Feb 2015 19:22:14 +0000 (19:22 +0000)
committerTom Hughes <tom@compton.nu>
Wed, 4 Feb 2015 22:44:49 +0000 (22:44 +0000)
To run rubocop on checkin, copy this script to .git/hooks and
it will cause any attempt to commit code which fails rubcop to
be blocked.

hooks/pre-commit [new file with mode: 0755]

diff --git a/hooks/pre-commit b/hooks/pre-commit
new file mode 100755 (executable)
index 0000000..6f7912f
--- /dev/null
@@ -0,0 +1,24 @@
+#!/usr/bin/ruby
+
+ok = true
+
+if IO.popen(["git", "ls-files", "--unmerged"]).read.empty?
+  need_stash = IO.popen(%w(git diff)).read.length > 0
+
+  system("git", "stash", "save", "--keep-index", "--quiet") if need_stash
+
+  files = IO.popen(["git", "diff", "--staged", "--name-only"]).readlines.map(&:chomp)
+
+  ruby_files = files.select do |file|
+    file =~ /\.rb$/ || `file --brief --mime-type #{file}` == "text/x-ruby\n"
+  end
+
+  ok &&= system("rubocop", *ruby_files) unless ruby_files.empty?
+
+  system("git", "stash", "pop", "--quiet") if need_stash
+else
+  puts "Unmerged files. Resolve before committing."
+  ok = false
+end
+
+exit ok