Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Last active September 23, 2015 18:27
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 kasparsd/5b9cbf1a25455f023d6a to your computer and use it in GitHub Desktop.
Save kasparsd/5b9cbf1a25455f023d6a to your computer and use it in GitHub Desktop.
Prepend the current Git branch name and the JIRA parent issue to every commit message
#!/bin/bash
#
# Prepend the current branch name to every commit message.
# Prepend the parent issue from JIRA, if found.
#
# Save this to .git/hooks/prepare-commit-msg and make it exacutable:
# chmod +x .git/hooks/prepare-commit-msg
#
# Extract the current working branch
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
# Prefix only JIRA style branches
if [[ ! "$BRANCH" =~ ^[A-Z]{2,} ]]; then
echo "Notice: Skipping commit message prefixing because the current branch doesn't start with capital letters (JIRA style)."
exit
fi
# Verify that Node.js is available
if ! command -v node >/dev/null 2>&1; then
echo "Error: Node.js is required for parsing the JIRA REST API response."
exit 1
fi
# Setup BASE64 auth value for JIRA authentication
JIRAAUTH=$(echo -n "USERNAME:PASSWORD" | base64)
if [ -z "$JIRAAUTH" ]; then
echo "Error: Failed to generate the base64 authorization key."
exit 1
fi
# Extract the commit message
MESSAGE=$(cat "$1")
# Get the issue details from JIRA REST API
ISSUEMETA=$(curl -s -X GET \
-H "Authorization: Basic $JIRAAUTH" \
-H "Content-Type: application/json" \
"https://YOURSLUG.atlassian.net/rest/api/2/issue/$BRANCH")
# Use Node.js to extract the parent issue key from the API response
ISSUEPARENT=$(node -pe 'JSON.parse(process.argv[1]).fields.parent.key' "$ISSUEMETA" 2>/dev/null)
if [ -n "$ISSUEPARENT" ]; then
# Prepend both the parent ticket and the current branch
echo "$ISSUEPARENT>$BRANCH: $MESSAGE" > "$1"
else
# Prepend only the current branch
echo "$BRANCH: $MESSAGE" > "$1"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment