def post_output_to_pr(self, organization_uri, project, repo_id,
                          pull_request_id, access_token, comment_content):
        if comment_content == '':
            print(
                f"{vso_task_skipped if self.enable_vso_output else ''}No Cloud Custodian output found in output dir"
            )
            sys.exit()

        # Create a connection to the org
        token = {'access_token': access_token}
        credentials = BasicTokenAuthentication(token)
        connection = VssConnection(base_url=organization_uri,
                                   creds=credentials)

        # Get a git client
        git_client = connection.get_client(
            "vsts.git.v4_1.git_client.GitClient")

        new_comment = Comment(content=comment_content)
        comments = [new_comment]
        comment_thread = GitPullRequestCommentThread(comments=comments)

        try:
            # Create a comment based on the cloud custodian output
            resp = git_client.create_thread(comment_thread, repo_id,
                                            pull_request_id, project)
            print(
                f"{vso_task_succeeded if self.enable_vso_output else ''}Successfully updated the pull request {pull_request_id}, the comment thread id is: {resp.id}"
            )
        except Exception as e:
            print(
                f"{vso_task_skipped if self.enable_vso_output else ''}Unable to post comment to PR: {pull_request_id}, {e}"
            )
            sys.exit(1)
Пример #2
0
    def __init__(self,
                 creds,
                 organization_name="",
                 project_name="",
                 repository_name="",
                 pool_name=""):
        # Create the relevant name attributes
        self._organization_name = organization_name
        self._project_name = project_name
        self._creds = creds
        self._repository_name = repository_name
        self._pool_name = pool_name

        # Create the relevant clients that are needed by the managers
        self._connection = VssConnection(base_url='https://dev.azure.com/' +
                                         organization_name,
                                         creds=creds)
        self._agent_client = self._connection.get_client(
            "vsts.task_agent.v4_1.task_agent_client.TaskAgentClient")
        self._build_client = self._connection.get_client(
            'vsts.build.v4_1.build_client.BuildClient')
        self._core_client = self._connection.get_client(
            'vsts.core.v4_0.core_client.CoreClient')
        self._extension_management_client = self._connection.get_client('vsts.extension_management.v4_1.extension_management_client.ExtensionManagementClient')  # pylint: disable=line-too-long
        self._git_client = self._connection.get_client(
            "vsts.git.v4_1.git_client.GitClient")
        self._release_client = self._connection.get_client(
            'vsts.release.v4_1.release_client.ReleaseClient')
        self._service_endpoint_client = self._connection.get_client(
            'vsts.service_endpoint.v4_1.service_endpoint_client.ServiceEndpointClient'
        )
    def satisfy(namespace):
        print("%s: Checking vsts ref deleted condition." %
              namespace.metadata.name)

        if (namespace.metadata.annotations is None
                or vsts_base_url_key not in namespace.metadata.annotations
                or vsts_repository_id_key not in namespace.metadata.annotations
                or ref_key not in namespace.metadata.annotations):
            print("Can't find vsts info in %s" % namespace.metadata.name)
            return False

        # vsts_base_url -- a vsts base url like: https://your-acount.visualstudio.com/DefaultCollection
        vsts_base_url = namespace.metadata.annotations[vsts_base_url_key]
        vsts_repository_id = namespace.metadata.annotations[
            vsts_repository_id_key]
        ref_name = namespace.metadata.annotations[ref_key]

        connection = VssConnection(base_url=vsts_base_url, creds=credentials)
        client = connection.get_client('vsts.git.v4_0.git_client.GitClient')
        all_refs = [ref.name for ref in client.get_refs(vsts_repository_id)]
        result = ref_name not in all_refs

        print("%s: Result of vsts ref deleted condition: %s" %
              (namespace.metadata.name, result))
        return result
def main(url, area, resource, auth_token, output_path=None):

    context = SimpleNamespace()
    context.runner_cache = SimpleNamespace()

    # setup the connection
    context.connection = VssConnection(
        base_url=url,
        creds=BasicAuthentication('PAT', auth_token),
        user_agent='azure-devops-python-samples/' + __VERSION__)

    # if the user asked for logging:
    # - add a hook for logging the http request
    # - create the root directory
    if output_path:
        # monkey-patch the get_client method to attach our hook
        _get_client = context.connection.get_client

        def get_client_with_hook(*args, **kwargs):
            logger.debug("get_client_with_hook")
            client = _get_client(*args, **kwargs)
            hacks.add_request_hook(client)
            return client

        context.connection.get_client = get_client_with_hook

        root_log_dir = pathlib.Path(output_path)
        if not root_log_dir.exists():
            root_log_dir.mkdir(parents=True, exist_ok=True)
        http_logging.push_state(True)
    else:
        root_log_dir = None

    # runner_lib.discovered_samples will contain a key for each area loaded,
    # and each key will have the resources and sample functions discovered
    if area == 'all':
        areas = runner_lib.discovered_samples.keys()
    else:
        if area not in runner_lib.discovered_samples.keys():
            raise ValueError("area '%s' doesn't exist" % (area, ))
        areas = [area]

    for area in areas:

        area_logging_path = runner_lib.enter_area(area, root_log_dir)

        for area_resource, functions in runner_lib.discovered_samples[
                area].items():
            if area_resource != resource and resource != 'all':
                logger.debug("skipping resource %s", area_resource)
                continue

            resource_logging_path = runner_lib.enter_resource(
                area_resource, area_logging_path)

            for run_sample in functions:
                runner_lib.before_run_sample(run_sample.__name__,
                                             resource_logging_path)
                run_sample(context)
                runner_lib.after_run_sample(resource_logging_path)
Пример #5
0
def create_tfs_connection(url, token):
    """
    Creates the TFS Connection Context
    """
    if token is None:
        token = os.environ.get('TFS_API_TOKEN', None)

    tfs_credentials = BasicAuthentication('', token)
    tfs_connection = VssConnection(base_url=url, creds=tfs_credentials)
    return tfs_connection
    def satisfy(self, namespace):
        print("%s: Checking deleted branch condition." % namespace.metadata.name)
        
        if (
            namespace.metadata.annotations is None 
            or self.vsts_base_url_key not in namespace.metadata.annotations
            or self.vsts_repository_id_key not in namespace.metadata.annotations
            or self.branch_key not in namespace.metadata.annotations
        ):
            print("Can't find vsts info in %s" % namespace.metadata.name)
            return False

        # vsts_base_url -- a vsts base url like: https://your-acount.visualstudio.com/DefaultCollection
        vsts_base_url = namespace.metadata.annotations[self.vsts_base_url_key]
        vsts_repository_id = namespace.metadata.annotations[self.vsts_repository_id_key]
        branch_name = namespace.metadata.annotations[self.branch_key]

        connection = VssConnection(base_url=vsts_base_url, creds=self.credentials)
        client = connection.get_client('vsts.git.v4_0.git_client.GitClient')
        all_branches = [branch.name for branch in client.get_branches(vsts_repository_id)]
        return branch_name not in all_branches
Пример #7
0
class BaseManager(object):
    """The basic manager which the other classes are build on

    Attributes:
        organization_name : The name of the DevOps organization
        project_name : The name of the DevOps project
        creds : These are credentials for an Azure user
    """
    def __init__(self,
                 creds,
                 organization_name="",
                 project_name="",
                 repository_name="",
                 pool_name=""):
        # Create the relevant name attributes
        self._organization_name = organization_name
        self._project_name = project_name
        self._creds = creds
        self._repository_name = repository_name
        self._pool_name = pool_name

        # Create the relevant clients that are needed by the managers
        self._connection = VssConnection(base_url='https://dev.azure.com/' +
                                         organization_name,
                                         creds=creds)
        self._agent_client = self._connection.get_client(
            "vsts.task_agent.v4_1.task_agent_client.TaskAgentClient")
        self._build_client = self._connection.get_client(
            'vsts.build.v4_1.build_client.BuildClient')
        self._core_client = self._connection.get_client(
            'vsts.core.v4_0.core_client.CoreClient')
        self._extension_management_client = self._connection.get_client('vsts.extension_management.v4_1.extension_management_client.ExtensionManagementClient')  # pylint: disable=line-too-long
        self._git_client = self._connection.get_client(
            "vsts.git.v4_1.git_client.GitClient")
        self._release_client = self._connection.get_client(
            'vsts.release.v4_1.release_client.ReleaseClient')
        self._service_endpoint_client = self._connection.get_client(
            'vsts.service_endpoint.v4_1.service_endpoint_client.ServiceEndpointClient'
        )

    def _get_project_by_name(self, project_name):
        """Helper function to get the project object from its name"""
        projects = self._core_client.get_projects()
        return next(
            (project for project in projects if project.name == project_name),
            None)

    def _get_repository_by_name(self, project, repository_name):
        """Helper function to get the repository object from its name"""
        repositories = self._git_client.get_repositories(project.id)
        return next((repository for repository in repositories
                     if repository.name == repository_name), None)

    def _get_definition_by_name(self, project, definition_name):
        """Helper function to get definition object from its name"""
        definitions = self._build_client.get_definitions(project.id)
        return next((definition for definition in definitions
                     if definition.name == definition_name), None)

    def _get_build_by_name(self, project, name):
        """Helper function to get build object from its name"""
        builds_unsorted = self._build_client.get_builds(project=project.id)
        builds = sorted(builds_unsorted,
                        key=lambda x: x.start_time,
                        reverse=True)
        return next(
            (build for build in builds if build.definition.name == name), None)

    def _get_github_repository_by_name(self, project, name):
        """Helper function to get a github repository object from its name"""
        service_endpoints = self._service_endpoint_client.get_service_endpoints(
            project.id)
        github_endpoint = next(
            (endpoint
             for endpoint in service_endpoints if endpoint.type == "github"),
            None)
        repositories = self._build_client.list_repositories(
            project.id, 'github', github_endpoint.id)
        repository_match = next((repository
                                 for repository in repositories.repositories
                                 if repository.full_name == name), None)
        return repository_match
Пример #8
0
# https://docs.microsoft.com/en-us/vsts/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts

# https://github.com/Microsoft/vsts-python-api
# https://github.com/Microsoft/vsts-python-samples

# qqccxbr43abamk3zykmcvufwx2je7zfllhfs6cgt7q75bj6ma6fa

if __name__ == "__main__":
    #response = requests.post('https://msasg.visualstudio.com/Cortana/_apis/git/repositories/CoreScience/commitsbatch?api-version=4.1',  data = {}, headers={'Authorization': 'qqccxbr43abamk3zykmcvufwx2je7zfllhfs6cgt7q75bj6ma6fa'})
    #print (response)

    team_instance = 'https://msasg.visualstudio.com/'
    credentials = BasicAuthentication(
        '', 'qqccxbr43abamk3zykmcvufwx2je7zfllhfs6cgt7q75bj6ma6fa')
    connection = VssConnection(base_url=team_instance, creds=credentials)
    core_client = connection.get_client(
        'vsts.core.v4_0.core_client.CoreClient')

    git_client = connection.get_client("vsts.git.v4_1.git_client.GitClient")

    # https://docs.microsoft.com/en-us/rest/api/vsts/git/commits/get%20commits%20batch?view=vsts-rest-4.1#gitquerycommitscriteria
    search_criteria = GitQueryCommitsCriteria()
    # git_client
    # def get_commits_batch(self, search_criteria, repository_id, project=None, skip=None, top=None, include_statuses=None):
    # https://github.com/Microsoft/vsts-python-api/blob/40d4f5803a3f0552e628b8ac3e7f7c99d1953f01/vsts/vsts/git/v4_1/models/git_query_commits_criteria.py
    result = git_client.get_commits_batch(project='Cortana',
                                          search_criteria=search_criteria,
                                          repository_id='CoreScience')

    print(len(result))
Пример #9
0
 def get_connection(self):
     credentials = self.get_credentials()
     return VssConnection(self.collection_uri, credentials)
def _get_vss_connection(organization, credentials):
    return VssConnection(get_base_url(organization),
                         creds=credentials,
                         user_agent='devOpsCli/{}'.format(VERSION))
Пример #11
0
def _get_vss_connection(team_instance, credentials):
    return VssConnection(get_base_url(team_instance),
                         creds=credentials,
                         user_agent='vstscli/{}'.format(VERSION))
Пример #12
0
    return dict1


'''
VSTS connection setup
'''
vstsuser = raw_input("VSTS user name (asos email...):")
token = getpass.getpass("VSTS access token:")
jirauser = raw_input("jira user name:")
jirapwd = getpass.getpass("Jira password:"******"%Y%m%d")
Пример #13
0
from msrest.authentication import BasicAuthentication
from gpiozero import Button

import config as cfg
import lightcontroller as light

#global variables
keepAlive = True
currentStatus = 'none'
currentResult = 'none'
triggerButton = Button(18)
"""set up a connection to VSTS.
Relies on the parameters set in config.py
"""
credentials = BasicAuthentication('', cfg.vstspat)
connection = VssConnection(base_url=cfg.vstsurl, creds=credentials)
client = connection.get_client('vsts.build.v4_0.build_client.BuildClient')
""" Determines what LED to switch on based on the status and result parameters provided
Actual switching of LED's is delegated to the lightcontroller.
"""


def setStatusLights(status, result):
    if status == 'completed':
        if result == 'succeeded':
            pprint.pprint("Green light lit!")
            light.setGreenOn()
        elif result == 'failed' or result == 'canceled':
            pprint.pprint("Red light lit!")
            light.setRedOn()
    elif status == 'inProgress':
Пример #14
0
##from vsts.release.v4_1.release_client import ReleaseClient
from vsts.work_item_tracking.v4_1.work_item_tracking_client import WorkItemTrackingClient
from msrest.authentication import BasicAuthentication
from vsts.vss_client import VssClient
import sys
import config
import pprint
from flask import Flask

# Fill in with your personal access token and org URL
organization_url = config.organization  #input("Enter Organization URL ex: https://dev.azure.com/OrgName: ")  #'https://dev.azure.com/mgendevops'
personal_access_token = config.PAT  #input("Enter Personal Access Token: ") #'sxidglzmnx6rxwjhjpgicfdw5zctxq5kp2stkcauxswdlwsv2beq'

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = VssConnection(base_url=organization_url, creds=credentials)

# Get a client (the "core" client provides access to projects, teams, etc)
core_client = connection.get_client('vsts.core.v4_1.core_client.CoreClient')

while (True):
    try:

        print("Enter Choice: \n")

        choice = input("1. Projects\n2. Processes\n3. Builds\n4. WorkItems\n")

        if (choice == '1'):
            # Get the list of projects in the org
            projects = core_client.get_projects()
            for project in projects:
Пример #15
0
    print(f"{sys.argv[0]} <release tag>")
    sys.exit(1)

tag_name = sys.argv[1].strip()
result = subprocess.run(["git", "rev-list", "-n", "1", sys.argv[1]],
                        stdout=subprocess.PIPE)
if result.returncode != 0:
    sys.exit(1)
tag_commit_hash = result.stdout.decode('utf-8')

personal_access_token = azurepipelines_api_key
organization_url = 'https://dev.azure.com/electrumsv'

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = VssConnection(base_url=organization_url, creds=credentials)

build_client = connection.get_client(
    'vsts.build.v4_1.build_client.BuildClient')

project_name = "ElectrumSV"

builds = build_client.get_builds(project=project_name,
                                 top=1,
                                 result_filter="succeeded",
                                 query_order="finishTimeDescending",
                                 branch_name="refs/heads/master",
                                 repository_id="electrumsv/electrumsv",
                                 repository_type="GitHub")
for build in builds:
    if build.source_version == tag_commit_hash:
Пример #16
0
                                        "conda-forge")
# By default for now don't report on the build information back to github
AZURE_REPORT_BUILD_STATUS = os.getenv("AZURE_REPORT_BUILD_STATUS", "false")

try:
    with open(os.path.expanduser("~/.conda-smithy/azure.token"), "r") as fh:
        AZURE_TOKEN = fh.read().strip()
    if not AZURE_TOKEN:
        raise ValueError()
except (IOError, ValueError):
    print(
        "No azure token.  Create a token at https://dev.azure.com/conda-forge/_usersSettings/tokens and\n"
        "put it in ~/.conda-smithy/azure.token")

credentials = BasicAuthentication("", AZURE_TOKEN)
connection = VssConnection(base_url=AZURE_TEAM_INSTANCE, creds=credentials)


def get_service_endpoint(project_id=AZURE_PROJECT_ID):
    from vsts.service_endpoint.v4_1.service_endpoint_client import ServiceEndpointClient
    from vsts.service_endpoint.v4_1.models import ServiceEndpoint

    service_endpoint_client = ServiceEndpointClient(
        base_url=AZURE_TEAM_INSTANCE, creds=credentials)
    endpoints: typing.List[
        ServiceEndpoint] = service_endpoint_client.get_service_endpoints(
            project=project_id, type="GitHub")
    for service_endpoint in endpoints:
        if service_endpoint.name == AZURE_SERVICE_ENDPOINT_NAME:
            return service_endpoint
    else:
Пример #17
0
 def connection(self):
     connection = VssConnection(base_url=self.instance_base_url,
                                creds=self.credentials)
     return connection
Пример #18
0
    result = []
    # Azure DevOps limits the amount that can be retrieved to 200 at once
    for i in range(int(max_id / MAX_AMOUNT)):
        work_items = work_tracking_client.get_work_items(
            range(1 + (MAX_AMOUNT * i), 1 + MAX_AMOUNT + (MAX_AMOUNT * i)))
        result.extend(work_items)
    return result


# Fill in with your personal access token and org URL
personal_access_token = 'token'
organization_url = 'org'

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = VssConnection(base_url=organization_url, creds=credentials)

# Get a client (the "core" client provides access to projects, teams, etc)
core_client = connection.get_client('vsts.core.v4_0.core_client.CoreClient')

# Get the list of projects in the org
projects = core_client.get_projects()

# Project choice that the program will be looking inside and working with
##working_project = choice("Choose project:", projects, lambda project: project.name)
working_project = projects[0]

teams = core_client.get_teams(project_id=working_project.id)

#working_team = choice("Choose team:", teams, lambda team: team.name)
working_team = teams[0]