Skip to content

Instantly share code, notes, and snippets.

@christophermanning
Last active November 22, 2022 22:14
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Bitbucket Download Directory

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.

#!/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)
@col000r
Copy link

col000r commented Sep 27, 2018

This is great, thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment