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

1

6

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?

Philippe answered 22/11, 2015 at 9:27 Comment(1)
It should be possible to use obtain a blob from any commit and read from it, e.g. git.Repo().commit(COMMIT_HEX_SHA).tree['subdir/somefile.ext'].data_stream.Penetrate
S
1

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}')
Sheath answered 19/12, 2018 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.