Git hook commit-msg git 添加文件

Git hook commit-msg git add file

我发现自己正在与一个具有繁琐的更改日志格式的团队合作。我决定要根据提交消息的详细信息自动创建更改日志条目。这个过程是你提供一个格式化的提交消息,然后我即时调整一个更改日志文件,并尝试将它添加到当前提交中。

我有一个提交消息挂钩:

#!/bin/bash

GIT_BRANCH=`git branch`

# Only run this hook on the master branch
if [ "$GIT_BRANCH" = '* master' ]
then
  # set some variables we'll need
  SAMPLE_COMMIT_MESSAGE="minor: #ws-666 Brings the devil back to life"
  COMMIT_MESSAGE_FILE=
  FULL_COMMIT_MESSAGE=$(cat $COMMIT_MESSAGE_FILE)
  CURRENT_DATE=$(date +"%Y-%m-%d")

  # let's do some pattern matching on the commit to set more variables
  [[ $FULL_COMMIT_MESSAGE =~ (ws-[0-9]+)[:space:]*(.*) ]]
  JIRA_ISSUE=${BASH_REMATCH[1]^^}
  COMMIT_MESSAGE=${BASH_REMATCH[2]}

  [[ $FULL_COMMIT_MESSAGE =~ ^(M) ]]
  if [ -n "${BASH_REMATCH[1]}" ]
  then
    CHANGE_IMPACT="_Major_"
  fi

  [[ $FULL_COMMIT_MESSAGE =~ ^(m) ]]
  if [ -n "${BASH_REMATCH[1]}" ]
  then
    CHANGE_IMPACT="_minor_"
  fi

  [[ $FULL_COMMIT_MESSAGE =~ ^([pP]) ]]
  if [ -n "${BASH_REMATCH[1]}" ]
  then
    CHANGE_IMPACT="_patch_"
  fi

  #echo Full Commit Message "$FULL_COMMIT_MESSAGE"
  #echo Jira issue $JIRA_ISSUE
  #echo Change Type $CHANGE_IMPACT 
  #echo Commit Message "$COMMIT_MESSAGE"

  if [ -z $JIRA_ISSUE ]
  then
    echo "You failed to specify a jira issue, your commit must look like:"
    echo "$SAMPLE_COMMIT_MESSAGE"
    exit 1
  fi

  if [ -z $CHANGE_IMPACT ]
  then
    echo "You failed to specify a change impact, your commit must look like:"
    echo "$SAMPLE_COMMIT_MESSAGE"
    exit 1
  fi

  if [ -z $COMMIT_MESSAGE ]
  then
    echo "You failed to specify an actual commit message, your commit must look like:"
    echo "$SAMPLE_COMMIT_MESSAGE"
    exit 1
  fi

  sed -i -e ":a;N;s/\(# Change log.*\)\n/\n\n\* next ($CURRENT_DATE)\n  $JIRA_ISSUE\n    \* $CHANGE_IMPACT: $COMMIT_MESSAGE/" change-log.md

  `git add change-log.md`

  echo Running $BASH_SOURCE
  set | egrep GIT
  echo PWD is $PWD

fi

# For testing, always exit
echo "Exiting, no commit made"
exit 1

然后我运行执行以下命令:

git checkout -- ../change-log.md ; git commit ../fake -m"Major #ws-123 WeeeeeeEE" ; git status

在 git 状态下我看到:

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   ../change-log.md

难道git不能在提交过程的这个阶段添加文件吗?关于如何最好地做到这一点的其他想法?我想我可以检查特定的更改日志条目是否存在,如果不存在,添加它,然后退出,要求添加该文件。

-j

在调用 git 添加之前编辑文件后添加 sleep 5m,然后下降到 shell 并键入 git add change-log.md 给了我 fatal: Unable to create '/home/jjshoe/test/.git/index.lock': File exists.

这完全有道理。

您可以做的一件事(有点老套)是使用以下单行添加一个 post-commit 钩子:

 git commit --amend -C HEAD --no-verify change-log.md

这将在每个提交发生变化时添加 change-log.md,如果没有发生变化则什么都不做。