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)
    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 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
Example #4
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
Example #5
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))
    for gitcommitRef in result:
        #print(type(gitcommitRef))
Example #6
0

'''
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")

enddate = datetime.today().isocalendar()
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':
        pprint.pprint("Yellow light blinking!")
Example #8
0
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:
                print("Project Name: " + project.name)
                print("Project ID: " + project.id)
                print("Description: " + str(project.description))