prepare-commit-msg 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env bash
  2. # Description: Git hook to check the JIRA reference in the commit message
  3. # Usage: Copy this file on your hooksPath with the name "commit-msg"
  4. # Ref: https://aviatrix.atlassian.net/l/c/ARC3NMy1#Git-client-hook-for-automatic-Jira-ref-insertion
  5. set -e
  6. [ -z "${GITHOOK_DEBUG}" ] || set -x
  7. # hook arguments
  8. COMMIT_MSG_FILE=$1
  9. # Possible values are none (git commit), message (git commit -m <msg>), template, merge, squash, or commit
  10. COMMIT_SOURCE=$2
  11. BRANCH=$(git branch --show-current)
  12. function get_sed () {
  13. OS=$(uname -s)
  14. if [ "${OS}" == "Linux" ]; then
  15. SED=$(command -v sed)
  16. else
  17. SED=$(command -v gsed)
  18. fi
  19. if [ -z "${SED}" ]; then
  20. echo ">> GNU 'sed' was not found on the system."
  21. echo ">> Please install it"
  22. exit 1
  23. fi
  24. echo "${SED}"
  25. }
  26. function not_include_ticket () {
  27. set -o pipefail
  28. if $(cat "$*" | grep -q "^JIRA: "); then
  29. return 1
  30. fi
  31. return 0
  32. }
  33. # Function to extract the ticket number:
  34. # Ex: AVXSRE-12324-toto -> AVXSRE-1234
  35. # AVXSRE-12134/titi -> AVXSRE-1234
  36. function get_branch_name () {
  37. echo "$*" | ${SED} -e 's@\([[:alpha:]]\+\).*-\([[:digit:]]\+\).*@\1-\2@g'
  38. }
  39. SED="$(get_sed)"
  40. BRANCH="$(get_branch_name $(git branch --show-current))"
  41. # check branch name isn’t empty (typical e.g. during rebase)
  42. if not_include_ticket "${COMMIT_MSG_FILE}" && [ -n "${BRANCH}" ]; then
  43. # check that this is a "message": if a -m or -F option was given
  44. if [ "${COMMIT_SOURCE}" == "message" ]; then
  45. echo >> ${COMMIT_MSG_FILE}
  46. echo "JIRA: ${BRANCH}" >> ${COMMIT_MSG_FILE}
  47. exit 0
  48. fi
  49. # check that this is a "commit"
  50. if [ -z "${COMMIT_SOURCE}" ]; then
  51. ${SED} -i "1s@^@\n\nJIRA: ${BRANCH}@" ${COMMIT_MSG_FILE}
  52. exit 0
  53. fi
  54. # check that this is an "amend"
  55. if [ "${COMMIT_SOURCE}" == "commit" ]; then
  56. ${SED} -i "2s@^@\n\nJIRA: ${BRANCH}\n@" ${COMMIT_MSG_FILE}
  57. exit 0
  58. fi
  59. fi