get commit message in git hook

前端 未结 4 1050
滥情空心
滥情空心 2020-12-03 06:49

I would like to check commit message before git commit. I use pre-commit hook to do that, but couldn\'t find the way to get commit message in .git/pre-commit script. How cou

相关标签:
4条回答
  • 2020-12-03 07:30

    You can do the following in a pre-receive hook (for server side) using Python, and that will display the revision information.

    import sys
    import subprocess
    old, new, branch = sys.stdin.read().split()
    proc = subprocess.Popen(["git", "rev-list", "--oneline","--first-parent" , "%s..%s" %(old, new)], stdout=subprocess.PIPE)
    commitMessage=str(proc.stdout.readlines()[0])  
    
    0 讨论(0)
  • 2020-12-03 07:35

    I implemented this in the commit-msg hook. See documentation.

    commit-msg
    This hook is invoked by git commit, and can be bypassed with the --no-verify option. 
    It takes a single parameter, the name of the file that holds the proposed commit log message. 
    Exiting with a non-zero status causes the git commit to abort.
    

    Under my_git_project/.git/hooks, I added this file commit.msg (has to be this name). I added the following bash contents inside this file which did the validation.

    #!/usr/bin/env bash
    INPUT_FILE=$1
    START_LINE=`head -n1 $INPUT_FILE`
    PATTERN="^(MYPROJ)-[[:digit:]]+: "
    if ! [[ "$START_LINE" =~ $PATTERN ]]; then
      echo "Bad commit message, see example: MYPROJ-123: commit message"
      exit 1
    fi
    
    0 讨论(0)
  • 2020-12-03 07:38

    The hook name should be:

    commit-msg , otherwise it won't get invoked:

    0 讨论(0)
  • 2020-12-03 07:50

    In the pre-commit hook, the commit message usually hasn't been created yet 1. You probably want to use one of the prepare-commit-msg or commit-msg hooks instead. There's a nice section in Pro Git on the order in which these hooks are run, and what you typically might do with them.

    1. The exception is that the committer might have supplied a commit message with -m, but the message still isn't accessible to the pre-commit hook, whereas it is to prepare-commit-msg or commit-msg

    0 讨论(0)
提交回复
热议问题