Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download single file from a git repository using python

I want to download single file from my git repository using python.

Currently I am using gitpython lib. Git clone is working fine with below code but I don't want to download entire directory.

import os
from git import Repo
git_url = '[email protected]:/home2/git/stack.git'
repo_dir = '/root/gitrepo/'
if __name__ == "__main__":
    Repo.clone_from(git_url, repo_dir, branch='master', bare=True)
    print("OK")
like image 410
Ravi Ranjan Avatar asked Jul 09 '18 06:07

Ravi Ranjan


2 Answers

Don't think of a Git repo as a collection of files, but a collection of snapshots. Git doesn't allow you to select what files you download, but allows you to select how many snapshots you download:

git clone [email protected]:/home2/git/stack.git

will download all snapshots for all files, while

git clone --depth 1 [email protected]:/home2/git/stack.git

will only download the latest snapshot of all files. You will still download all files, but at least leave out all of their history.

Of these files you can simply select the one you want, and delete the rest:

import os
import git
import shutil
import tempfile

# Create temporary dir
t = tempfile.mkdtemp()
# Clone into temporary dir
git.Repo.clone_from('[email protected]:/home2/git/stack.git', t, branch='master', depth=1)
# Copy desired file from temporary dir
shutil.move(os.path.join(t, 'setup.py'), '.')
# Remove temporary dir
shutil.rmtree(t)
like image 185
Nils Werner Avatar answered Oct 06 '22 08:10

Nils Werner


You can also use subprocess in python:

import subprocess

args = ['git', 'clone', '--depth=1', '[email protected]:/home2/git/stack.git']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, _error = res.communicate()

if not _error:
    print(output)
else:
    print(_error)

However, your main problem remains.

Git does not support downloading parts of the repository. You have to download all of it. But you should be able to do this with GitHub. Reference

like image 36
Benyamin Jafari Avatar answered Oct 06 '22 07:10

Benyamin Jafari