如何通过Python修改Git提交信息?

问题描述 投票:0回答:2

我已经使用

subprocess.check_output
来获取 Git 命令的结果,但我想不出如何更新我们使用命令
git commit -amend
所做的提交消息?

git subprocess git-commit gitpython
2个回答
1
投票

您可以将提交消息传递给

git commit --amend
。例如:

git commit --amend -m "This is a new commit message"

或者您可以从文件中读取新的提交消息:

git commit --amend -F commitmsg

或者您可以从 stdin 读取它:

echo "This is a new commit message" | git commit --amend -F-

您可以通过 Python 使用这些机制中的任何一种。


0
投票

您可以使用Python作为编辑器,因此修改使用

GIT_EDITOR
,它可以是您自己的Python命令来操作文本,这甚至可以是对包含代码片段的Python的调用,例如

import os
import subprocess
# Add "Some Appended Text!" after the commit message.
subprocess.check_call(
    ("git", "commit", "--amend"),
    env={
        **os.environ,
        "GIT_EDITOR": "".join([
            """'%s' -c "import sys;""" % sys.executable,
            """file = sys.argv[-1];""",
            """data = open(file, 'r').read();""",
            """data = '\\n'.join([l for l in data.split('\\n') if not l.startswith('#')]);""",
            """data = data.rstrip() + '\\n\\nSome Appended Text!\\n';""" % ,
            """open(file, 'w').write(data)" - """,
        ]),
    }
)

© www.soinside.com 2019 - 2024. All rights reserved.