Skip to content

Instantly share code, notes, and snippets.

@brianoflan
Created January 12, 2018 23:45
Show Gist options
  • Save brianoflan/c18cd07f026bae344844f5a51901f13b to your computer and use it in GitHub Desktop.
Save brianoflan/c18cd07f026bae344844f5a51901f13b to your computer and use it in GitHub Desktop.
Wrap git to add a ticket number to every commit (put this earlier in your PATH than /usr/bin/git)
#!/bin/bash
REAL_GIT=${REAL_GIT-/usr/bin/git}
TICKET_PREFIX=TICKET-PREFIX- # Like JIRA-, REDMINE-, CLEARQUEST- or something.
TICKET_REGEX="${TICKET_PREFIX}[0-9][0-9]*"
main() {
local command=$1
shift
if [[ commit == $command ]] || [[ ticket == $command ]] ; then
get_ticket
fi ;
if [[ ticket != $command ]] ; then
$REAL_GIT $command "$@" || die "ERROR from '$REAL_GIT $command $@': $?." "$?"
fi ;
if [[ commit == $command ]] || [[ ticket == $command ]] ; then
local that_commit=$($REAL_GIT log -1 --pretty=%B)
if ! echo "$that_commit" | egrep -oh "$TICKET_REGEX" ; then
echo "NOTE: Last commit ('$that_commit') lacks any reference to a ticket ($TICKET_PREFIX)." 1>&2
local new_commit_msg=''
[[ -z $that_commit ]] && new_commit_msg="$TICKET" || new_commit_msg="$that_commit $TICKET"
$REAL_GIT commit --amend -m "$new_commit_msg"
else
echo "NOTE: Last commit ('$that_commit') already refers to a ticket ($TICKET_PREFIX)." 1>&2
fi ;
fi ;
}
die() {
echo "${1:-ERROR}" 1>&2
exit "${2-1}"
}
get_ticket() {
local ticket=''
local reporoot=$($REAL_GIT rev-parse --show-toplevel)
local changelog=$(ls "$reporoot/" | grep CHANGELOG \
|| ls "$reporoot/" | grep -i CHANGELOG
)
if [[ -z $ticket ]] ; then
if [ ${TICKET+x} ] ; then
# Try $TICKET variable:
ticket=$TICKET
elif [[ $changelog ]] ; then
# Try changelog in reverse chronological order (latest at head instead of tail):
ticket=$(egrep "$TICKET_PREFIX" "$reporoot/$changelog" | egrep -oh "$TICKET_REGEX" | head -1)
fi ;
fi;
if [[ -z $ticket ]] ; then
# Try $DEFAULT_TICKET variable:
if [ ${DEFAULT_TICKET+x} ] ; then
ticket=$DEFAULT_TICKET
fi ;
fi;
if ! echo "$ticket" | egrep "^$TICKET_REGEX" >/dev/null ; then
echo "WARNING: Ticket '$ticket' does not match TICKET_REGEX /^$TICKET_REGEX/." 1>&2
fi ;
if [[ -z $ticket ]] ; then
die "ERROR: Failed to determine current $TICKET_PREFIX ticket (matching /TICKET_REGEX/) via \$TICKET nor $reporoot/$changelog nor \$DEFAULT_TICKET."
return 1
fi ;
TICKET=$ticket
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment