GitPython是否可以在没有签出的情况下从指定的提交中获取文件

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

我想用GitPython从指定的提交中复制文件。我到目前为止来到这里:

import git
git = git.Git(REPO_PATH)
git.checkout(COMMIT_HEX_SHA)
fo = open(REPO_PATH + "/foo.txt", "r")
str = fo.read(10);
fo.close()

有用。但checkout更改HEAD并更改文件。是否可以在没有checkout的情况下从指定的提交中复制文件或读取文件?

python gitpython
2个回答
0
投票

Byron's comment确实给你一个流,但请注意:如果你习惯使用with.readlines()读取流,不要在这里尝试。去寻找简单的.read()

git.Repo().commit(COMMIT_HEX_SHA).tree['subdir/somefile.ext'].data_stream.read()

如果你不想要尾随换行符,你也可以像git show一样直接委托给shown here

git.Repo().git.show('{}:{}'.format(COMMIT_HEX_SHA, 'subdir/somefile.ext'))

0
投票

我建议你使用PyDriller(它在内部使用GitPython)。它更容易使用:

for commit in RepositoryMining("path_to_repo", single="commitHASH").traverse_commits():
    for modified_file in commit.modifications:
        # do whatever you want with the source code
        print(modified_file.source_code)
© www.soinside.com 2019 - 2024. All rights reserved.