def setUp(self): """Creating a new authenticated Bitbucket...""" if USERNAME and PASSWORD: self.bb = Bitbucket(USERNAME, PASSWORD) elif USERNAME and CONSUMER_KEY and CONSUMER_SECRET: global OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET self.bb = Bitbucket(USERNAME) # First time we need to open up a browser to enter the verifier if not OAUTH_ACCESS_TOKEN and not OAUTH_ACCESS_TOKEN_SECRET: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/') # open a webbrowser and get the token import webbrowser webbrowser.open(self.bb.url('AUTHENTICATE', token=self.bb.access_token)) # Copy the verifier field from the URL in the browser into the console oauth_verifier = raw_input('Enter verifier from url [oauth_verifier]') self.bb.verify(oauth_verifier) OAUTH_ACCESS_TOKEN = self.bb.access_token OAUTH_ACCESS_TOKEN_SECRET = self.bb.access_token_secret else: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/', OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug']
def setUp(self): """Creating a new authenticated Bitbucket...""" if USERNAME and PASSWORD: self.bb = Bitbucket(USERNAME, PASSWORD) elif USERNAME and CONSUMER_KEY and CONSUMER_SECRET: # Try Oauth authentication global OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET self.bb = Bitbucket(USERNAME) # First time we need to open up a browser to enter the verifier if not OAUTH_ACCESS_TOKEN and not OAUTH_ACCESS_TOKEN_SECRET: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/') # open a webbrowser and get the token webbrowser.open(self.bb.url('AUTHENTICATE', token=self.bb.access_token)) # Copy the verifier field from the URL in the browser into the console token_is_valid = False while not token_is_valid: # Ensure a valid oauth_verifier before starting tests oauth_verifier = raw_input('Enter verifier from url [oauth_verifier]') token_is_valid = bool(oauth_verifier and self.bb.verify(oauth_verifier)[0]) if not token_is_valid: print('Invalid oauth_verifier, please try again or quit with CONTROL-C.') OAUTH_ACCESS_TOKEN = self.bb.access_token OAUTH_ACCESS_TOKEN_SECRET = self.bb.access_token_secret else: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/', OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug']
def _get_client(self, repo=None): if repo: bb = Bitbucket(username=self.config['username'], password=self.config['password'], repo_name_or_slug=repo) else: bb = Bitbucket(username=self.config['email'], password=self.config['password']) return bb
def ApiDeleteIssue(request): if request.method == 'POST': issueId = str(request.data["id"]) bb = Bitbucket(bbUser, bbPass, repo_name_or_slug="supportal2016test") success, result = bb.issue.delete(issue_id=issueId) return Response({"message": "Issue Deleted"})
def setUp(self): """Creating a new authenticated Bitbucket...""" try: # Try and get OAuth credentials first, if that fails try basic auth from settings import USERNAME, CONSUMER_KEY, CONSUMER_SECRET PASSWORD = None except ImportError: try: # TODO : check validity of credentials ? from settings import USERNAME, PASSWORD CONSUMER_KEY = None CONSUMER_SECRET = None except ImportError: # Private tests require username and password of an existing user. raise ImportError('Please provide either USERNAME and PASSWORD or USERNAME, CONSUMER_KEY and CONSUMER_SECRET in bitbucket/tests/private/settings.py.') if USERNAME and PASSWORD: self.bb = Bitbucket(USERNAME, PASSWORD) elif USERNAME and CONSUMER_KEY and CONSUMER_SECRET: # Try Oauth authentication global OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET self.bb = Bitbucket(USERNAME) # First time we need to open up a browser to enter the verifier if not OAUTH_ACCESS_TOKEN and not OAUTH_ACCESS_TOKEN_SECRET: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/') # open a webbrowser and get the token webbrowser.open(self.bb.url('AUTHENTICATE', token=self.bb.access_token)) # Copy the verifier field from the URL in the browser into the console token_is_valid = False while not token_is_valid: # Ensure a valid oauth_verifier before starting tests oauth_verifier = raw_input('Enter verifier from url [oauth_verifier]') token_is_valid = bool(oauth_verifier and self.bb.verify(oauth_verifier)[0]) if not token_is_valid: print('Invalid oauth_verifier, please try again or quit with CONTROL-C.') OAUTH_ACCESS_TOKEN = self.bb.access_token OAUTH_ACCESS_TOKEN_SECRET = self.bb.access_token_secret else: self.bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/', OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug']
def setUp(self): """Creating a new authenticated Bitbucket...""" self.bb = Bitbucket(USERNAME, PASSWORD) # Create a repository. success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True) # Save repository's id assert success self.bb.repo_slug = result[u'slug']
def createIssue(request): if request.method == "POST": getUser = request.user form = IssueForm(request.POST) if form.is_valid(): priority = "minor" issue = Issue(**form.cleaned_data) title = form.cleaned_data['title'] kind = form.cleaned_data['kind'] content = form.cleaned_data['description'] if issue.highPriority: current_time = datetime.datetime.now().time() users = OnCallRotation.objects.all() priority = "major" assigned = "unassigned" for user in users: if user.oncall_clockin <= current_time <= user.oncall_clockout: assigned = str(user.username) elif user.oncall_clockin > user.oncall_clockout: end = datetime.time(hour=23, minute=59, second=59, microsecond=999999) if user.oncall_clockin <= current_time <= end: assigned = str(user.username) slack_payload = { "text": str(getUser) + " just created a high priority issue:\n" + "*" + title + "*" + "\n" + ">" + content + "\nAssigned to: @" + assigned } r = requests.post(slack_url, json=slack_payload) bb = Bitbucket(bbUser, bbPass, repo_name_or_slug="supportal2016test") success, result = bb.issue.create(title=u'' + title, content=u'' + content, priority=u'' + priority, status=u'new', kind=u'' + kind) else: form = IssueForm() if request.user.is_superuser: context = { "form": form, } else: context = {"form": form, "hours_avail": 8} return render(request, "issue_form.html", context)
def __init__(self, board_name, backlog_list_name, lists_names=[]): self.board_name = board_name self.backlog_name = backlog_list_name self.lists_names = lists_names + [backlog_list_name] self.repos = [] self._trello = TrelloClient(conf.TRELLO_API_KEY, conf.TRELLO_TOKEN) self._bitbucket = Bitbucket(conf.BITBUCKET_USER, conf.BITBUCKET_PASSWORD)
def main(): global ARGS, bb, dest ARGS = parse_args() bb = Bitbucket(ARGS.username, ARGS.password) status, repos = bb.repository.all() for r in repos: print("Found repo: %s, cloning ... " % r['name']) clone(r['name'])
def authenticate_user(username, password): """ Authenticate the user with bitbucket api Keyword arguments: username -- username/email address used for authentication password -- password used for authentication """ client = Bitbucket(username, password) return client
def get_bitbucket(): from django.conf import settings as django_settings from deployment.fabfile import get_config username = get_config("bitbucket", "username") client_key = get_config("bitbucket", "client_key") client_secret = get_config("bitbucket", "client_secret") token = get_config("bitbucket", "access_token") token_secret = get_config("bitbucket", "access_token_secret") if not all([username, client_key, client_secret, token, token_secret]): return None bb = Bitbucket(username) bb.authorize( client_key, client_secret, 'http://localhost/', token, token_secret ) return bb
def __init__(self, username): """Initialise the BitBucketProvider using the Bitbucket module. The Bitbucket username is initialised to username. Keyword arguments: username -- The Bitbucket username. """ super().__init__(username) self.bitbucket = Bitbucket() self.username = username
def create_repo(username, reponame, scm="git", private=True): password = get_internet_password(username, "bitbucket.org") bb = Bitbucket(username, password) response = bb.repository.create(reponame, scm=scm, private=private) if response[0]: # True or False rsp = response[1] repoUrl = "https://bitbucket.org/{username}/{reponame}".format( username=username, reponame=reponame) return repoUrl, rsp else: print("Something went wrong!", file=sys.stderr) sys.exit(1)
def process_args(self, shelf, args): # pip install --user bitbucket-api from bitbucket.bitbucket import Bitbucket # this only works for the logged-in user. It would be great if... # yeah. username = args[0] assert shelf.options.login is not None, \ '--login must be supplied when accessing the Bitbucket API' password = getpass.getpass('Password: '******'bb:%s/%s' % (username, repo['slug']) return []
def handle_post(self, data): """Handle post """ if data['private']: return if len(data['tags']) == 0 or 'point' not in data['tags']: return tagset = set(data['tags']) if tagset & FR_TAGS: issue_type = 'enhancement' elif tagset & BUG_TAGS: issue_type = 'bug' else: return if cache_get('issue-post:%s' % data['post_id']): return text = template('report.md', **data) args = { 'kind': issue_type, 'title': data['text'][:100], 'content': text, } bb = Bitbucket(settings.api_login, settings.api_password, settings.api_slug) issue = Issue(bb) status, resp = issue.create(**args) try: env.user = User('login', 'support') except UserNotFound: return reply = template('reply.txt', issue=resp['local_id']) try: add_comment(data['post_id'], None, text=reply, dont_subscribe=True, force=True) except (PostError, CommentError), e: log.error(e) return
def ApiCreateIssue(request): if request.method == 'POST': title = str(request.data["title"]) content = str(request.data["description"]) kind = str(request.data["kind"]) priority = str(request.data["priority"]) print(title) print(content) print(kind) bb = Bitbucket(bbUser, bbPass, repo_name_or_slug="supportal2016test") success, result = bb.issue.create(title=u'' + title, content=u'' + content, priority=u'' + priority, status=u'new', kind=u'' + kind) if priority == "major": current_time = datetime.datetime.now().time() users = OnCallRotation.objects.all() priority = "major" assigned = "unassigned" for user in users: if user.oncall_clockin <= current_time <= user.oncall_clockout: assigned = str(user.username) elif user.oncall_clockin > user.oncall_clockout: end = datetime.time(hour=23, minute=59, second=59, microsecond=999999) if user.oncall_clockin <= current_time <= end: assigned = str(user.username) slack_payload = { "text": str(getUser) + " just created a high priority issue:\n" + "*" + title + "*" + "\n" + ">" + content + "\nAssigned to: @" + assigned } r = requests.post(slack_url, json=slack_payload) return Response({"message": "OK"})
from bitbucket.bitbucket import Bitbucket bb = Bitbucket(username='******', password='', repo_name_or_slug='village-timetable-parser') bb.authorize("f7XTPKEw475LnbrvJ7", "GaFcjNsedMbKnPE4Ye3X6svGR7XfcUbV","http://localhost") import webbrowser webbrowser.open(bb.url('AUTHENTICATE', token=bb.access_token)) oauth_verifier = raw_input('Enter verifier from url [oauth_verifier] i.e 7889090090') r = bb.verify(oauth_verifier) (res,keys) = bb.ssh.all() len(keys) #keys[0]['label'] #keys[0]['pk'] #bb.ssh.delete(84026) (res,keys) = bb.ssh.all() keys
def viewIssues(request): #lists for issue titles and content bucket_id = [] bucket_titles = [] bucket_content = [] bucket_kind = [] bucket_priority = [] #call api to get initial repository and find number of issues in said repository r = requests.get(bucket_url) bucket_json = r.json() issue_count = bucket_json['count'] if request.method == "POST": form = deleteForm(request.POST) if form.is_valid(): bb = Bitbucket(bbUser, bbPass, repo_name_or_slug="supportal2016test") success, result = bb.issue.delete( issue_id=form.cleaned_data['id_to_be_deleted']) else: form = deleteForm() x = 1 #issue counter y = x #id counter while x <= issue_count: #get each individual issue by id r2 = requests.get( 'https://api.bitbucket.org/1.0/repositories/shawdl/supportal2016test/issues/' + str(y)) if r2.text == "Not Found": #y is necessary because x = count only counts the number of issues, meaning that it will not reach an id of 7 #with a count of 3. Thus, y helps us reach the other ids y += 1 else: bucket_issues = r2.json() print(r2.status_code) print(r2.text) #store converted issue titles and content in the appropriate lists, only if the issues have a status of open if bucket_issues['status'] != "closed": bucket_id.append(bucket_issues['local_id']) bucket_titles.append(bucket_issues['title']) bucket_content.append(bucket_issues['content']) bucket_kind.append(bucket_issues['metadata']['kind']) bucket_priority.append(bucket_issues['priority']) #Move to next issue x += 1 y += 1 zipped_data = zip(bucket_id, bucket_titles, bucket_content, bucket_kind, bucket_priority) #pass the lists to the template if request.user.is_superuser: context = { "zipped_data": zipped_data, "title": "View Issues", "bucket_url": bucket_url, "form": form } else: context = { "zipped_data": zipped_data, "title": "View Issues", "bucket_url": bucket_url } return render(request, "view_issues.html", context)
def setUp(self): """Creating a new annonymous Bitbucket...""" self.bb = Bitbucket()
## Get list of all your github private repos. ## By default we filter out public repos and repos where you are not the owner. You can change this. g = Github(GH_USERNAME, GH_PASSWORD) theRepos = [] for repo in g.get_user().get_repos(): if not repo.private: continue if repo.owner.name != g.get_user().name: continue theRepos.append((repo.name, repo.clone_url)) ### CLOWN ALL THE THIGNS for theName, theCloneURL in theRepos: print theName subprocess.check_call(['git', 'clone', theCloneURL, theName]) ### Go through all the cloned directories, create a bitbucket repo and then push them ### If the repo already exists on github this will skip it. bb = Bitbucket(BB_USERNAME, BB_PASSWORD, 'private_slug') for name in glob.iglob('*'): print name result, r = bb.repository.create(name, scm='git', private=True) if not result: print 'Could not create repo, skipping' continue push_url = '[email protected]:{owner}/{name}.git'.format(owner = r['owner'], name = r['name']) os.chdir(name) subprocess.check_call(['git', 'remote', 'set-url', 'origin', push_url]) subprocess.check_call(['git', 'push']) os.chdir(d)
import os from github import Github from bitbucket.bitbucket import Bitbucket from subprocess import call gh = Github(os.environ['GITHUB_USER'], os.environ['GITHUB_PASS']) bb = Bitbucket(os.environ['BITBUCKET_USER'], os.environ['BITBUCKET_PASS']) os.mkdir('repos') os.chdir('repos') for repo in gh.get_user().get_repos(): # only worry about our own if repo.owner.login == os.environ['GITHUB_USER']: # only worry about private repos if repo.private: print "grabbing %s/%s" % (repo.owner.login, repo.name) call(["git", "clone", "--mirror", repo.ssh_url]) os.chdir(repo.name + ".git") success, result = bb.repository.create(repo.name, scm='git', private=True) if not success: raise Exception(result) call([ 'git', 'remote', 'set-url', 'origin', '[email protected]:%s/%s.git' % (os.environ['BITBUCKET_USER'], repo.name) ]) print "uploading %s/%s" % (os.environ['BITBUCKET_USER'], repo.name) call(["git", "push", "--mirror", "origin"]) os.chdir('..')
def __init__(self, username, password): """ Setup client for Bitbucket API """ self.__username = username self.__bb = Bitbucket(username, password)
from bitbucket.bitbucket import Bitbucket USERNAME = raw_input('what is ur USERNAME') PASSWORD = raw_input('what is urPASSWORD') cred = Bitbucket(USERNAME,PASSWORD) x = raw_input('What is your reponame?') success,result=cred.repository.create(x)
def authorize_bitbucket(settings): """ Handles the authorization of Jumpstart's Bitbucket account to allow access to its repository. It needs to be authorized since the system will push the project to its repository. .. seealso:: :py:func:`create_new_repository()` :param settings: Contains the necessary keys that will be used for Bitbucket authorization :returns: an *authorized* :py:class:`Bitbucket` object Raises: :py:class:`ProjectSetupError` :: bitbucket = Bitbucket(bitbucket_username) where ``bitbucket_username`` refers the Jumpstart's Bitbucket username. .. note:: :py:class:`Bitbucket` is from Python's `Bitbucket API library <https://pypi.python.org/pypi/bitbucket-api>`_. """ # [Paul] Notes on Bitbucket API: # Bitbucket.authorize() always returns True if all parameters are provided (even if incorrect! -- see code in link below) # Actual verification of oauth credentials only done upon sending of GET request in the following Repository class methods: # Repository.all() # Repository.get()* # Repository.create() # Repository.update() # Repository.delete() # Repository.archive() # *Hence, we create a blank TEST_REPOSITORY to verify if our succeeding actions can push through via the Bitbucket API # (better than calling Repository.all()) # Reference source code: # Bitbucket class - https://bitbucket-api.readthedocs.org/en/latest/_modules/bitbucket/bitbucket.html # Repository class - https://bitbucket-api.readthedocs.org/en/latest/_modules/bitbucket/repository.html TEST_REPOSITORY_SLUG = settings.test_repository_slug bitbucket_username = settings.repository_username bitbucket_consumer_key = settings.repository_consumer_key bitbucket_consumer_secret = settings.repository_consumer_secret bitbucket_oauth_access_token = settings.repository_oauth_access_token bitbucket_oauth_access_token_secret = settings.repository_oauth_access_token_secret # Bitbucket OAuth Authentication bitbucket = Bitbucket(bitbucket_username) if not bitbucket_oauth_access_token and not bitbucket_oauth_access_token_secret: bitbucket.authorize(bitbucket_consumer_key, bitbucket_consumer_secret, 'http://127.0.0.1:8000/') # Open a webbrowser and get the token webbrowser.open(bitbucket.url('AUTHENTICATE', token=bitbucket.access_token)) # Copy the verifier field from the URL in the browser into the console oauth_verifier = raw_input('Enter verifier from url [oauth_verifier]') success, result = bitbucket.verify(oauth_verifier) if not success: LOGGER.warning("OAuth verification with Bitbucket repository failed. Could not proceed. Please check the Consumer Key and Consumer Secret provided in the Settings page. (bitbucket: %s, bitbucket username: %s)" % (error_message, bitbucket, bitbucket_username)) raise ProjectSetupError("%s" % error_message) settings.repository_oauth_access_token = bitbucket.access_token settings.repository_oauth_access_token_secret = bitbucket.access_token_secret settings.save() else: bitbucket.authorize(bitbucket_consumer_key, bitbucket_consumer_secret, 'http://127.0.0.1:8000/', bitbucket_oauth_access_token, bitbucket_oauth_access_token_secret) # Test repository accessibility via Bitbucket API #test_repository_slug = settings.test_repository_slug ---> still to be added in Settings model success, test_repository = bitbucket.repository.get(TEST_REPOSITORY_SLUG) if not success: # failed to establish connection to the repository. cannot proceed. prompt for retry. LOGGER.warning("Authentication with Bitbucket repository failed. Could not proceed. (bitbucket: %s, bitbucket username: %s)" % (error_message, bitbucket, bitbucket_username)) raise ProjectSetupError("%s" % error_message) return bitbucket
def __init__(self, username, password): self._logger = logging.getLogger(__name__) self._bb = Bitbucket(username=username, password=password)
# Taken from this original code .. # https://bitbucket-api.readthedocs.org/en/latest/usage.html#private >>> import webbrowser >>> from bitbucket.bitbucket import Bitbucket >>> bb = Bitbucket(USERNAME) >>> # First time we need to open up a browser to enter the verifier >>> if not OAUTH_ACCESS_TOKEN and not OAUTH_ACCESS_TOKEN_SECRET: >>> bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/') >>> # open a webbrowser and get the token >>> webbrowser.open(bb.url('AUTHENTICATE', token=bb.access_token)) >>> # Copy the verifier field from the URL in the browser into the console >>> oauth_verifier = raw_input('Enter verifier from url [oauth_verifier]') >>> OAUTH_ACCESS_TOKEN = bb.access_token >>> OAUTH_ACCESS_TOKEN_SECRET = bb.access_token_secret >>> else: >>> bb.authorize(CONSUMER_KEY, CONSUMER_SECRET, 'http://localhost/', OAUTH_ACCESS_TOKEN, OAUTH_ACCESS_TOKEN_SECRET) from bitbucket.bitbucket import Bitbucket bb = Bitbucket(username='******', password='', repo_name_or_slug='village-timetable-parser') bb.authorize("f7XTPKEw475LnbrvJ7", "GaFcjNsedMbKnPE4Ye3X6svGR7XfcUbV","http://localhost") import webbrowser webbrowser.open(bb.url('AUTHENTICATE', token=bb.access_token)) oauth_verifier = raw_input('Enter verifier from url [oauth_verifier] i.e 7889090090') r = bb.verify(oauth_verifier)
import requests import subprocess import shutil import json from sh import git from bitbucket.bitbucket import Bitbucket ''' Version: 0.0.2 System level Requirements: sh, requests, bitbucket-api, django Next: Add Jira and bitbucket project setup ''' bb_username = raw_input("bitbucket username:"******"bitbucket password:"******"{0}/assets".format(script_path) save_path = os.path.join(os.path.expanduser("~"), "Desktop") project_name = raw_input("Project Name:") print("*" * edging) project_path = "{0}/{1}".format(save_path, project_name) ios_path = "{0}/ios/".format(project_path) cms_path = "{0}/cms".format(project_path) design_path = "{0}/designs".format(project_path)
def __init__(self, username): self.bb = Bitbucket() self.username = username