【问题标题】:GitPython Is it possible to get file from specified commit without checkoutGitPython是否可以在不签出的情况下从指定的提交中获取文件
【发布时间】:2016-02-24 12:20:27
【问题描述】:

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

【问题讨论】:

  • 应该可以使用从任何提交中获取 blob 并从中读取,例如git.Repo().commit(COMMIT_HEX_SHA).tree['subdir/somefile.ext'].data_stream.

标签: python gitpython


【解决方案1】:

Byron's comment 确实为您提供了流,但请注意:如果您习惯于使用with-as 构造或.readlines() 来读取流,请不要在这里尝试。选择普通的.read()

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

如果您不想要尾随换行符,您也可以直接委托给git show,例如shown here

git.Repo().git.show(f'{COMMIT_HEX_SHA}:{file_with_path}')

【讨论】:

    【解决方案2】:

    我建议你使用 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)
    

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多