Skip to content

Instantly share code, notes, and snippets.

@marioizquierdo
Last active July 3, 2018 11:24
Show Gist options
  • Save marioizquierdo/6443317 to your computer and use it in GitHub Desktop.
Save marioizquierdo/6443317 to your computer and use it in GitHub Desktop.
git hook commit message for JIRA and Trello branches
#!/usr/bin/env ruby
#
# Git commit-msg hook.
#
# If your branch name is in the form "story/DIO-1234/description",
# automatically adds "DIO-1234/description: " to commit messages, unless they mention "DIO-1234" already.
#
# If your branch name is in the form "mario/1234-my-trello-card",
# automatically adds "1234-my-trello-card: " to commit messages, unless they mention "1234" already.
#
# By Mario Izquierdo.
#
# Install:
# Create a file with this content in `yourproject/.githooks/commit-msg`
# or put this file somewhere, for example `~/.githooks/commit-msg-jira-trello`, and symlink it:
#
# $ cd yourproject
# $ ln -s ~/.githooks/commit-msg-jira-trello .git/hooks/commit-msg
#
branchname = `git branch --no-color 2> /dev/null`[/^\* (.+)/, 1].to_s # get current branch name
commit_message_file = ARGV[0] # argument given by git when calling this hook
original_commit_message = File.read(commit_message_file).strip
# JIRA
jira_pattern = /(DIO-\d+)\/(.*)/i # match branch names like story/DIO-1234/blabla_blabla
if m = branchname.match(jira_pattern)
jira_number, short_desc = m.captures
exit if original_commit_message.include?(jira_number) # do not add the jira number again if it is already in the commit message
# Add jira_number and short_desc to commit message
message = "#{jira_number}/#{short_desc}: #{original_commit_message}"
File.open(commit_message_file, 'w') {|f| f.write message }
end
# Trello
trello_pattern = /\/((\d+)-[^\/]+)$/i # match branch names like mario/1234-my-trello-card
if m = branchname.match(trello_pattern)
trello_url, trello_id = m.captures
exit if original_commit_message.include?(trello_id) # do not add the trello url again if the id is already in the commit message
# Add trello_url to commit message
message = "#{trello_url}: #{original_commit_message}"
File.open(commit_message_file, 'w') {|f| f.write message }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment