Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active April 4, 2018 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/1fc7eae317f8be8077156768191c0789 to your computer and use it in GitHub Desktop.
Save havenwood/1fc7eae317f8be8077156768191c0789 to your computer and use it in GitHub Desktop.
A crystal git command that prints the shasum of your last commit. Just `crystal build git-sum.cr --release` and put the resulting `git-sha` executable in your PATH, then `git sha`.
require "colorize"
require "option_parser"
##
# Use color by default if stdout is a terminal.
color = STDOUT.tty?
OptionParser.parse! do |opts|
opts.banner = "usage: git sum [-h --help] [--no-color]"
# Git redirects --help to the manpage.
opts.on "-h", "print this help menu" do
puts opts
exit
end
opts.on "--no-color", "omit color" do
color = false
end
end
checksum = IO::Memory.new
git_error = IO::Memory.new
checksum_command = Process.run "git", {"rev-parse", "HEAD"}, output: checksum, error: git_error
abort git_error.to_s.chomp, checksum_command.exit_code unless checksum_command.success?
if color
abbrev = IO::Memory.new
abbrev_command = Process.run "git", {"config", "--get", "core.abbrev"}, output: abbrev
short = abbrev_command.success? ? abbrev.to_s.to_i : 9
print checksum.to_s[0..short.to_s.to_i.pred].colorize(:green).mode(:bold)
print checksum.to_s[short.to_s.to_i..-1].colorize(:magenta).mode(:bold)
else
print checksum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment