Search code examples
pythongitpython

GitPython Is it possible to get file from specified commit without checkout


I want to copy files from specified commit with GitPython. Now I come here so far:

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()

It works. But checkout changes HEAD and changes files. Is it possible to copy files or read files from specified commit without checkout?


Solution

  • Byron's comment does indeed give you a stream, but a word of caution: If you're used to using a with-as construct or .readlines() to read streams, don't try them here. Go for plain .read().

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

    If you don't want the trailing newline, you can also delegate directly to git show like shown here:

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