def __init__(self, tmp_dir, git_provider_url, organisation, repository_name, username, password, git_user, git_email): super().__init__(tmp_dir, username, password, git_user, git_email) self._git_provider_url = git_provider_url self._organisation = organisation self._repository_name = repository_name self._bitbucket = Bitbucket(self._git_provider_url, self._username, self._password)
def __init__(self, url, username, password, verifyssl): self.verifyssl = verifyssl self.bitbucketInstance = Bitbucket(url=url, username=username, password=password, verify_ssl=self.verifyssl)
def __init__(self, url: str, user: str, password: str): """ C'tor of Server. :param str url: URL of the BitBucket server :param str user: Login username :param str password: Login password or token """ self.server_url = url self.user = user self.password = password self.api = Bitbucket(self.server_url, self.user, self.password)
def __init__( self, git_provider_url: str, username: Optional[str], password: Optional[str], organisation: str, repository_name: str, ) -> None: self.__bitbucket = Bitbucket(git_provider_url, username, password) self.__git_provider_url = git_provider_url self.__organisation = organisation self.__repository_name = repository_name
def enumerate_bitbucket_projects(section): xfilter = section.get("filter", "*") query = section.get("query") url = section.get("bitbucket_url") username = section.get("username") token = section.get("access_token") try: result = [] bb = Bitbucket(url=url, username=username, password=token) result = bb.repo_list(project_key=query) return [repo for repo in result if fnmatch(repo["slug"], xfilter)] except HTTPError as e: print(f"HTTPError => {e}") except Exception as e: print(f"bitbucket repo_list {query} error {type(e)} => {e}") return []
def _get_bitbucket_server_client(self) -> "atlassian.Bitbucket": try: from atlassian import Bitbucket except ImportError as exc: raise ImportError( "Unable to import atlassian, please ensure you have installed the bitbucket extra" ) from exc if self.access_token_secret is not None: # If access token secret specified, load it access_token = Secret(self.access_token_secret).get() else: # Otherwise, fallback to loading from local secret or environment variable access_token = prefect.context.get("secrets", {}).get( "BITBUCKET_ACCESS_TOKEN" ) if access_token is None: access_token = os.getenv("BITBUCKET_ACCESS_TOKEN") host = "https://bitbucket.org" if self.host is None else self.host session = requests.Session() if access_token is None: session.headers["Authorization"] = "Bearer " else: session.headers["Authorization"] = "Bearer " + access_token return Bitbucket(host, session=session)
class BitBucket: def __init__(self, url, username, password): self.bitbucket = AtlassianBitBucketLib( url=url, username=username, password=password, ) async def create_pull_request( self, source_project: str, source_repo: str, dest_project: str, dest_repo: str, branch_name: str, main_branch_name: str, commit_title: str, commit_message: str, ) -> str: pull_request = self.bitbucket.open_pull_request( source_project, source_repo, dest_project, dest_repo, branch_name, main_branch_name, commit_title, commit_message, ) pull_request_url = pull_request["links"]["self"][0]["href"] return pull_request_url
def connectBitBucket(self, args): bitbucket_url = "https://bitbucket.microchip.com/" try: gitAccess = Bitbucket( url=bitbucket_url, username=args.bitbucket_user_id, password=args.bitbucket_personal_access_token) gitAccess.get_users() return gitAccess except Exception as e: if (args.debug_mode): print("[Debug] " + str(e)) raise Exception( "[!] Invlaid bitbucket login information or do not have permission to access this repo" )
def get_raw_pull_request_data(self): """ :brief get_raw_pull_request_data: A function to return all pull requests user has reviewed from server :return: A list of raw pull-request data values. """ bitbucket = Bitbucket(url=self._url, username=self._user, password=self._password, verify_ssl=False) params = { 'role' : 'REVIEWER', 'limit' : '150', } print("****************************** Beginning to Read Pull Request Data ******************************") data = bitbucket.get(PR_DASHBOARD_PATH, params=params) pr_data_list = [] if 'values' in data: pr_data_list = (data or {}).get('values') # Check if last page or the oldest pr entry is saved somewhere before reading another page while not data.get('isLastPage') and not self._is_pr_cached(pr_data_list[-1]): start = data.get('nextPageStart') params['start'] = start data = bitbucket.get(PR_DASHBOARD_PATH, params=params) pr_data_list += (data or {}).get('values') print("******************************* Ending to Read Pull Request Data *********************************") return pr_data_list
def get_bitbucket_client(credentials: dict = None, host: str = None, **kwargs: Any) -> "Bitbucket": """ Utility function for loading Bitbucket client objects from a given set of credentials. Args: - credentials (dict, optional): a dictionary of AWS credentials used to initialize the Client; if not provided, will attempt to load the Client using ambient environment settings - host (str, optional): the host string for bitbucket server users. If not provided, defaults to https://bitbucket.org - **kwargs (Any, optional): additional keyword arguments to pass to the Bitbucket Client Bitbucket accepts: "cloud", "api_version", "api_root" Returns: - Client: an initialized and authenticated Bitbucket Client """ if not Bitbucket: raise ImportError( "Unable to import Bitbucket, please ensure you have installed the bitbucket extra" ) if credentials: access_token = credentials["BITBUCKET_ACCESS_TOKEN"] else: access_token = prefect.context.get("secrets", {}).get("BITBUCKET_ACCESS_TOKEN", None) if not access_token: access_token = os.getenv("BITBUCKET_ACCESS_TOKEN", None) if not host: host = "https://bitbucket.org" session = requests.Session() if access_token is None: session.headers["Authorization"] = "Bearer " else: session.headers["Authorization"] = "Bearer " + access_token return Bitbucket(host, session=session, **kwargs)
# coding: utf8 from atlassian import Bitbucket def html(project): html_data = """<tr> <td>{project_key}</td> <td>{project_name}</td> <td><ul>""".format(**project) for user in project['project_administrators']: html_data += '\n\t<li><a href="mailto:{email}">{name}</a></li>'.format(**user) return html_data + '</ul></td></tr>\n' bitbucket = Bitbucket( url='http://localhost:7990', username='******', password='******') data = bitbucket.project('DEMO') print(html(data))
import OMPython import os from github import Github from atlassian import Bitbucket import json import pygit2 import glob import re import shutil import requests import zipfile import common bitbucket = Bitbucket(url="https://api.bitbucket.org") def removerepo(ghurl, repopath): print("Removing repository " + ghurl) shutil.rmtree(repopath) tagregex = re.compile('^refs/tags') def alltags(gitrepo): return list((remove_prefix(e, "refs/tags/"), str(gitrepo.lookup_reference_dwim(e).target)) for e in filter(lambda r: tagregex.match(r), gitrepo.listall_references()))
# coding=utf-8 from atlassian import Bitbucket bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') #Get all tasks for a pull-request by pull_request_id data = bitbucket.get_tasks("project_name", "repository_name", "pull_request_id") print(data) #Get information about task by task_id data = bitbucket.get_task("task_id") print(data) #Add task to the comment by comment_ID in pull-request data = bitbucket.add_task("comment_ID", "task_text") print(data) #Update task by task_ID with new state (OPEN, RESOLVED) or/and text. data = bitbucket.update_task("task_ID", text="text", state="OPEN") print(data) #Delete task by task_ID. RESOLVED tasks can't be deleted data = bitbucket.delete_task("task_ID") print(data)
from atlassian import Bitbucket bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') changelog = bitbucket.get_changelog(project='DEMO', repository='example-repository', ref_from='develop', ref_to='master') print(changelog)
# coding=utf-8 from pprint import pprint from atlassian import Bitbucket bitbucket = Bitbucket(url="http://localhost:7990", username="******", password="******") pprint(bitbucket.project_list())
# coding=utf-8 from atlassian import Bitbucket bitbucket = Bitbucket(url="http://localhost:7990", username="******", password="******") changelog = bitbucket.get_changelog(project="DEMO", repository="example-repository", ref_from="develop", ref_to="master") print(changelog)
# coding: utf8 import logging from atlassian import Bitbucket logging.basicConfig(level=logging.DEBUG, format='[%(asctime).19s] [%(levelname)s] %(message)s') logging.getLogger('requests').setLevel(logging.WARNING) log = logging.getLogger('bitbucket-projects-administrators') bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') html = '<table><tr><th>Project Key</th><th>Project Name</th><th>Administrator</th></tr>' for data in bitbucket.all_project_administrators(): html += '<tr><td>{project_key}</td><td>{project_name}</td><td><ul>'.format( **data) for user in data['project_administrators']: html += '<li><a href="mailto:{email}">{name}</a></li>'.format(**user) html += '</ul></td></tr>' html += '</table><p></p><p></p>' print(html)
from atlassian import Bitbucket """This example shows how to create, get and delete tags""" bitbucket = Bitbucket( url='http://localhost:7990', username='******', password='******') if __name__ == '__main__': response = bitbucket.set_tag(project='gonchik.tsymzhitov', repository='gonchik', tag_name='test1', commit_revision='ebcf5fdffa0', description='Stable release') print("Response after set_tag method") print(response) response = bitbucket.get_project_tags(project='INT', repository='jira-plugins', tag_name='test1') print("Retrieve tag") print(response) print("Remove tag") bitbucket.delete_tag(project='INT', repository='jira-plugins', tag_name='test1')
# coding: utf8 from atlassian import Bitbucket bitbucket = Bitbucket( url='http://localhost:7990', username='******', password='******') data = bitbucket.fork_repository( project='DEMO', repository='example-repository', new_repository='forked-repository') print(data)
# coding: utf8 import os import requests import pytest import sys from atlassian import Bitbucket BITBUCKET = None try: from .mockup import mockup_server BITBUCKET = Bitbucket("{}/bitbucket/cloud".format(mockup_server()), username="******", password="******", cloud=True) except ImportError: pass class TestBasic: @pytest.mark.skipif(sys.version_info < (3, 4), reason="requires python3.4") def test_get_repositories(self): result = [ x["name"] for x in BITBUCKET.get_repositories("TestWorkspace1") ] assert result == ["testrepository1", "testrepository2" ], "Result of [get_repositories(...)]" @pytest.mark.skipif(sys.version_info < (3, 4), reason="requires python3.4") def test_get_pipelines(self):
# coding=utf-8 from atlassian import Bitbucket from pprint import pprint bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') pprint(bitbucket.project_list())
def test_init_bitbucket(self): Bitbucket(url=STASH_URL, username=ATLASSIAN_USER, password=ATLASSIAN_PASSWORD)
# coding=utf-8 from atlassian import Bitbucket def html(project): html_data = '<table>\n' html_data += '\t<tr><th>ITEM</th><th>VALUE</th></tr>\n' html_data += '\t<tr><td>key</td><td>{key}</td></tr>\n'.format(**project) html_data += '\t<tr><td>name</td><td>{name}</td></tr>\n'.format(**project) html_data += '\t<tr><td>description</td><td>{description}</td></tr>\n'.format( **project) html_data += '\t<tr><td>id</td><td>{id}</td></tr>\n'.format(**project) return html_data + '</table>\n' bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') data = bitbucket.project('DEMO') print(html(data))
# coding: utf8 from atlassian import Bitbucket bitbucket = Bitbucket( url='http://localhost:7990', username='******', password='******') changelog = bitbucket.get_changelog( project='DEMO', repository='example-repository', ref_from='develop', ref_to='master') print(changelog)
# coding=utf-8 from atlassian import Bitbucket bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') data = bitbucket.get_users(user_filter="username") print(data)
# coding: utf8 import logging from atlassian import Bitbucket logging.basicConfig(level=logging.DEBUG, format='[%(asctime).19s] [%(levelname)s] %(message)s') logging.getLogger('requests').setLevel(logging.WARNING) log = logging.getLogger('bitbucket-projects-administrators') bitbucket = Bitbucket( url='http://localhost:7990', username='******', password='******') html = '<table><tr><th>Project Key</th><th>Project Name</th><th>Administrator</th></tr>' for data in bitbucket.all_project_administrators(): html += '<tr><td>{project_key}</td><td>{project_name}</td><td><ul>'.format(**data) for user in data['project_administrators']: html += '<li><a href="mailto:{email}">{name}</a></li>'.format(**user) html += '</ul></td></tr>' html += '</table><p></p><p></p>' print(html)
# coding=utf-8 from atlassian import Bitbucket bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') pr_id = 12345 pr = bitbucket.get_pullrequest("project_name", "repository_name", pr_id) ver = pr.json().get("version") print("PR version: {}".format(ver)) response = bitbucket.decline_pull_request("project_name", "repository_name", pr_id, ver) print("Declined: {}".format(response)) ver = response.json().get("version") print("PR version: {}".format(ver)) response = bitbucket.reopen_pull_request("project_name", "repository_name", pr_id, ver) print("Reopen: {}".format(response)) ver = response.json().get("version") print("PR version: {}".format(ver)) response = bitbucket.is_pull_request_can_be_merged("project_name", "repository_name", pr_id) print("Reopen: {}".format(response)) print("PR version: {}".format(ver)) response = bitbucket.merge_pull_request("project_name", "repository_name", pr_id, ver)
import logging from datetime import datetime from atlassian import Bitbucket """ That example shows how to make a report of bitbucket usage """ stash = Bitbucket( url="https://stash.example.com", username="******", password="******", timeout=60, ) def report(limit=200, include_in_active=False): response = stash.get_users_info(stash, limit=limit) users = [] if response: users = response.get("values") or [] print("|Status|Display name| Email |Last Auth DateTime|") for user in users: auth_date = user.get("lastAuthenticationTimestamp") or None if auth_date: auth_date = int(auth_date / 1000) full_date = datetime.utcfromtimestamp(auth_date).strftime("%Y-%m-%d %H:%M:%S") else: full_date = None if include_in_active or user.get("active"):
# coding=utf-8 from atlassian import Bitbucket bitbucket = Bitbucket(url="http://localhost:7990", username="******", password="******") data = bitbucket.fork_repository( project_key="DEMO", repository_slug="example-repository", new_repository_slug="forked-repository", ) print(data)
def main(): args = create_parser().parse_args() threads = int(args.threads) EXEC = threadly.Scheduler(threads) server_domain = args.server_url if args.server_url[:8] == "https://": server_domain = args.server_url[8:] elif args.server_url[:7] == "http://": server_domain = args.server_url[7:] if os.environ.get('BBMIGRATE_IN_DOCKER') == "true": open("{}/.gitconfig".format(str(Path.home())), "w").write("[credential]\n helper = store\n") open("{}/.git-credentials".format(str(Path.home())), "w").write("https://{}:{}@{}\nhttps://{}:{}@{}\n".format( args.server_user, urllib.parse.quote(args.server_pass), server_domain, args.cloud_user, urllib.parse.quote(args.cloud_pass), "bitbucket.org")) # setting up directory for repo clones dir_name = os.path.abspath(args.repo_path) clone_dir = dir_name try: if not os.path.isdir(clone_dir): os.mkdir(clone_dir) except OSError: logger.exception(f'Failed to create directory {clone_dir}') sys.exit(1) logger.info("Saving repos to path:{}".format(clone_dir)) # initializing Bitbucket Server instance try: bitbucket_server = Bitbucket(url=args.server_url, username=args.server_user, password=args.server_pass) except Error: logger.exception( f'Unable to instantiate Bitbucker Server connection! One or more parameters may be missing or malformed.' ) sys.exit(1) try: projects_gen = bitbucket_server.project_list() except Error: logger.exception( f'Failed to retrieve data from Bitbucket Server {args.server_url}') sys.exit(1) projects = [] logger.info( f'Retrieving projects and repos from Bitbucket Server {args.server_url}' ) for p in projects_gen: new_project_key = p['key'].replace("-", "") project_dir = os.path.join(clone_dir, new_project_key) p['project_dir'] = project_dir p['new_project_key'] = new_project_key projects.append(p) try: repos = bitbucket_server.repo_list(project_key=p['key']) except Error: logger.exception( "Failed to gather repository list from Bitbucket Server project {}" .format(p['name'])) sys.exit(1) logger.info( "Retrieving repositories from Bitbucket Server project {}".format( p['name'])) p['repos'] = [] for r in repos: new_repo_name = new_project_key.lower() + "." + r['slug'].lower() repo_dir = os.path.join(project_dir, r['slug']) new_repo_git = "https://bitbucket.org/" + args.workspace + "/" + new_repo_name + ".git" old_repo_git = "" for href in r['links']['clone']: if href['href'][:8] == "https://": old_repo_git = href['href'] break r['old_repo_git'] = old_repo_git r['new_repo_git'] = new_repo_git r['new_repo_name'] = new_repo_name r['repo_dir'] = repo_dir p['repos'].append(r) p['repos'] = sorted(p['repos'], key=lambda k: k['slug']) projects = sorted(projects, key=lambda k: k['key']) processing = [] logger.info("Duplicating projects on BBCloud") for p in projects: proj = p f = EXEC.schedule_with_future(bbcloud.duplicate_project, args=(args.cloud_user, args.cloud_pass, args.workspace, proj)) processing.append(f) for lf in processing: lf.get() processing = [] logger.info("Duplicating repos and cloning them on BBCloud") for project in projects: project_name = project['name'] project_dir = project['project_dir'] try: os.mkdir(project_dir) except: pass for repo in project['repos']: p = project r = repo f = EXEC.schedule_with_future( git.backupRepo, args=(args.cloud_user, args.cloud_pass, args.workspace, p, r, clone_dir, args.no_remove_repos)) processing.append(f) if len(processing) > 10: for lf in processing: lf.get() processing = [] for lf in processing: lf.get() # When it's all over, remove the tmp dir to keep things tidy if not args.no_remove_repos: try: os_system_string = "rm -rf " + clone_dir os.system(os_system_string) except OSError: logger.exception(f'Failed to remove temp directory {clone_dir}') sys.exit(1)
from jira import JIRA from atlassian import Bitbucket jiraOptions = {"server": "http://localhost/jira"} jiraBasicAuth = ('admin', '1234') try: jira = JIRA(options=jiraOptions, basic_auth=jiraBasicAuth) bbucket = Bitbucket(url='http://localhost/bitbucket', username='******', password=1234) # BR anahtarina sahip statusu To Do olan issuelari ceker issues = jira.search_issues(jql_str="project = BR AND status = 'To Do'") # BR anahtarina sahip bir proje Bitbucket da varsa bu kismi yapar if not bbucket.project(key="BR").get("errors"): # Her issue icin Bitbucketda repo olusturup Jirada da bu issueya ait statusu Done yapar for issue in issues: bbucket.create_repo(project_key="BR", repository=issue.fields.customfield_10001) jira.transition_issue(issue=issue, transition="DONE") # BR anahtarina sahip bir proje Bitbucketda yoksa bu kismi yapar else: # To Do statusuna ait tüm issuelar icin yapar for issue in issues: # BR anahtarina sahip bir sonraki issue icin Bitbucketda aynı projeyi tekrar oluşturmamak adina bu kontrolu yapar # BR anahtarina sahip bir proje Bitbucketda yoksa bu kısmı yapar if bbucket.project(key="BR").get("errors"): bbucket.create_project(key="BR", name=issue.fields.customfield_10000) bbucket.create_repo(project_key="BR", repository=issue.fields.customfield_10001)
# coding=utf-8 from atlassian import Bitbucket def html(project): html_data = "<table>\n" html_data += "\t<tr><th>ITEM</th><th>VALUE</th></tr>\n" html_data += "\t<tr><td>key</td><td>{key}</td></tr>\n".format(**project) html_data += "\t<tr><td>name</td><td>{name}</td></tr>\n".format(**project) html_data += "\t<tr><td>description</td><td>{description}</td></tr>\n".format( **project ) html_data += "\t<tr><td>id</td><td>{id}</td></tr>\n".format(**project) return html_data + "</table>\n" bitbucket = Bitbucket(url="http://localhost:7990", username="******", password="******") data = bitbucket.project("DEMO") print(html(data))
def __init__(self, url, username, password): self.bitbucket = AtlassianBitBucketLib( url=url, username=username, password=password, )
from atlassian import Bitbucket bitbucket = Bitbucket(url='http://localhost:7990', username='******', password='******') def project_key(): prj = input("Enter the project key \n") return prj.upper() def repo_id(): return input("Enter the repository id \n")
# coding=utf-8 from atlassian import Bitbucket """This example shows how to create, get and delete tags""" bitbucket = Bitbucket(url="http://localhost:7990", username="******", password="******") if __name__ == "__main__": response = bitbucket.set_tag( project="gonchik.tsymzhitov", repository="gonchik", tag_name="test1", commit_revision="ebcf5fdffa0", description="Stable release", ) print("Response after set_tag method") print(response) response = bitbucket.get_project_tags(project="INT", repository="jira-plugins", tag_name="test1") print("Retrieve tag") print(response) print("Remove tag") bitbucket.delete_tag(project="INT", repository="jira-plugins", tag_name="test1")