如何编写Python预推送来检查提交消息?

Lee*_*hai 5 python git githooks

我知道我可以使用 commit-msg 挂钩来检查消息(我做到了),但我希望在使用不同的标准推送之前再次检查消息。

.git/hooks 下给出的示例是用 shell 脚本编写的,但我希望编写一个 python 脚本,因为我想到的字符串操作更复杂。

我知道我可以将第一行更改为#!/usr/bin/env python. 我的问题是,我不知道如何获取最新提交的消息字符串。我尝试过git rev-list(在该示例的第 44 行),但它没有给我消息字符串,并且需要提交哈希 ID。请注意,消息字符串可能是多行(因为第一行限制为最多 50 个字符)。

EIDT:其他问题询问如何用 Python 编写预推送脚本,但不涉及检查消息字符串。

phd*_*phd 4

pre-push hook会传递本地/远程引用和提交 ID (sha1) 的列表,因此您必须逐行读取它们,拆分并获取本地提交 ID。看看如何在 shell 脚本中完成它。

有了提交 ID,您可以使用以下命令提取完整的提交消息

git show --format='%B' -s $SHA1
Run Code Online (Sandbox Code Playgroud)

在 Python 中它是这样的:

for line in sys.stdin:
    local_ref, local_sha1, remote_ref, remote_sha1 = line.strip().split()
    message = subprocess.check_output(
        ['git', 'show', '--format=%B', '-s', local_sha1])
    if not check(message):
        sys.exit(1)
Run Code Online (Sandbox Code Playgroud)