1. 程式人生 > >git學習--commit-msg缺失導致的missing Change-Id問題分析

git學習--commit-msg缺失導致的missing Change-Id問題分析

一.簡介  commit-msg hook  這個hook由’git commit’觸發, 且可以通過--no-verify 來略過.它接受一個引數, 包含commit msg的檔案的路徑.如果以非0狀態退出, ‘git commit’ 將會被取消.這個hook可以用於修改message(資訊)檔案, 用來匹配專案的規範格式(如果有的話).也可以用於校驗commit msg,並在必要時拒絕提交.預設的’commit-msg’ hook, 當啟用時,將檢查重複的”Signed-off-by”行, 如果找到,則取消commit.

二.問題情景  當執行git add “file”新增到暫存器,然後執行git commit提交到本地庫的時候,git需要在commit的時候在日誌中寫入一個唯一標識提交的SHA-1值,即是Change-Id值. git commit時會呼叫commit_msg指令碼檢查提交資訊,以便在git push的時候能正常推送到遠端庫。此時呼叫預設目錄下的commit_msg鉤子指令碼,預設目錄為“.git/hooks/commit_msg”. 如果此目錄下無commit_msg指令碼則commit時提交日誌中無ChangeId資訊,則在git push的時候出錯,無法正常吧改動上傳到遠端伺服器。  如下為git push提交不成功出現的錯誤資訊:

[分離頭指標 fbea87a] 測試
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 ttt
[email protected]:~/Work/test/test0$ git push origin HEAD:refs/for/master
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 223 bytes, done.
Total 2 (delta 0), reused 0 (delta 0)
remote: Processing changes: refs: 1, done    
remote: ERROR: missing Change-Id in commit message footer
remote: Suggestion for commit message:
remote: ttt
remote: 
remote: Change-Id: Ifbea87a6358d55a189528a5f501492c37bdfec21
remote: 
remote: Hint: To automatically insert Change-Id, install the hook:
remote:   gitdir=$(git rev-parse --git-dir); scp -p -P 29418 
[email protected]
:hooks/commit-msg ${gitdir}/hooks/ remote: remote: To ssh://[email protected]:29418/test/test0 ! [remote rejected] HEAD -> refs/for/master (missing Change-Id in commit message footer) error: 無法推送一些引用到 'ssh://[email protected]:29418/test/test0'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

三.解決方法  方法一:臨時解決

1> 複製Change-Id: Ifbea87a6358d55a189528a5f501492c37bdfec21

2> 執行 gitdir=$(git rev-parse --git-dir); scp -p -P 29418 [email protected]:hooks/commit-msg ${gitdir}/hooks/  從伺服器拷貝commit-msg指令碼到.git/hooks/目錄下

3> 執行git commit --amend重新修復提交,把第一步中的Change-Id: Ifbea87a6358d55a189528a5f501492c37bdfec21黏貼到提交日誌的下一行。

4> 重新執行git push推送本地改動到遠端伺服器
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

方法二:永久解決  存放一個全域性的鉤子指令碼配置,commit-msg可以從伺服器上拷貝,也可以用已有倉庫的commit-msg指令碼。本方法採用指令碼一次性解決。指令碼命名為commit_msg_hook.sh,只要執行一次指令碼然後重啟shell生效。當用戶執行git commit提交程式碼的時候會自動呼叫commit-msg指令碼在提交日誌中自動放入Change-Id資訊,不在需要手工寫入。指令碼內容如下:

SERVER_PORT="29418"
###gerrit伺服器ip地址,根據具體情況更改
SERVER_IP="192.168.77.11"
mkdir -p ~/.git_template/hooks
scp -p -P "$SERVER_PORT" "$SERVER_IP":hooks/commit-msg ~/.git_template/hooks
chmod u+x ~/.git_template/hooks/commit-msg
git config --global init.templatedir ~/.git_template
這裡寫程式碼片二.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

四.commit_msg指令碼解析

########################################

BEGIN: gerrit version v2.10版本的commit_msg鉤子指令碼如下:

########################################

#!/bin/sh
# From Gerrit Code Review 2.10
#
# Part of Gerrit Code Review (http://code.google.com/p/gerrit/)
#
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

unset GREP_OPTIONS

CHANGE_ID_AFTER="Bug|Issue"
MSG="$1"

# Check for, and add if missing, a unique Change-Id
#
add_ChangeId() {
    clean_message=`sed -e '
        /^diff --git .*/{
            s///
            q
        }
        /^Signed-off-by:/d
        /^#/d
    ' "$MSG" | git stripspace`
    if test -z "$clean_message"
    then
        return
    fi

    if test "false" = "`git config --bool --get gerrit.createChangeId`"
    then
        return
    fi

    # Does Change-Id: already exist? if so, exit (no change).
    ###grep引數-i, --ignore-case 忽略大小寫方式查詢以“Change-Id:”開頭字串###
    if grep -i '^Change-Id:' "$MSG" >/dev/null
    then
        return
    fi

    id=`_gen_ChangeId`

    ###$$:Shell本身的PID(ProcessID)###
    T="$MSG.tmp.$$"
    AWK=awk
    if [ -x /usr/xpg4/bin/awk ]; then
        # Solaris AWK is just too broken
        AWK=/usr/xpg4/bin/awk
    fi

    # How this works:
    # - parse the commit message as (textLine+ blankLine*)*
    # - assume textLine+ to be a footer until proven otherwise
    # - exception: the first block is not footer (as it is the title)
    # - read textLine+ into a variable
    # - then count blankLines
    # - once the next textLine appears, print textLine+ blankLine* as these
    #   aren't footer
    # - in END, the last textLine+ block is available for footer parsing
    $AWK '
    BEGIN {
        # while we start with the assumption that textLine+
        # is a footer, the first block is not.
        isFooter = 0
        footerComment = 0
        blankLines = 0
    }

    # Skip lines starting with "#" without any spaces before it.
    ###awk的next用法在處理逐行讀取文字方面很強大,next逐行讀取文字###
    /^#/ { next }

    # Skip the line starting with the diff command and everything after it,
    # up to the end of the file, assuming it is only patch data.
    # If more than one line before the diff was empty, strip all but one.
    /^diff --git / {
        blankLines = 0
        while (getline) { }
        next
    }

    # Count blank lines outside footer comments
    /^$/ && (footerComment == 0) {
        blankLines++
        next
    }

    # Catch footer comment
    /^\[[a-zA-Z0-9-]+:/ && (isFooter == 1) {
        footerComment = 1
    }

    /]$/ && (footerComment == 1) {
        footerComment = 2
    }

    # We have a non-blank line after blank lines. Handle this.
    (blankLines > 0) {
        print lines
        for (i = 0; i < blankLines; i++) {
            print ""
        }

        lines = ""
        blankLines = 0
        isFooter = 1
        footerComment = 0
    }

    # Detect that the current block is not the footer
    (footerComment == 0) && (!/^\[?[a-zA-Z0-9-]+:/ || /^[a-zA-Z0-9-]+:\/\//) {
        isFooter = 0
    }

    {
        # We need this information about the current last comment line
        if (footerComment == 2) {
            footerComment = 0
        }
        if (lines != "") {
            lines = lines "\n";
        }
        lines = lines $0
    }

    # Footer handling:
    # If the last block is considered a footer, splice in the Change-Id at the
    # right place.
    # Look for the right place to inject Change-Id by considering
    # CHANGE_ID_AFTER. Keys listed in it (case insensitive) come first,
    # then Change-Id, then everything else (eg. Signed-off-by:).
    #
    # Otherwise just print the last block, a new line and the Change-Id as a
    # block of its own.
    END {
        unprinted = 1
        if (isFooter == 0) {
            print lines "\n"
            lines = ""
        }
        changeIdAfter = "^(" tolower("'"$CHANGE_ID_AFTER"'") "):"
        numlines = split(lines, footer, "\n")
        for (line = 1; line <= numlines; line++) {
            if (unprinted && match(tolower(footer[line]), changeIdAfter) != 1) {
                unprinted = 0
                print "Change-Id: I'"$id"'"
            }
            print footer[line]
        }
        if (unprinted) {
            print "Change-Id: I'"$id"'"
        }
    }' "$MSG" > "$T" && mv "$T" "$MSG" || rm -f "$T"
}
_gen_ChangeIdInput() {
    echo "tree `git write-tree`"
    if parent=`git rev-parse "HEAD^0" 2>/dev/null`
    then
        echo "parent $parent"
    fi
    echo "author `git var GIT_AUTHOR_IDENT`"
    echo "committer `git var GIT_COMMITTER_IDENT`"
    echo
    printf '%s' "$clean_message"
}
_gen_ChangeId() {
    _gen_ChangeIdInput |
    git hash-object -t commit --stdin
}


add_ChangeId

########################################

END

########################################