def __init__(self, url, user_name, password):
     self.user_name = user_name
     self.url = url
     logging.info("Connect to stash https://%s with user %s", self.url,
                  self.user_name)
     self.stash = stashy.connect('https://' + self.url, self.user_name,
                                 password)
Exemple #2
0
    def run(self):
        exp = self.reg_exp.match(self.param.message.textMessage.text)
        pr_id, project, repo = exp.group(2), exp.group(3), exp.group(4)

        cred = db.get_cred(self.param.sender_uid, 'BITBUCKET')

        try:
            stash = stashy.connect(self.url, cred['login'], cred['passwd'])
        except Exception:
            self.reply(
                'Не удалось авторизоваться в BitBucket укажи другой логин и пароль'
            )
            return

        prev_pr = stash.projects[project].repos[repo].pull_requests[pr_id].get(
        )
        intro = 'В репозитории #{}_{}_PR{} получены новые изменения Pull Request:'.format(
            repo, project, pr_id)
        while prev_pr and prev_pr.state != 'MERGED':
            pr = stash.projects[project].repos[repo].pull_requests[pr_id].get()
            if pr != prev_pr:
                diff_info = 'Текущие изменения в PR:\n{}'.format(pr.diff())
                merge_info = 'Информация о доступности слияния:\n{}'.format(
                    pr.merge_info())
                can_merged = 'Слияние можно проводить' if pr.can_merge(
                ) else 'Слияние запрещено'

                self.reply("\n".join(
                    (intro, diff_info, merge_info, can_merged)))
                prev_pr = pr

            time.sleep(5)
Exemple #3
0
def scanStash(repoObj, cxURL, baseProject, testRun):
    stash = stashy.connect(repoObj["url"], repoObj["username"],
                           repoObj["password"])
    for project in stash.projects:
        projectName = project["name"]
        pk = project_key = project["key"]

        if scanProject(projectName, repoObj["include"], repoObj["exclude"]):
            print
            print "####################################"
            print "Stash Project: " + projectName
            print "####################################"

            for repo in stash.projects[project_key].repos.list():
                for url in repo["links"]["clone"]:
                    href = url["href"]
                    if "ssh" in href:
                        print "CX Project Name: " + projectName + " " + repo[
                            "name"]
                        if testRun == False:
                            cxResult = pyC.scanProject(
                                baseProject + projectName + " " + repo["name"],
                                href, repoObj["sshkey"])
                            print "Successful: " + str(cxResult.IsSuccesfull)
                            print "Project ID: " + str(
                                cxResult.ProjectID) + ", Scan ID: " + str(
                                    cxResult.RunId)
                            print "URL: " + cxURL + "CxWebClient/projectscans.aspx?id=" + str(
                                cxResult.ProjectID)
                            print
 def __init__(self, user, passwd):
     '''
     Constructor
     '''
     self.user = user
     self.passwd = passwd
     self.stash = stashy.connect(self.url, user, passwd)
Exemple #5
0
def connect(url, username, password):
    """
    Return a connected Bitbucket session
    """

    bb_session = stashy.connect(url, username, password)

    logger.info("Connected to: %s as %s", url, username)

    return bb_session
Exemple #6
0
def connect(url, username, password):
    """
    Return a connected Bitbucket session
    """

    bb_session = stashy.connect(url, username, password)

    logger.info('Connected to: %s as %s', url, username)

    return bb_session
def clone_repo(domain, project, username, password):
    """ Clones all BitBucket repos within a Project """
    domain = 'https://{0}'.format(domain)

    bitbucket = connect(domain, username, password)
    repos = bitbucket.projects[project].repos.list()

    for repo in repos:
         for url in repo["links"]["clone"]:
              if (url["name"] == "ssh"):
                   system("git clone {0}".format(url["href"]))
def connect(url, username=None, password=None, token=None):
    """
    Return a connected Bitbucket session
    """
    if token is not None:
        bb_session = Stash(url, token=token)
        logger.info("Connected to: %s with token", url)
    else:
        bb_session = stashy.connect(url, username, password)
        logger.info("Connected to: %s as username %s", url, username)

    return bb_session
Exemple #9
0
    def setup(self):
        sensor_config = self._config.get('sensor', None)
        if not sensor_config:
            raise ValueError('"sensor" config value is required')

        # validate the format of all repository names
        self.targets = sensor_config.get('targets')
        if not self.targets:
            raise ValueError('"targets" parameter in the "sensor" is required')

        if not all(
            ['repository' in x and 'branches' in x for x in self.targets]):
            raise ValueError(
                '"repository" and "branches" are mandatory in "sensor.target"')

        if not all(
            [len(x['repository'].split('/')) == 2 for x in self.targets]):
            raise ValueError(
                'Invalid repository name is specified in the "targets" parameter'
            )

        self.TIMEOUT_SECONDS = sensor_config.get('timeout',
                                                 self.TIMEOUT_SECONDS)

        # initialize global parameter
        self.commits = {}

        self.service_type = sensor_config.get('bitbucket_type')
        if self.service_type == 'server':
            # initialization for BitBucket Server
            self.client = stashy.connect(
                sensor_config.get('bitbucket_server_url'),
                self._config.get('username'), self._config.get('password'))

            self._init_server_last_commit()
        elif self.service_type == 'cloud':
            # initialization for BitBucket Cloud
            self.client = Client(
                BasicAuthenticator(
                    self._config.get('username'),
                    self._config.get('password'),
                    self._config.get('email'),
                ))
            self._init_cloud_last_commit()
        else:
            raise ValueError('specified bitbucket type (%s) is not supported' %
                             self.service_type)
        self._increment_event_id()

        self._logger.info("It's ready to monitor events.")
Exemple #10
0
def scanStash(repoObj, cxURL, baseProject, testRun):
    stash = stashy.connect(repoObj["url"], repoObj["username"], repoObj["password"])
    for project in stash.projects:
    	projectName = project["name"]
    	pk = project_key = project["key"]

    	if scanProject(projectName, repoObj["include"], repoObj["exclude"]):

            for repo in stash.projects[project_key].repos.list():
            	for url in repo["links"]["clone"]:
                    href = url["href"]
                    if "ssh" in href:
                        #Call Checkmarx and create or update the project
						checkmarxProject(cxURL, projectName + " " + repo["name"], href, repoObj["sshkey"], testRun)
    def get_bitbucket_server_repos(self, client_repos):
        """
        Retrieves info for the BitBucket Server repos specified.

        :return a list of dictionaries with repos' info
        """
        bitbucket_server_inst = stashy.connect(self.host,
                                               self.credentials['username'],
                                               self.credentials['password'],
                                               verify=False)

        projects = set()
        project_repos = []
        filtered_repos = set()

        if client_repos == 'all':
            projects = set(bitbucket_server_inst.projects.list())
        else:
            for a in client_repos.split(','):
                spl = a.split('/')
                projects.add(spl[0])
                if len(spl) > 1:
                    filtered_repos.add(a)

        for project in projects:
            project_repos.extend(
                bitbucket_server_inst.projects[project].repos.list())

        repos = []

        for repo in project_repos:
            try:
                clone_url = (item for item in repo['links']['clone']
                             if item["name"] == "http").next()
                repo_info = {
                    'project': repo['project']['key'],
                    'slug': repo['slug'],
                    'name': repo['project']['key'] + '-' + repo['slug'],
                    'cloneUrl': clone_url['href'],
                    'browse': repo['links']['self'][0]['href']
                }

                if not filtered_repos or (repo_info['project'] + '/' +
                                          repo_info['slug']) in filtered_repos:
                    repos.append(repo_info)
            except:
                print 'An error occurred when retrieving info for repo: ' + repo[
                    'project']['key'] + '/' + repo['slug']
        return repos
Exemple #12
0
    def refresh_stash_pull_requests(self, request):
        stash = stashy.connect(settings.STASH_URL, settings.STASH_USER, settings.STASH_PASS)
        stashy_pull_requests = list(stash.projects['ANDROIDSELLERS'].repos['mobile.android.allegro'].pull_requests)
        stash_pull_requests = StashPullRequestsFactory.create_pull_requests_form_stashy(stashy_pull_requests)
        local_pull_requests = list(PullRequest.objects.filter(from_stash=True).all())
        for stash_pull_request in stash_pull_requests:
            try:
                pull_request = self._update_or_create_pullrequest(stash_pull_request)

                if pull_request in local_pull_requests:
                    local_pull_requests.remove(pull_request)
            except LordUserFound:
                pass
        for local_pull_request in local_pull_requests:
            local_pull_request.delete()
Exemple #13
0
    def run(self):
        exp = self.reg_exp.match(self.param.message.textMessage.text)
        project, repo = exp.group(2), exp.group(3)

        cred = db.get_cred(self.param.sender_uid, 'BITBUCKET')

        try:
            stash = stashy.connect(self.url, cred['login'], cred['passwd'])
        except Exception as e:
            self.reply(
                'Не удалось авторизоваться в BitBucket укажи другой   и пароль '
                + str(e))
            return

        prev_commits = []
        intro = 'В репозитории #{}_{} получены новые изменения:'.format(
            repo, project)
        while True:
            removed_commits_msg, added_commits_msg = '', ''
            commits = list(
                stash.projects[project].repos[repo].commits('master'))
            if not prev_commits or prev_commits != commits:
                removed_commits = diff(prev_commits, commits)
                if len(removed_commits) > 0:
                    removed_commits_msg = 'Удалены коммиты:\n{}'.format(
                        "\n".join([
                            "\t".join((commit['displayId'],
                                       commit['author']['name']))
                            for commit in removed_commits
                        ]))

                added_commits = diff(commits, prev_commits)
                if len(added_commits) > 0:
                    added_commits_msg = 'Добавлены коммиты:\n{}'.format(
                        "\n".join([
                            "\t".join((commit['displayId'],
                                       commit['author']['name']))
                            for commit in added_commits
                        ]))

                self.reply("\n".join(
                    (intro, removed_commits_msg, added_commits_msg)))
                prev_commits = commits

            time.sleep(5)
Exemple #14
0
	def signin(self):
		url = "https://{}/".format(config.source['host'])

		if len(config.source['apiKey']) == 0:
			pw = os.environ.get('PW', None)
			if pw is None:
				pw = getpass.getpass('Password: '******'/j_atl_security_check'), verify=True, data={
				'j_username': config.source['username'],
				'j_password': pw,
				'_atl_remember_me': 'on',
				'submit': 'Log in'
			})

			client = stashy.client.Stash(url, session=session, verify=True)
		else:
			client = stashy.connect(url, config.source['username'], config.source['apiKey'], verify=True)
			session = client._client._session

		self.stashy = client
		self.session = session
Exemple #15
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    args = setup_args(argv)

    bitbucket_pass = getpass.getpass(
        "Bitbucket/Stash password for '{user}': ".format(
            user=args.bitbucket_username))
    logging.info("connecting to bitbucket/stash...")
    stash = stashy.connect(args.bitbucket_http_base, args.bitbucket_username,
                           bitbucket_pass)

    gitmodule_mappings = []
    for line in args.gitmodule_mappings.splitlines():
        if len(line.strip()) <= 0:
            continue
        parts = line.split(' ')
        gitmodule_mappings.append((parts[0], parts[1]))

    paths = process_repos(
        stash,
        args.bitbucket_project,
        args.working_dir,
        args.gitea_ssh_base,
        args.gitea_org,
        gitmodule_mappings,
    )
    if args.push:
        push_all(
            paths,
            args.gitea_http_base,
            args.gitea_api_key,
            args.gitea_org,
        )
    else:
        logging.info("skipping push")
import sys
import os
import time
import stashy

# Main program
if __name__ == '__main__':

    USER = '******'
    PASSWORD = '******'
    STASH_URL = '<STASH_URL>'
    GIT_DIR = '<GIT_DIR>'

    l = []

    stash = stashy.connect(STASH_URL, USER, PASSWORD)
    for p in stash.projects.list():
        d = { k: p[k] for k in ['name', 'key'] }
        l.append(d)

    while True:
        for a, b in enumerate([e['name'] for e in l], 1):
            print('{} - {}'.format(a, b))

        answer = input('Please choose one Project: ')
        try:
            i = int(answer)
            if i < 1 or i > len(l):
                print('\nSorry, input must be between 1 to {}'.format(len(l)))
                time.sleep(2)
                continue
#  user = foo
#  password = bar
#
# Future functionality might be changing your branches
# to master and issuing a git pull/fetch/rebase.

import stashy
import os
from subprocess import call
from secrets import *

PROJECT = 'ETPUPD'
MODULE_PATH = '/opt/testing/modules/'
DATA_PATH = '/opt/testing/'

stash = stashy.connect("https://repo.advisory.com", user, password)

repo_data = stash.projects[PROJECT].repos.list()

modules = []

for _, repo in enumerate(repo_data):
	for _, links in enumerate(repo['links']['clone']):
		if links['name'] == 'ssh':
			modules.append({ 'name': repo['name'], 'url': links['href'] })

for _, module in enumerate(modules):
	repository_path = MODULE_PATH + module['name']
        hiera_path = DATA_PATH + module['name']
	if not os.path.exists(repository_path) and module['name'] != 'hieradata':
		call(['git', 'clone', module['url'], repository_path])
Exemple #18
0
 def __init__(self, project, repo):
     self.project = project
     self.repo = repo
     self.bb = stashy.connect(utils.BASE_BITBUCKET_URL, utils.LOGIN, utils.PASSWORD)
Exemple #19
0
#!/usr/bin/python3
import sys
import os
import stashy

# pulls all git repos from stash

stash = stashy.connect("GIT_URL", "GIT_USER", "GIT_PASS")

for repo in stash.projects[sys.argv[1]].repos.list():
    for url in repo["links"]["clone"]:
        if (url["name"] == "ssh"):
            print('pull\t' + repo["name"] + '\n')
            #cmd = "cd '/root/git/" + sys.argv[1] + "/" + repo["name"].lower() + "'; git branch --set-upstream origin/master; git pull " + url["href"] + " 2>&1"
            cmd = "cd '/root/git/" + sys.argv[1] + "/" + repo["name"].lower(
            ).replace(" ", "-") + "'; git pull 2>&1"
            #os.system("cd %s ; git pull %s" % url["href"])
            os.system(cmd)
            break
Exemple #20
0
 def __init__(self, host: str, user: str, token: str, clone_type: str, working_dir: str):
     self.bitbucket = stashy.connect(host, user, token)
     self.clone_type = clone_type
     self.working_dir = working_dir
Exemple #21
0
 def __init__(self, url, *, username, password):
     self._stash = stashy.connect(url, username=username, password=password)
     self._url = url
def main(argv=None):
    '''
    Process the command line arguments and create the JSON dump.

    :param argv: List of arguments, as if specified on the command-line.
                 If None, ``sys.argv[1:]`` is used instead.
    :type argv: list of str
    '''
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Transfer all projects/repositories from GitLab to Stash. \
                     Note: This script assumes you have your SSH key \
                     registered with both GitLab and Stash.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        conflict_handler='resolve')
    parser.add_argument('gitlab_url',
                        help='The full URL to your GitLab instance.')
    parser.add_argument('stash_url',
                        help='The full URL to your Stash instance.')
    parser.add_argument('-p', '--password',
                        help='The password to use to authenticate if token is \
                              not specified. If password and token are both \
                              unspecified, you will be prompted to enter a \
                              password.')
    parser.add_argument('-P', '--page_size',
                        help='When retrieving result from GitLab, how many \
                              results should be included in a given page?.',
                        type=int, default=20)
    parser.add_argument('-s', '--verify_ssl',
                        help='Enable SSL certificate verification',
                        action='store_true')
    parser.add_argument('-S', '--skip_existing',
                        help='Do not update existing repositories and just \
                              skip them.',
                        action='store_true')
    parser.add_argument('-t', '--token',
                        help='The private GitLab API token to use for \
                              authentication. Either this or username and \
                              password must be set.')
    parser.add_argument('-u', '--username',
                        help='The username to use for authentication, if token\
                              is unspecified.')
    parser.add_argument('-v', '--verbose',
                        help='Print more status information. For every ' +
                             'additional time this flag is specified, ' +
                             'output gets more verbose.',
                        default=0, action='count')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    args.page_size = max(100, args.page_size)

    # Convert verbose flag to actually logging level
    log_levels = [logging.WARNING, logging.INFO, logging.DEBUG]
    log_level = log_levels[min(args.verbose, 2)]
    # Make warnings from built-in warnings module get formatted more nicely
    logging.captureWarnings(True)
    logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' +
                                '%(message)s'), level=log_level)

    # Setup authenticated GitLab and Stash instances
    if args.token:
        git = GitLab(args.gitlab_url, token=args.token,
                            verify_ssl=args.verify_ssl)
    else:
        git = None
    if not args.username:
        print('Username: '******'').strip()
    if not args.password:
        args.password = getpass.getpass('Password: '******'Retrieving existing Stash projects...', end="", file=sys.stderr)
    sys.stderr.flush()
    key_set = {proj['key'] for proj in stash.projects}
    stash_project_names = {proj['name'] for proj in stash.projects}
    names_to_keys = {proj['name']: proj['key'] for proj in stash.projects}
    print('done', file=sys.stderr)
    sys.stderr.flush()
    updated_projects = set()
    repo_to_slugs = {}
    failed_to_clone = set()
    cwd = os.getcwd()
    transfer_count = 0
    skipped_count = 0
    print('Processing GitLab projects...', file=sys.stderr)
    sys.stderr.flush()
    for project in gen_all_results(git.getallprojects,
                                   per_page=args.page_size):
        print('\n' + ('=' * 80) + '\n', file=sys.stderr)
        sys.stderr.flush()
        proj_name = project['namespace']['name']
        # Create Stash project if it doesn't already exist
        if proj_name not in stash_project_names:
            # Create Stash project key
            key = proj_name
            if key.islower():
                key = key.title()
            key = re.sub(r'[^A-Z]', '', key)
            if len(key) < 2:
                key = re.sub(r'[^A-Za-z]', '', proj_name)[0:2].upper()
            added = False
            suffix = 65
            while key in key_set:
                if not added:
                    key += 'A'
                else:
                    suffix += 1
                    key = key[:-1] + chr(suffix)
            key_set.add(key)

            # Actually add the project to Stash
            print('Creating Stash project "%s" with key %s...' %
                  (proj_name, key), end="", file=sys.stderr)
            sys.stderr.flush()
            stash.projects.create(key, proj_name)
            names_to_keys[proj_name] = key
            stash_project_names.add(proj_name)
            print('done', file=sys.stderr)
            sys.stderr.flush()
        else:
            key = names_to_keys[proj_name]

        stash_project = stash.projects[key]

        # Initialize maping from repository names to slugs for later
        if key not in repo_to_slugs:
            repo_to_slugs[key] = {repo['name']: repo['slug'] for repo in
                                  stash_project.repos}

        # Create Stash-compatible name for repository
        # Repository names are limited to 128 characters.
        # They must start with a letter or number and may contain spaces,
        # hyphens, underscores and periods
        repo_name = project['name']
        if not repo_name[0].isalnum():
            repo_name = 'A ' + repo_name
        repo_name = re.sub(r'[^A-Za-z0-9 _.-]', ' ', repo_name)
        if len(repo_name) > 128:
            repo_name = repo_name[0:128]

        # Add repository to Stash project if it's not already there
        if repo_name not in repo_to_slugs[key]:
            print('Creating Stash repository "%s" in project "%s"...' %
                  (repo_name, proj_name), end="", file=sys.stderr)
            sys.stderr.flush()
            stash_repo = stash_project.repos.create(repo_name)
            repo_to_slugs[key][repo_name] = stash_repo['slug']
            print('done', file=sys.stderr)
            sys.stderr.flush()
        elif args.skip_existing:
            print('Skipping existing Stash repository "%s" in project "%s"' %
                  (repo_name, proj_name), file=sys.stderr)
            sys.stderr.flush()
            skipped_count += 1
            continue
        else:
            print('Updating existing Stash repository "%s" in project "%s"' %
                  (repo_name, proj_name), file=sys.stderr)
            sys.stderr.flush()
            repo_slug = repo_to_slugs[key][repo_name]
            stash_repo = stash_project.repos[repo_slug].get()

        for clone_link in stash_repo['links']['clone']:
            if clone_link['name'] == 'ssh':
                stash_repo_url = clone_link['href']
                break

        with tempfile.TemporaryDirectory() as temp_dir:
            # Clone repository to temporary directory
            print('\nCloning GitLab repository...', file=sys.stderr)
            sys.stderr.flush()
            try:
                subprocess.check_call(['git', 'clone', '--mirror',
                                       project['ssh_url_to_repo'],
                                       temp_dir])
            except subprocess.CalledProcessError:
                print('Failed to clone GitLab repository. This usually when ' +
                      'it does not exist.', file=sys.stderr)
                failed_to_clone.add(project['name_with_namespace'])
                skipped_count += 1
                continue
            os.chdir(temp_dir)

            # Check that repository is not empty
            try:
                subprocess.check_call(['git', 'log', '--format=oneline', '-1'],
                                      stdout=subprocess.DEVNULL,
                                      stderr=subprocess.DEVNULL)
            except subprocess.CalledProcessError:
                print('Repository is empty, so skipping push to Stash.',
                      file=sys.stderr)
                skipped_count += 1
            else:
                # Change remote to Stash and push
                print('\nPushing repository to Stash...', file=sys.stderr)
                sys.stderr.flush()
                subprocess.check_call(['git', 'remote', 'set-url', 'origin',
                                       stash_repo_url])
                subprocess.check_call(['git', 'push', '--mirror'])
                transfer_count += 1

            os.chdir(cwd)

        updated_projects.add(proj_name)


    print('\n' + ('=' * 35) + 'SUMMARY' + ('=' * 35), file=sys.stderr)
    print('{} repositories transferred.\n'.format(transfer_count),
          file=sys.stderr)
    print('{} repositories skipped.\n'.format(skipped_count),
          file=sys.stderr)
    print('Projects created/updated:', file=sys.stderr)
    for proj in sorted(updated_projects):
        print('\t' + proj, file=sys.stderr)
    print('Repositories that we could not clone:', file=sys.stderr)
    for repo_name in sorted(failed_to_clone):
        print('\t' + repo_name, file=sys.stderr)
Exemple #23
0
#!/usr/bin/python
import sys
import os
import stashy
from pathlib import Path

stash = stashy.connect("https://stash.ruter.no/", "kh1334",
                       "XXXXXXXXXXXXXXXXXXXXXXXX")

repos = {'RDPIN', 'RDPMON', 'RDPMQS', 'RDPSIR', 'RDP', 'TAAS'}

root_dir = "/Users/runestorlopa/src/ruter/"

for repo_to_clone in repos:
    if os.path.exists(root_dir + repo_to_clone):
        os.chdir(root_dir + repo_to_clone)
        os.system(
            "eval 'find . -type d -depth 1 -exec git --git-dir={}/.git --work-tree=$PWD/{} pull origin master --prune \\;'"
        )
    else:
        Path(root_dir + repo_to_clone).mkdir()

    for repo in stash.projects[repo_to_clone].repos.list():
        for url in repo["links"]["clone"]:
            if url["name"] == "http":
                print(url)
                git_command = "git clone " + url["href"]
                os.chdir(root_dir + repo_to_clone)
                print(git_command)
                os.system(git_command)
                break
Exemple #24
0
def connect_to_bitbucket(server_url):
    username = getpass.getuser()
    password = getpass.getpass('%s Password: ' % (server_url))
    return stashy.connect(server_url, username, password)
Exemple #25
0
import stashy
import sys
import getpass
import subprocess

# pip install stashy before running this

user = sys.argv[1]
project = sys.argv[2]

stash = stashy.connect("https://stash.url", user, getpass.getpass())
repo_list = stash.projects[project].repos.list()
for repo in repo_list:
  # this bit probably won't work, need project to be lowercase
  bashCommand='git clone ssh://[email protected]:7999/$project/' + repo['name'] + '.git'
  print bashCommand
  subprocess.call(bashCommand, shell=True)
# Added ACTION_FLAG bit so the same logic can run fetch --all on every repository and/or clone.

import sys
import os
import stashy

ACTION_FLAG = 1     # Bit: +1=Clone, +2=fetch --all

url  = os.environ["STASH_URL"]  # "https://mystash.com/stash"
user = os.environ["STASH_USER"] # joedoe"
pwd  = os.environ["STASH_PWD"]  # Yay123
part_to_change  = os.environ["STASH_URL_PART_TO_CHANGE"]  # mystash.com
part_to_replace_with  = os.environ["STASH_URL_PART_TO_REPLACE_WITH"]  # mynewstash.com


stash = stashy.connect(url, user, pwd)

def mkdir(xdir):
    if not os.path.exists(xdir):
        os.makedirs(xdir)

def run_cmd(cmd):
    print ("Directory cwd: %s "%(os.getcwd() ))
    print ("Running Command: \n    %s " %(cmd))
    os.system(cmd)

start_dir = os.getcwd()

for project in stash.projects:
    pk = project_key = project["key"]
    mkdir(pk)
Exemple #27
0
#!/usr/bin/env python3
import sys
import json
import stashy

source = json.loads(sys.stdin.read())["source"]
sys.stderr.write(str(source))
stash = stashy.connect(source["url"], source["username"], source["password"])

branches = []
for details in stash.projects[source["project"]].repos[
        source["repo"]].branches():
    branch = details["id"].split("/")[-1]
    branches.append(branch)

sys.stdout.write(json.dumps([{"version": str(branches)}]))
except ImportError:
    import simplejson as json

if "STASH_ENDPOINT" in env:
    pass
else:
    print "Must export STASH_{ENDPOINT,USERNAME,PASSWORD} envvars!"
    exit(1)

STASH_ENDPOINT = env['STASH_ENDPOINT']
STASH_USERNAME = env['STASH_USERNAME']
STASH_PASSWORD = env['STASH_PASSWORD']
HOMEDIR = env['HOME']


stash = stashy.connect(STASH_ENDPOINT, STASH_USERNAME, STASH_PASSWORD)

projects = stash.projects.list()

def main():
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    for p in projects:
        repos = stash.projects[p["key"]].repos.list()
        for r in repos:
            project = r["project"]["key"]
            slug = r["slug"]
            cloneurlUpper= r["links"]["clone"]
            urlvalues = [i['href'] for i in cloneurlUpper if 'href' in i]
            urllistvalues = [i for i, s in enumerate(urlvalues) if 'ssh' in s]
            urlindex = urllistvalues[0]
Exemple #29
0
def get_repository_from_stash():
    stash = stashy.connect(config.stash, config.login, config.password)
    repository = stash.projects['BUDG'].repos['web_bb']
    return repository
Exemple #30
0
    def run(self):
        exp = self.reg_exp.match(self.param.message.textMessage.text)
        project, repo = exp.group(2), exp.group(3)

        cred = db.get_cred(self.param.sender_uid, 'BITBUCKET')

        prev_prs = []
        intro = 'В репозитории #{}_{} получены новые изменения Pull Request:'.format(
            repo, project)
        while True:
            try:
                stash = stashy.connect(self.url, cred['login'], cred['passwd'])
            except Exception:
                self.reply(
                    'Не удалось авторизоваться в BitBucket укажи другой логин и пароль'
                )
                return

            declined_prs_msg, opened_prs_msg, merged_prs_msg = '', '', ''
            prs = list(
                set(stash.projects[project].repos[repo].pull_requests.all())
                | set(stash.projects[project].repos[repo].pull_requests.all(
                    state='MERGED'))
                | set(stash.projects[project].repos[repo].pull_requests.all(
                    state='DECLINED')))
            if not prev_prs or prev_prs != prs:
                diff_prs = diff(prs, prev_prs)

                opened_prs = list(
                    filter(lambda x: x['state'] in 'OPEN', diff_prs))
                if len(opened_prs) > 0:
                    opened_prs_msg = "\n".join([
                        "Пользователь {} открыл PR #{} \"{}\" {}->{}".format(
                            pr['author']['user']['displayName'], pr['id'],
                            pr['title'], pr['fromRef']['displayId'],
                            pr['toRef']['displayId']) for pr in opened_prs
                    ])

                merged_prs = list(
                    filter(lambda x: x['state'] in 'MERGED', diff_prs))
                if len(merged_prs) > 0:
                    merged_prs_msg = "\n".join([
                        "Пользователь {} выполнил merge PR #{} \"{}\" {}->{}".
                        format(pr['author']['user']['displayName'], pr['id'],
                               pr['title'], pr['fromRef']['displayId'],
                               pr['toRef']['displayId']) for pr in merged_prs
                    ])

                declined_prs = list(
                    filter(lambda x: x['state'] in 'DECLINED', diff_prs))
                if len(declined_prs) > 0:
                    declined_prs_msg = "\n".join([
                        "Пользователь {} отклонил PR #{} \"{}\" {}->{}".format(
                            pr['author']['user']['displayName'], pr['id'],
                            pr['title'], pr['fromRef']['displayId'],
                            pr['toRef']['displayId']) for pr in declined_prs
                    ])

                self.reply("\n".join(
                    (intro, opened_prs_msg, merged_prs_msg, declined_prs_msg)))
                prev_prs = prs

            time.sleep(5)
def connect_to_stash():
    account = find_credentials.get_username()
    password = find_credentials.get_password()
    base_url = alfred_config.read_config('base_url')
    return stashy.connect("{0}/stash".format(base_url), account, password)
Exemple #32
0
def to_bitbucket(username, password, project_name, project_key):
    bitbucket = stashy.connect("http://localhost:7990/", username, password)
    bitbucket.projects.create(project_key, project_name)
import os
import click
import stashy
from datetime import datetime, timedelta

stash = stashy.connect(os.environ['BB_HOST'], os.environ['BB_USER'], os.environ['BB_PASSWORD'])

users_for_cleanup = []

for user in stash.admin.users.list():
    if user['directoryName'] == 'Delegated LDAP Authentication':
        try:
            last_login = datetime.fromtimestamp(user['lastAuthenticationTimestamp']/1000)
            time_diff = datetime.now() - last_login
            if time_diff > timedelta(days=365):
                users_for_cleanup.append(user)
        except:
                users_for_cleanup.append(user)


for old_user in users_for_cleanup:
    if click.confirm(f"Delete {old_user['name']}?",default=True):
        stash.admin.users.delete(old_user['name'])
Exemple #34
0
 def __init__(self, user, password, url="https://scm.scytl.net/stash/"):
     self.stash_server = stashy.connect(url, user, password)
Exemple #35
0
def stash_init(base,user,pwrd):
	#Turn these three variables into raw input entered by user
	stash = stashy.connect(base, user, pwrd)

	return stash
Exemple #36
0
#!/usr/bin/python

# This script will clone all of the repos in the "PROJECT" Stash project into the current directory.

#
# To install dependency `pip install stashy`
# If you see an error about egg_info, try running `pip install --upgrade setuptools`
# The script will still work even if you see a huge warning about SSL being misconfigured.
#

import sys
import os
import getpass
import stashy

#https://docs.python.org/2/library/getpass.html

usr = getpass.getuser() #Return the “login name” of the user.
pwd = getpass.getpass("Enter Stash password for %s: " % user)

stash = stashy.connect("http://stash.example.com", user, pwd)

for repo in stash.projects["PROJECT"].repos.list():
    if "Deprecated" in repo["name"] or "Abandoned" in repo["name"]:
        continue
    for url in repo["links"]["clone"]:
        if (url["name"] == "ssh"):
            os.system("git clone %s" % url["href"])
            break
print "\nIn the following stash:"
print "\t" + args.stashurl + " (" + args.stashuser + ")"

print "\nIn the following directory:"
print "\t" + args.clone_directory
cont = raw_input("\nContinue? [Y/n]")

if cont and "y" != cont[0].lower():
	exit(0)

print "\n\n"
repositories_cloned = SortedSet([])
repositories_already_cloned = SortedSet([])
pswd = getpass.getpass('Stash Password:')
stash = stashy.connect(args.stashurl, args.stashuser, pswd)
for project in stash.projects.list():
	if projects and project["name"].lower() not in projects:
		continue

	first_repo = True
	print "Searching stash project[" + project["name"] + "]"
	for repo in stash.projects[project["key"]].repos.list():
		name = repo["name"].lower()
		if None == repositories or name in repositories:
			if first_repo:
				print ""
				first_repo = False

			print "Found repository[" + name + "]"
			repositories.remove(name)
Exemple #38
0
import stashy, pprint
from pync import Notifier
from collections import defaultdict
from time import time, sleep
from config import *
if blink:
	from subprocess import call

d = defaultdict(int)
last_updated = int(time()) * 1000

stash = stashy.connect(url, username, password).projects['WT']
Notifier.notify('Now checking for merged pull requests.')
while True:
	try:
		print 'checking: ' + str(last_updated)
		for repo in repos_to_check:
			pull_requests = list(stash.repos[repo].pull_requests.all(state='MERGED', order="NEWEST"))
			if pull_requests:
				pr = pull_requests[0]
				merged_time = pr['updatedDate']
				d[repo] = merged_time
				if merged_time > last_updated:
					Notifier.notify('New pull request merged', title=repo, open=url+'/projects/WT/repos/'+repo+'/pull-requests/'+str(pr['id'])+'/overview')
					if blink:
						call('./blink1-tool --blue', shell=True)
				else:
					print repo + ": no new pull requests merged"
			else:
				print repo + ": no pull requests at all"
		sleep(5)