bash 如何将 Git 的分支名称添加到提交消息中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5894946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:28:59  来源:igfitidea点击:

How to add Git's branch name to the commit message?

gitbashgit-branch

提问by Tomer Lichtash

I need some help with a Bash script that will automatically add the git's branch name as a hash in commit messages.

我需要一些有关 Bash 脚本的帮助,该脚本会自动将 git 的分支名称添加为提交消息中的哈希值。

采纳答案by ninjagecko

Use the prepare-commit-msgor commit-msggithook.

使用prepare-commit-msgcommit-msggithook

There are examples already in your PROJECT/.git/hooks/directory.

您的PROJECT/.git/hooks/目录中已有示例。

As a security measure, you will have to manually enable such a hook on each repository you wish to use it. Though, you can commit the script and copy it on all clones into the .git/hooks/directory.

作为一项安全措施,您必须在要使用它的每个存储库上手动启用此类挂钩。不过,您可以提交脚本并将其在所有克隆上复制到.git/hooks/目录中。

回答by shytikov

Here is my commit-msgscript as an example:

这是我的commit-msg脚本作为示例:

#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
#
NAME=$(git branch | grep '*' | sed 's/* //') 
DESCRIPTION=$(git config branch."$NAME".description)

echo "$NAME"': '$(cat "") > ""
if [ -n "$DESCRIPTION" ] 
then
   echo "" >> ""
   echo $DESCRIPTION >> ""
fi 

Creates following commit message:

创建以下提交消息:

[branch_name]: [original_message]

[branch_description]

I'm using issue number as branch_name, issue description is placed to the branch_descriptionusing git branch --edit-description [branch_name]command.

我正在使用问题编号 as branch_name,问题描述放在branch_descriptionusinggit branch --edit-description [branch_name]命令中。

More about branch descriptions you can find on this Q&A.

您可以在此问答中找到有关分支描述的更多信息。

The code example is stored in following Gist.

代码示例存储在以下Gist 中

回答by Pylinux

A bit simpler script that adds the branch name to the commit message beforeyou edit it. So if you want want to change or remove it you can.

一个更简单的脚本,编辑之前将分支名称添加到提交消息中。所以如果你想改变或删除它,你可以。

Create this file .git/hooks/prepare-commit-msg:

创建这个文件.git/hooks/prepare-commit-msg

#!/bin/bash

branchPath=$(git symbolic-ref -q HEAD) #Somthing like refs/heads/myBranchName
branchName=${branchPath##*/}      #Get text behind the last / of the branch path

firstLine=$(head -n1 )

if [ -z "$firstLine"  ] ;then #Check that this is not an amend by checking that the first line is empty
    sed -i "1s/^/$branchName: \n/"  #Insert branch name at the start of the commit message file
fi

回答by Farid Movsumov

You can do it with a combination of the prepare-commit-msg and pre-commit hooks.

您可以结合使用 prepare-commit-msg 和 pre-commit 钩子来做到这一点。

.git/hooks/prepare-commit-msg

.git/hooks/prepare-commit-msg

#!/bin/sh

BRANCH=`git branch | grep '^\*' | cut -b3-`
FILE=`cat ""`
echo "$BRANCH $FILE" > ""

.git/hooks/pre-commit

.git/钩子/预提交

#!/bin/bash

find vendor -name ".git*" -type d | while read i
do
        if [ -d "$i" ]; then
                DIR=`dirname $i`
                rm -fR $i
                git rm -r --cached $DIR > /dev/null 2>&1
                git add $DIR > /dev/null 2>&1
        fi
done

Set permissions

设置权限

sudo chmod 755 .git/hooks/prepare-commit-msg
sudo chmod 755 .git/hooks/pre-commit

回答by Tim

add the below code in prepare-commit-msg file.

在 prepare-commit-msg 文件中添加以下代码。

#!/bin/sh
#
# Automatically add branch name and branch description to every commit message except merge commit.
#

COMMIT_EDITMSG=

addBranchName() {
  NAME=$(git branch | grep '*' | sed 's/* //') 
  DESCRIPTION=$(git config branch."$NAME".description)
  echo "[$NAME]: $(cat $COMMIT_EDITMSG)" > $COMMIT_EDITMSG
  if [ -n "$DESCRIPTION" ] 
  then
     echo "" >> $COMMIT_EDITMSG
     echo $DESCRIPTION >> $COMMIT_EDITMSG
  fi 
}

MERGE=$(cat $COMMIT_EDITMSG|grep -i 'merge'|wc -l)

if [ $MERGE -eq 0 ] ; then
  addBranchName
fi

It will add branch name to commit message except merge-commit. The merge-commit has branch information by defaultso extra branch name is unnecessary and make the message ugly.

除了合并提交之外,它将向提交消息添加分支名称。合并提交默认具有分支信息,因此不需要额外的分支名称并使消息变得丑陋。

回答by Novice C

Inspired by Tim's answer which builds upon the top answer, it turns out the prepare-commit-msg hook takes as an argument what kind of commit is occurring. As seen in the default prepare-commit-msg if $2 is 'merge' then it is a merge commit. Thus the case switch can be altered to include Tim's addBranchName() function.

受到 Tim 的答案的启发,该答案建立在最佳答案的基础上,事实证明 prepare-commit-msg 钩子将正在发生的提交类型作为参数。正如在默认的 prepare-commit-msg 中看到的,如果 $2 是“合并”,那么它就是一个合并提交。因此可以更改大小写开关以包含 Tim 的 addBranchName() 函数。

I've included my own preference for how to add the branch name, and all the uncommented parts of the default prepare-commit-msg.samplehook.

我已经包含了我自己对如何添加分支名称的偏好,以及默认prepare-commit-msg.sample挂钩的所有未注释部分。

prepare-commit-msg

准备提交消息

#!/bin/sh

addMyBranchName() {
  # Get name of current branch
  NAME=$(git branch | grep '*' | sed 's/* //')

  # First blank line is title, second is break for body, third is start of body
  BODY=`cut -d \| -f 6  | grep -v -E .\+ -n | cut -d ':' -f1 | sed '3q;d'`

  # Put in string "(branch_name/): " at start of commit message body.
  # For templates with commit bodies
  if test ! -z $BODY; then
    awk 'NR=='$BODY'{
mkdir -p ~/.git_hooks
# make it executable
chmod a+x ~/.git_hooks/commit-msg
="\('$NAME'/\): "}1;' > tmp_msg && mv tmp_msg "" else echo "title\n\n($NAME/):\n`cat `\n" > "" fi } # You might need to consider squashes case "," in # Commits that already have a message commit,?*) ;; # Messages are one line messages you decide how to handle message,) ;; # Merge commits merge,) # Comments out the "Conflicts:" part of a merge commit. perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "" ;; # Non-merges with no prior messages *) addMyBranchName ;; esac

回答by Maroun

If you want to make it global (for all projects):

如果你想让它成为全球性的(对于所有项目):

Create git-msgfile with the content of shytikov's answer, and put it in some folder:

git-msg使用shytikov's answer的内容创建文件,并将其放在某个文件夹中:

git config --global init.templatedir '~/.git_hooks'

Now enable hooks:

现在启用钩子:

#!/bin/sh
#
# A hook script to prepare the commit log message.
# If the branch name it's a jira Ticket.
# It adds the branch name to the commit message, if it is not already part of it.

branchPath=$(git symbolic-ref -q HEAD) #Somthing like refs/heads/myBranchName
branchName=${branchPath##*/}      #Get text behind the last / of the branch path

regex="(PROJECTNAME-[0-9]*)"

if [[ $branchName =~ $regex ]]
then
    # Get the captured portion of the branch name.
    jiraTicketName="${BASH_REMATCH[1]}"

    originalMessage=`cat `

    # If the message already begins with PROJECTNAME-#, do not edit the commit message.
    if [[ $originalMessage == $jiraTicketName* ]]
        then
        exit
    fi

    sed -i '.bak' "1s/^/$jiraTicketName: /"  #Insert branch name at the start of the commit message file
fi

and git initagain in each project you want to use it.

git init再次在您想要使用它的每个项目中。

回答by Mihai Georgescu

In case you want the JIRA ticket added to the commit message use the script bellow.

如果您希望将 JIRA 票添加到提交消息中,请使用以下脚本。

Commit message something like PROJECT-2313: Add awesome featureThis requires your branch name to start with the jira Ticket.

提交类似PROJECT-2313: Add awesome feature这样的消息需要您的分支名称以 jira 票证开头。

This is a combination of this solutions:

这是以下解决方案的组合:

It is modified for OS X, with the sed -i '.bak'and it works as well from SourceTree.

它针对 OS X 进行了修改,sed -i '.bak'并且在 SourceTree 中也能正常工作。

https://gist.github.com/georgescumihai/c368e199a9455807b9fbd66f44160095

https://gist.github.com/georgescumihai/c368e199a9455807b9fbd66f44160095

#!/bin/sh
BRANCH=$(cat .git/HEAD  | cut -d '_' -f2)
if [ ! -z "$BRANCH" ]
then
    echo "$BRANCH" > "/Users/username/.gitmessage" 
else
    echo "[JIRA NUMBER]" > "/Users/username/.gitmessage"
fi 

回答by PhPGuy

I was having issues getting these solutions to work on MacOS due to the fact that it uses BSD sedinstead of GNU sed. I managed to create a simple script that does the job though. Still using .git/hooks/pre-commit:

由于 MacOS 使用 BSDsed而不是 GNU ,我在让这些解决方案在 MacOS 上工作时遇到了问题sed。我设法创建了一个简单的脚本来完成这项工作。仍在使用.git/hooks/pre-commit

##代码##

This assumes a branch naming standard similar to functional-desc_JIRA-NUMBER. If your branch name is only your Jira ticket number you can simply get rid of everything from the pipe to the f2. It also requires that you have a file named .gitmessagein your home directory.

这假定分支命名标准类似于functional-desc_JIRA-NUMBER. 如果您的分支名称只是您的 Jira 票号,您可以简单地摆脱从管道到 f2 的所有内容。它还要求您.gitmessage在主目录中有一个命名的文件。