0

Say I have a path to a git repository in the local filesystem: path_to_my_repository, and a path to a file in the repository path_to_file.

For a given list of dates, how can I get the corresponding version of the file on a particular branch from Python (i.e. loading the file in memory).

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564

1 Answers1

2

This shell command should do what you want:

git show "<branch>@{<timestamp>}:<path/to/file>"

For example:

git show "master@{yesterday}:some/file/in/repo"
git show "master@{2014-01-01 00:00:00}:another/file"

This prints to STDOUT.

To run this from an arbitrary directory, you can use the -C option to point to your repository root:

git -C path_to_my_repository show "master@{2014-05-05 12:00:00}:path_to_file"

You can run this from Python using the subprocess module like this, or something close to it:

from subprocess import Popen, PIPE

p = Popen(['git', '-C', path_to_my_repository, 'show',
        'master@{' + date_string + '}:' + path_to_file],
    stdin=PIPE, stdout=PIPE, stderr=PIPE)

# Content will be in `output`
output, err = p.communicate()

or using any other method to call a shell command. You should also be able to use libgit2, or a number of other tools.

Community
  • 1
  • 1
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • Thanks, I am unable to replicate this though, even in the shell: `git -C /Users/josh/code/reps/my_repo show "master@{2014-05-01 12:00:00}:/Users/josh/code/reps/my_repo/learning/main/config.xml" fatal: Path '/Users/josh/code/reps/my_repo/learning/main/config.xml' exists on disk, but not in 'master@{2014-05-01 12:00:00}`. However, I definitely know that file existed on that date. – Amelio Vazquez-Reina Jul 17 '14 at 21:48
  • 1
    @user815423426, the path should be a relative path within the repository. For example, in your case I believe you want to use `learning/main/config.xml`. – ChrisGPT was on strike Jul 17 '14 at 21:53