python - 使用 python 脚本作为 git filter-branch 的过滤器

标签 python git bash

我正在尝试使用 git filter-branch 重命名 git 存储库中的一些提交者。我很想使用一些更复杂的逻辑,但我不太了解 bash。我当前使用的(工作)脚本如下所示:

git filter-branch -f --tag-name-filter cat --env-filter '

cn="$GIT_COMMITTER_NAME"
cm="$GIT_COMMITTER_EMAIL"

if [ $cn = "ew" ]
then
    cn="Eric"
    cm="my.email@provider.com"
fi

export GIT_COMMITTER_NAME="$cn"
export GIT_COMMITTER_EMAIL="$cm"
' -- --all

我可以使用 python 脚本作为 --env-filter 参数吗?如果是这样,我如何才能访问 $GIT_COMMITTER_NAME 来读写它?

我如何在 python 文件中执行与该 bash 字符串等效的操作?

最佳答案

在python中,需要import os,之后os.environ是一个字典,里面有传入的环境。对 os.environ 的更改会自动导出。这里真正的问题是运行了 git 的 --filter-* 过滤器,正如它所说:

always evaluated in the shell context using the eval command (with the notable exception of the commit filter, for technical reasons).

所以它实际上是在使用 shell,如果你让 shell 调用 Python,你最终会得到 shell 的一个子进程,并且在 Python 进程中所做的任何更改都不会影响该 shell。您必须评估 Python 脚本的输出:

eval `python foo.py`

其中 foo.py 输出适当的 export 命令:

import os

def example():
    cn = os.environ['GIT_COMMITTER_NAME']
    cm = os.environ['GIT_COMMITTER_EMAIL']
    if cn == 'ew':
        cn = 'Eric'
        cm = 'my.email@provider.com'
    print ('export GIT_COMMITTER_NAME="%s"' % cn)
    print ('export GIT_COMMITTER_EMAIL="%s"' % cm)

example() # or if __name__ == '__main__', etc.

(以上所有内容均未经测试)。

关于python - 使用 python 脚本作为 git filter-branch 的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9692566/

相关文章:

git - 如何仅在当前目录中显示未跟踪的文件(忽略子目录)?

gitbranch 和 checkout 什么都不做?

bash - 如何使 GETOPTS 选项字符串选项区分大小写?

Python argparse 出现在 gc.garbage 中

python - 如何从 Python 语音识别中提取子字符串

python - 如何在 matplotlib 中使轴透明?

linux - 如何在Linux中对以数字命名的子目录进行排序

python - 使用Python从docx解析表

GitHub pull 请求 - "Allow edits by maintainers"

python - 在 python3 中从 bash 执行 DNS 查询的最佳方法是什么?