#!/usr/bin/ruby ok = true if IO.popen(["git", "ls-files", "--unmerged"]).read.empty? need_stash = !IO.popen(%w[git diff]).read.empty? system("git", "stash", "save", "--keep-index", "--quiet") if need_stash files = IO.popen(["git", "diff", "--staged", "--name-status"]).map do |line| Regexp.last_match(1) if line =~ /^[AM]\s+(.*)$/ end.compact ruby_files = files.select do |file| file =~ /\.rb$/ || (file !~ /\.erb$/ && `file --brief --mime-type #{file}` == "text/x-ruby\n") end ok &&= system("bundle", "exec", "rubocop", *ruby_files) unless ruby_files.empty? cookbooks = files.grep(%r{(cookbooks/[^/]+)/}) { Regexp.last_match(1) }.uniq ok &&= system("bundle", "exec", "foodcritic", *cookbooks) unless cookbooks.empty? system("git", "stash", "pop", "--quiet") if need_stash else puts "Unmerged files. Resolve before committing." ok = false end exit ok