Append ticket number using git commit hooks?

前端 未结 6 1618
[愿得一人]
[愿得一人] 2020-12-24 02:21

So my branch is named after bugtracker ticket number, something like \"issue-1234\", and we have a convention to always write down ticket number in commit message. I\'m wond

6条回答
  •  温柔的废话
    2020-12-24 02:48

    Here's a complete solution for any kind of issue/ticket numbering commit messages:

    prepare-commit-msg

    #!/bin/bash
    # Append issue number / bug tracking URL to commit.
    #
    # If the branch name contains the issue number, it will append it to the
    # commit message. Example:
    #
    #   BRANCH NAME            LINE TO APPEND
    #   feature/GH-123-emoji   GitHub: #123
    #   WRIKE-123-add-payment  Wrike: https://www.wrike.com/open.htm?id=123
    #   UNKNOWN-123            Issue: #123
    
    branchName=`git rev-parse --abbrev-ref HEAD`
    
    IFS=- read issueTracker issueNumber <<< $(echo $branchName | sed -nr 's,([a-z-]+/)?([A-Z]+-[0-9]+)-.+,\2,p')
    
    if [[ -z $issueNumber ]]; then
      exit 0
    fi
    
    case "$issueTracker" in
      WRIKE)
        line="Wrike: https://www.wrike.com/open.htm?id=$issueNumber"
        ;;
      GH)
        line="GitHub: #$issueNumber"
        ;;
      GL)
        line="GitLab: #$issueNumber"
        ;;
      *)
        line="Issue: #$issueNumber"
        ;;
    esac
    
    # If the commit message already contains the line (`--amend`), then do
    # not add it again.
    if ! ( grep "$line" "$1" > /dev/null ); then
      sed -i.bak -e "/# Please enter the commit message for your changes./ s,^,$line\n\n," $1
    fi
    

    Put it into repository's .git/hooks directory to apply only to the repo, or set up core.hooksPath in ~/.gitconfig and copy to that directory to apply to all of your repositories.

    See in my config files repository besides other usefull scripts.

提交回复
热议问题