from mercurial import hg, ui, commands import shutil import os import urllib, urllib2 import json class bitbucket: def __init__(self, user='', password='', url=False): if url == False: url = 'bitbucket.org' self.uri = url self.user = user self.password = password self.ui = ui.ui() self.ui.setconfig('ui', 'quiet', True) def clone(self, name, destination): try: shutil.rmtree(destination) except: pass try: commands.clone(self.ui, self._convertrepo(name), destination) except urllib2.HTTPError: raise ValueError("Repository not found: %s" % name) def _convertrepo(self, name): if os.path.isdir(name): return name try: (user, repo) = name.split('/') except ValueError: user = self.user repo = name if self.password: uri = 'https://%s:%s@%s/%s/%s' % (self.user, self.password, self.uri, user, repo) else: # ssh mode. Auth by key uri = 'ssh://hg@{uri}/{user}/{repo}'.format(uri=self.uri, user=user, repo=repo) return str(uri) def load(self, repo): self.repo = hg.repository(self.ui, self._convertrepo(repo)) def update(self, revision='tip'): commands.update(self.ui, self.repo, revision) def updateToTag(self, tag): tags = self.tags() if tag in tags: self.update(revision=tag) else: raise ValueError ("Tag %s is not valid. Valid tags are: %s" % (tag, ", ".join(tags))) def updateToVersion(self, tag): tags = self.versions() if tag in tags: self.update(revision=tag) else: raise ValueError ("Version {0} is not valid. Valid vesrions are: {1}".format(tag, ", ".join(tags))) def tags(self): return self.repo.tags() def versions(self): return [x for x in self.tags() if x != 'tip'] def list(self): data = urllib.urlopen('https://{0}:{1}@api.bitbucket.org/1.0/user/repositories'.format(self.user, self.password)) repos = {} for repo in json.load(data): path = "/".join([repo['owner'], repo['slug']]) # get tags available tagData = urllib.urlopen('https://{0}:{1}@api.bitbucket.org/1.0/repositories/{3}/{2}/tags'.format(self.user, self.password, repo['slug'], repo['owner'])) tags = json.load(tagData) repo['tags'] = [tag for tag in tags] repos[path] = repo return repos