我想用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
的情况下从指定的提交中复制文件或读取文件?
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'))
我建议你使用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)