Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active August 3, 2022 20:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henrik/e8583343ce0347db7f2480f46cf4fdce to your computer and use it in GitHub Desktop.
Save henrik/e8583343ce0347db7f2480f46cf4fdce to your computer and use it in GitHub Desktop.
Git hook to run Rubocop on changed files after committing, without locking up the terminal. Bit of a WIP.
#!/usr/bin/env ruby
# diff-filter=AM = only show added and modified, not removed
changed_files = `git diff-tree --no-commit-id --name-only --diff-filter=AM -r HEAD`.lines.map(&:chomp)
unless changed_files.empty? # E.g. an "--allow-empty" commit.
bg_process = fork do
# This will report offenses in the entirety of the updated files, not just the changed lines. Not sure if we could easily get Rubocop to check changed-lines only, but this may be good enough.
rubocop_results = `bundle exec rubocop --color #{changed_files.join(" ")}`
no_offenses_detected = rubocop_results.include?("\e[32mno offenses\e[0m detected")
unless no_offenses_detected
puts rubocop_results
puts
# If the background process outputs after the prompt has rendered in the main process, you won't see a prompt with bash (maybe with zsh).
# Could we somehow communicate back to the main process and have it display another prompt for us?
puts "Press 'Enter' if you didn't get your prompt back."
puts
end
end
# Run in a detached BG process so the main script can finish (returning you to the terminal prompt) quickly. It can still output the results to the terminal from the BG process.
Process.detach(bg_process)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment