Add a pre-commit hook to run rubocop
[chef.git] / hooks / pre-commit
1 #!/usr/bin/ruby
2
3 ok = true
4
5 if IO.popen(["git", "ls-files", "--unmerged"]).read.empty?
6   need_stash = IO.popen(%w(git diff)).read.length > 0
7
8   system("git", "stash", "save", "--keep-index", "--quiet") if need_stash
9
10   files = IO.popen(["git", "diff", "--staged", "--name-only"]).readlines.map(&:chomp)
11
12   ruby_files = files.select do |file|
13     file =~ /\.rb$/ || `file --brief --mime-type #{file}` == "text/x-ruby\n"
14   end
15
16   ok &&= system("rubocop", *ruby_files) unless ruby_files.empty?
17
18   system("git", "stash", "pop", "--quiet") if need_stash
19 else
20   puts "Unmerged files. Resolve before committing."
21   ok = false
22 end
23
24 exit ok