Python script to download/shallow clone the files of a directory at bitbucket. This is useful when you just want a copy of the files in a subdirectory of a repository without needing mercurial or having to download the entire repository.
Last active
November 22, 2022 22:14
-
-
Save christophermanning/1474925 to your computer and use it in GitHub Desktop.
Bitbucket Download Directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import sys | |
import urllib | |
from urlparse import urlparse | |
try : import json | |
except : import simplejson as json | |
def open_directory(API_PATH, username, repo_slug, path): | |
directory_url = "%s/%s/%s/%s" % (API_PATH, username, repo_slug, path) | |
json_data_url_handle = urllib.urlopen(directory_url) | |
if json_data_url_handle.code != 200: | |
print "url %s not found" % directory_url | |
exit() | |
json_directory = json.loads(json_data_url_handle.read()) | |
for directory in json_directory['directories']: | |
open_directory(API_PATH, username, repo_slug, path + "/" + directory) | |
for file in json_directory['files']: | |
try: | |
os.makedirs(os.path.dirname(file['path'])) | |
except OSError: | |
None | |
print "downloading %s" % file['path'] | |
urllib.urlretrieve("%s/%s/%s/raw/%s/%s" % (API_PATH, username, repo_slug, file['revision'], file['path']), file['path']) | |
if (len(sys.argv) != 2 or sys.argv[1].find("https://bitbucket.org/") != 0 or sys.argv[1].find("/src/") == -1): | |
print "usage: python bitbucket_download.py https://bitbucket.org/pypy/pypy/src/b590cf6de419/demo/" | |
print "find the url by going to the source tab of a repository and browse to the directory you want to download" | |
exit() | |
API_PATH = "https://api.bitbucket.org/1.0/repositories" | |
null, username, repo_slug, path = urlparse(sys.argv[1]).path.split("/", 3) | |
open_directory(API_PATH, username, repo_slug, path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great, thanks so much!