source

커밋 메시지에 Git 지점 이름을 추가하는 방법

ittop 2023. 4. 17. 22:29
반응형

커밋 메시지에 Git 지점 이름을 추가하는 방법

Git의 브랜치 이름을 자동으로 커밋 메시지로 추가하는 Bash 스크립트에 대한 도움이 필요합니다.

제 사진이 .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 "$1") > "$1"
if [ -n "$DESCRIPTION" ] 
then
   echo "" >> "$1"
   echo $DESCRIPTION >> "$1"
fi 

다음 커밋 메시지를 만듭니다.

[branch_name]: [original_message]

[branch_description]

는요, 발행번호로 쓰고 branch_name 의 설명은, 「」에 되어 있습니다.branch_description를 사용합니다.git branch --edit-description [branch_name]명령어를 입력합니다.

브랜치에 대한 자세한 내용은 이 Q&A에서 확인할 수 있습니다.

코드 예는 다음 Gist에 저장되어 있습니다.

하다를 사용하세요.prepare-commit-msg ★★★★★★★★★★★★★★★★★」commit-msg githook.

.PROJECT/.git/hooks/디렉토리로 이동합니다.

보안 대책으로 사용하는 각 저장소에서 이러한 후크를 수동으로 활성화해야 합니다.에서 " "에 할 수 ..git/hooks/디렉토리로 이동합니다.

커밋 메시지를 편집하기 전에 브랜치 이름을 커밋메시지에 추가하는 간단한 스크립트입니다.변경 또는 삭제가 필요한 경우 변경할 수 있습니다.

.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 $1)

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

prepare-commit-msg 및 pre-commit 후크를 조합하여 수행할 수 있습니다.

.syslog/syslog/syslog-commit-msg

#!/bin/sh

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

.syslog/syslog/pre-commit

#!/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

권한 설정

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

다음 코드를 prepare-commit-msg 파일에 추가합니다.

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

COMMIT_EDITMSG=$1

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

merge-commit 이외의 브랜치명이 커밋메시지에 추가됩니다.merge-commit에는 기본적으로 분기 정보가 있기 때문에 분기 이름을 추가할 필요가 없으며 메시지를 보기 흉하게 만듭니다.

상위 답변에 기반한 Tim의 답변에서 영감을 얻어 prepare-commit-msg 훅은 어떤 종류의 커밋이 발생하고 있는지 인수로 간주합니다.디폴트 prepare-commit-msg에서 알 수 있듯이 $2가 'merge'일 경우 머지 커밋입니다.따라서 케이스 스위치는 Tim의 addBranchName() 함수를 포함하도록 변경할 수 있습니다.

에 대한 지점명 추가 방법 중 없는 prepare-commit-msg.sample

준비 커밋 메시지

#!/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 $1 | 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'{$0="\('$NAME'/\): "}1;' $1 > tmp_msg && mv tmp_msg "$1"
  else
    echo "title\n\n($NAME/):\n`cat $1`\n" > "$1"
  fi
}

# You might need to consider squashes
case "$2,$3" 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' "$1"
  ;;

  # Non-merges with no prior messages
  *)
    addMyBranchName $1
  ;;
esac

글로벌하게 하고 싶은 경우(모든 프로젝트에서)

git-msgshytikov의 답변 내용을 파일로 정리하여 다음 폴더에 넣습니다.

mkdir -p ~/.git_hooks
# make it executable
chmod a+x ~/.git_hooks/commit-msg

후크를 유효하게 합니다.

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

★★★★★★★★★★★★★★★★★」git init사용할 각 프로젝트에서 다시 사용할 수 있습니다.

커밋 메시지에 JIRA 티켓을 추가할 경우 아래 스크립트를 사용합니다.

" " 등의 를 .PROJECT-2313: Add awesome feature이를 위해서는 지점 이름이 jira 티켓으로 시작해야 합니다.

이 솔루션의 조합은 다음과 같습니다.

X용으로 가 변경되었습니다.sed -i '.bak'소스 트리

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

#!/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 $1`

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

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

이 답변(https://stackoverflow.com/a/17270862/9266796))을 편집하여 이름에 슬래시가 포함된 지점에서도 사용할 수 있습니다.@/sed세퍼레이터를 선택합니다.을 취득하는 .git branch --show-current, 메시지의 제목이 쉽기 에, 의 맨 이는 메시지의 실제 제목이 처음에 표시되는 것이 더 타당하기 때문입니다.

은 '일부러'로 해야 합니다..git/hooks/prepare-commit-msg.

#!/bin/bash

branchName=$(git branch --show-current)
firstLine=$(head -n1 $1)

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

필요에 따라 조정했습니다.

#!/bin/bash

# hook arguments
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

BRANCH_NAME=$(git branch --show-current)

# check branch name isn’t empty (typical e.g. during rebase)
if [ -n "$BRANCH_NAME" ]
then
  # check that this is a regular commit
  if [ "$COMMIT_SOURCE" = "message" ] || [ -z "$COMMIT_SOURCE" ]
  then
      sed -r -i "1!b;/^(fixup|squash)/! s@^@$BRANCH_NAME @" $COMMIT_MSG_FILE # insert branch name at the start of the commit message file
  fi
fi

클립을 해 주세요.prepare-commit-msg 내 " " ".git/hooks더입니니다다

경우 되어야 합니다.git commit,git commit -m …마지, 기본을 바꿔라.

BSD BSD를 시키는 데 .sed GNU가 sed작업을 수행할 수 있는 간단한 스크립트를 만들 수 있었습니다. still직 still still를 하고 있다..git/hooks/pre-commit:

#!/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 

을 가정한 입니다.functional-desc_JIRA-NUMBER지점명이 Jira 티켓 번호일 경우 파이프에서 f2까지 모두 제거할 수 있습니다.또, 파일명도 필요합니다..gitmessage을 사용하다

여기에 있는 훌륭한 답들을 조합하고 몇 가지 수정사항을 더하면.git/hooks/prepare-commit-msg.feature/ABC-#123-feature-title 출력 " " "ABC #123:

COMMIT_MSG=$1
REPLACE_DELIMETER=true
FIRST_LINE=$(head -n1 $COMMIT_MSG)

addBranchName() {
  BRANCH_NAME=$(git branch | grep '*' | sed 's/* //') # get the branch name (e.g. `feature/ABC-#123-feature-title`)
  NAME=${BRANCH_NAME##*/} # get everything after the last slash (e.g. `ABC-#123-feature-title`)
  DELIMITER=$(echo $NAME | grep -o '[-_]' | head -n1) # get the character that separates the parts (e.g. `-`)
  FEATURE_ID=$(echo $NAME | cut -d $DELIMITER -f 1,2) # get the first two parts of the name, split by the delimeter found in the branch name (e.g. `ABC-#123`)

  if [ "$REPLACE_DELIMETER" = true ]; then
    FEATURE_ID=$(echo $FEATURE_ID | sed "s/$DELIMITER/ /g") # replace the delimiter if `REPLACE_DELIMETER` is set to true (e.g. `ABC #123`)
  fi

  echo "$FEATURE_ID: $(cat $COMMIT_MSG)" > $COMMIT_MSG # prepend the name and parse the existing commit message (for instance commented out commit details)
}

if [ -z "$FIRST_LINE" ]; then # check that this is not an amend by checking that the first line is empty
  addBranchName
fi

여기에는 git prepare-commit-msg 훅을 사용할 수 있습니다.

후크는 다음과 같습니다.

# Get the currently checked-out branch name
BRANCH_NAME=$(git branch | grep '*' | sed 's/* //')

# Get the commit message, removing lines that start with a #
MESSAGE=$(cat "$1" | sed '/^#.*/d')

# Check if the commit message is non-empty
if [ -n "$MESSAGE" ]
then
    # Add the branch name and the commit message
    echo "$BRANCH_NAME: $MESSAGE" > "$1"
else
    echo "Aborting commit due to empty commit message."
    exit 1
fi

기본 병합 설명에는 이미 분기 이름이 포함되어 있으므로 병합을 커밋할 때 분기 이름을 포함하지 않을 수 있습니다.git이 머지되면 MERGE_HEAD 파일이 .git 폴더에 추가됩니다.브랜치명을 입력하기 전에 훅을 종료할 수 있습니다.

# Check if the MERGE_HEAD file is present
if [ -f ".git/MERGE_HEAD" ]
then
    exit 0
fi

GIST에서 풀 훅을 가져올 수 있습니다.

Git 훅은 저장소별로 작동하므로 후크 파일을 사용하는 각 저장소의 .git/hooks 디렉토리에 복사해야 합니다.git 훅을 여러 저장소에 추가하는 프로세스를 자동화하려면 저장소의 루트 폴더에서 다음 스크립트를 실행할 수 있습니다.

다음과 같이 스크립트를 gist에서 root 폴더로 가져올 수 있습니다.

curl -s "https://gist.githubusercontent.com/wolf6101/a90126e4b47a943e0235861516236eb3/raw/2f505db26d8adbabab9b93a8bb990ab42b2fb55c/apply-git-hooks.sh" -o "apply-git-hooks.sh"  

후크를 추가하려면:

sh apply-git-hooks.sh     

후크를 제거하려면:

sh apply-git-hooks.sh remove

ABC-123이라는 이름의 브런치를 커밋하면 다음과 같이 됩니다.

git commit -m "I wrote something incredible, check this out"

"ABC-123: 내가 엄청난 글을 썼어, 이것 좀 봐"라는 메시지가 표시됩니다.

이는 GUI를 통한 커밋에도 적용됩니다.

언급URL : https://stackoverflow.com/questions/5894946/how-to-add-gits-branch-name-to-the-commit-message

반응형