Esempio n. 1
0
 def test_resolve_instance_project_and_repo(self):
     try:
         resolve_instance_project_and_repo(detect='off',
                                           organization='',
                                           project='',
                                           project_required=False,
                                           repo=None,
                                           repo_required=True)
         self.fail('we should have received an error')
     except CLIError as ex:
         self.assertEqual(str(ex), '--repository must be specified')
Esempio n. 2
0
def delete_ref(name,
               object_id,
               repository=None,
               organization=None,
               project=None,
               detect=None):
    """Delete a reference.
    :param str name: Name of the reference to delete (example: heads/my_branch).
    :param str object_id: Id of the reference to delete.
    :param str repository: Name or ID of the repository.
    :param str organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_git_client(organization)
        ref_update = GitRefUpdate(
            name=resolve_git_refs(name),
            new_object_id='0000000000000000000000000000000000000000',
            old_object_id=object_id)
        return client.update_refs(ref_updates=[ref_update],
                                  repository_id=repository,
                                  project=project)[0]
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 3
0
def create_ref(name,
               object_id,
               repository=None,
               organization=None,
               project=None,
               detect=None):
    """Create a reference.
    :param str name: Name of the reference to create (example: heads/my_branch or tags/my_tag).
    :param str object_id: Id of the object to create the reference from.
    :param str repository: Name or ID of the repository.
    :param str organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_git_client(organization)
        # by default, the create method does not support setting the is_locked value
        # to True.
        ref_update = GitRefUpdate(
            is_locked=False,
            name=resolve_git_refs(name),
            new_object_id=object_id,
            old_object_id='0000000000000000000000000000000000000000')
        return client.update_refs(ref_updates=[ref_update],
                                  repository_id=repository,
                                  project=project)[0]
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 4
0
def list_pull_request_statuses(pull_request_id, iteration_id=None, repository=None, organization=None,
                               project=None, detect=None):
    """Get all the statuses associated with a pull request.
    :param int pull_request_id: ID of the pull request.
    :param int iteration_id: ID of the iteration to associate status with. Minimum value is 1.
    :param str repository: Name or ID of the repository.
    :param str organization: The URI for the AZDO account (https://dev.azure.com/<account>/)
    :param str project: Name or ID of the project.
    :param str detect: When 'On' unsupplied arg values will be detected from the current working directory's repo.
    """
    try:
        team_instance, project, repository = resolve_instance_project_and_repo(
                                                detect=detect,
                                                organization=organization,
                                                project=project,
                                                repo=repository)
        git_client = get_git_client(team_instance)
        if iteration_id is not None:
            return git_client.get_pull_request_iteration_status(repository_id=repository,
                                                                pull_request_id=pull_request_id,
                                                                iteration_id=iteration_id,
                                                                project=project)
        return git_client.get_pull_request_statuses(repository_id=repository,
                                                    pull_request_id=pull_request_id,
                                                    project=project)
    except Exception as ex:
        raise ex
Esempio n. 5
0
def delete_ref(name,
               object_id,
               repository=None,
               organization=None,
               project=None,
               detect=None):
    """Delete a reference.
    :param str name: Name of the reference to delete (example: heads/my_branch).
    :param str object_id: Id of the reference to delete.
    :param str repository: Name or ID of the repository.
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    client = get_git_client(organization)
    ref_update = GitRefUpdate(
        name=resolve_git_refs(name),
        new_object_id='0000000000000000000000000000000000000000',
        old_object_id=object_id)
    return client.update_refs(ref_updates=[ref_update],
                              repository_id=repository,
                              project=project)[0]
def create_import_request(git_source_url,
                          project=None,
                          repository=None,
                          organization=None,
                          detect=None):
    """Create a git import request (currently only supports import from public git source)
    :param repository: Name or ID of the repository to create the import request in.
    :type repository: str
    :param git_source_url: Url of the source git repository
    :type git_source_url: str
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository,
        repo_required=True)
    client = get_git_client(organization)
    gitImportGitSource = GitImportGitSource(overwrite=False,
                                            url=git_source_url)
    gitImportRequestParameter = GitImportRequestParameters(
        delete_service_endpoint_after_import_is_done=False,
        git_source=gitImportGitSource,
        service_endpoint_id=None,
        tfvc_source=None)
    gitImportRequest = GitImportRequest(parameters=gitImportRequestParameter)
    importRequest = client.create_import_request(
        import_request=gitImportRequest,
        project=project,
        repository_id=repository)
    return _wait_for_import_request(client, project, repository,
                                    importRequest.import_request_id)
def build_definition_list(name=None, top=None, organization=None, project=None, repository=None,
                          repository_type=None, detect=None):
    """List build definitions.
    :param name: Limit results to definitions with this name or starting with this name. Examples: "FabCI" or "Fab*"
    :type name: bool
    :param top: Maximum number of definitions to list.
    :type top: int
    :param repository: Limit results to definitions associated with this repository.
    :type repository: str
    :param repository_type: Limit results to definitions associated with this repository type.
    It is mandatory to pass 'repository' argument along with this argument.
    :type repository_type: str
    :rtype: [BuildDefinitionReference]
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect, organization=organization, project=project, repo=repository)
    client = get_build_client(organization)
    query_order = 'DefinitionNameAscending'
    repository_type = None
    if repository is not None:
        if repository_type is None:
            repository_type = 'TfsGit'
        if repository_type.lower() == 'tfsgit':
            resolved_repository = _resolve_repository_as_id(repository, organization, project)
        else:
            resolved_repository = repository
        if resolved_repository is None:
            raise ValueError("Could not find a repository with name '{}', in project '{}'."
                             .format(repository, project))
    else:
        resolved_repository = None
    definition_references = client.get_definitions(project=project, name=name, repository_id=resolved_repository,
                                                   repository_type=repository_type, top=top,
                                                   query_order=query_order)
    return definition_references
Esempio n. 8
0
def show_repo(repo, organization=None, project=None, detect=None, open=False):  # pylint: disable=redefined-builtin
    """Get the details of a Git repository.
    :param repo: ID or name of the repository.
    :type repo: str
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the team project.
    :type project: str
    :param detect: Automatically detect organization, project and repository. Default is "on".
    :type detect: str
    :param open: Open the repository page in your web browser.
    :type open: bool
    :rtype: :class:`<GitRepository> <git.v4_0.models.GitRepository>`
    """
    try:
        organization, project, repo = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            project_required=True,
            repo=repo)
        git_client = get_git_client(organization)
        repository = git_client.get_repository(project=project,
                                               repository_id=repo)
        if open:
            _open_repository(repository, organization)
        return repository
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 9
0
def delete_ref(name, object_id=None, repository=None, organization=None, project=None, detect=None):
    """Delete a reference.
    :param str name: Name of the reference to delete (example: heads/my_branch).
    :param str object_id: Id of the reference to delete.
    :param str repository: Name or ID of the repository.
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    client = get_git_client(organization)

    if object_id is None:
        ref = client.get_refs(repository_id=repository, project=project, filter=name)
        if not ref or len(ref) != 1:
            logger.error('ref not found')
            raise CLIError("Failed to find object_id for ref " + name + ". Please provide object_id.")

        object_id = ref[0].object_id

    ref_update = GitRefUpdate(name=resolve_git_refs(name),
                              new_object_id='0000000000000000000000000000000000000000',
                              old_object_id=object_id)
    return client.update_refs(ref_updates=[ref_update],
                              repository_id=repository,
                              project=project)[0]
Esempio n. 10
0
def create_ref(name, object_id, repository=None, organization=None, project=None, detect=None):
    """Create a reference.
    :param str name: Name of the reference to create (example: heads/my_branch or tags/my_tag).
    :param str object_id: Id of the object to create the reference from.
    :param str repository: Name or ID of the repository.
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    client = get_git_client(organization)
    # by default, the create method does not support setting the is_locked value
    # to True.
    ref_update = GitRefUpdate(is_locked=False,
                              name=resolve_git_refs(name),
                              new_object_id=object_id,
                              old_object_id='0000000000000000000000000000000000000000')
    response = client.update_refs(ref_updates=[ref_update],
                                  repository_id=repository,
                                  project=project)[0]
    if response.success is False:
        raise CLIError(response.custom_message)
    return response
Esempio n. 11
0
def list_pull_requests(repository=None,
                       creator=None,
                       include_links=False,
                       reviewer=None,
                       source_branch=None,
                       status=None,
                       target_branch=None,
                       project=None,
                       skip=None,
                       top=None,
                       organization=None,
                       detect=None):
    """List pull requests.
    :param repository: Name or ID of the repository.
    :type repository: str
    :param creator: Limit results to pull requests created by this user.
    :type creator: str
    :param include_links: Include _links for each pull request.
    :type include_links: bool
    :param reviewer: Limit results to pull requests where this user is a reviewer.
    :type reviewer: str
    :param source_branch: Limit results to pull requests that originate from this source branch.
    :type source_branch: str
    :param status: Limit results to pull requests with this status.
    :type status: str
    :param target_branch: Limit results to pull requests that target this branch.
    :type target_branch: str
    :param skip: Number of pull requests to skip.
    :type skip: int
    :param top: Maximum number of pull requests to list.
    :type top: int
    :rtype: list of :class:`VssJsonCollectionWrapper <v5_0.git.models.VssJsonCollectionWrapper>`
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    search_criteria = GitPullRequestSearchCriteria(
        creator_id=resolve_identity_as_id(creator, organization),
        include_links=include_links,
        reviewer_id=resolve_identity_as_id(reviewer, organization),
        source_ref_name=resolve_git_ref_heads(source_branch),
        status=status,
        target_ref_name=resolve_git_ref_heads(target_branch))
    client = get_git_client(organization)
    if repository is None:
        pr_list = client.get_pull_requests_by_project(
            project=project,
            search_criteria=search_criteria,
            skip=skip,
            top=top)
    else:
        pr_list = client.get_pull_requests(project=project,
                                           repository_id=repository,
                                           search_criteria=search_criteria,
                                           skip=skip,
                                           top=top)
    return pr_list
def build_definition_list(name=None,
                          top=None,
                          organization=None,
                          project=None,
                          repository=None,
                          repository_type=None,
                          detect=None):
    """List build definitions.
    :param name: Limit results to definitions with this name or starting with this name. Examples: "FabCI" or "Fab*"
    :type name: bool
    :param top: Maximum number of definitions to list.
    :type top: int
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the team project.
    :type project: str
    :param repository: Limit results to definitions associated with this repository.
    :type repository: str
    :param detect: Automatically detect values for organization and project. Default is "on".
    :type detect: str
    :param repository_type: Limit results to definitions associated with this repository type.
    It is mandatory to pass 'repository' argument along with this argument.
    :type repository_type: str
    :rtype: [BuildDefinitionReference]
    """
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_build_client(organization)
        query_order = 'DefinitionNameAscending'
        repository_type = None
        if repository is not None:
            if repository_type is None:
                repository_type = 'TfsGit'
            if repository_type.lower() == 'tfsgit':
                resolved_repository = _resolve_repository_as_id(
                    repository, organization, project)
            else:
                resolved_repository = repository
            if resolved_repository is None:
                raise ValueError(
                    "Could not find a repository with name '{}', in project '{}'."
                    .format(repository, project))
        else:
            resolved_repository = None
        definition_references = client.get_definitions(
            project=project,
            name=name,
            repository_id=resolved_repository,
            repository_type=repository_type,
            top=top,
            query_order=query_order)
        return definition_references
    except VstsServiceError as ex:
        raise CLIError(ex)
def create_wiki(name=None,
                wiki_type='projectwiki',
                mapped_path=None,
                version=None,
                organization=None,
                project=None,
                repository=None,
                detect=None):
    """Create a wiki.
    :param name: Name of the new wiki.
    :type name: str
    :param wiki_type: Type of wiki to create.
    :type wiki_type: str
    :param version: [Required for codewiki type] Repository branch name to publish the code wiki from.
    :type version: str
    :param mapped_path: [Required for codewiki type] Mapped path of the new wiki
    e.g. '/' to publish from root of repository.
    :type mapped_path: str
    :param repository: [Required for codewiki type] Name or ID of the repository to publish the wiki from.
    :type repository: str
    """
    repository_id = None
    if wiki_type == 'codewiki':
        if not name:
            raise CLIError('--name is required for wiki type \'codewiki\'')
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository,
            repo_required=True)
        repository_id = _get_repository_id_from_name(organization=organization,
                                                     project=project,
                                                     repository=repository)
    else:
        organization, project = resolve_instance_and_project(
            detect=detect, organization=organization, project=project)
    wiki_client = get_wiki_client(organization)
    from azext_devops.devops_sdk.v5_0.wiki.models import WikiCreateParametersV2
    wiki_params = WikiCreateParametersV2()
    wiki_params.name = name
    wiki_params.type = wiki_type
    project_id = get_project_id_from_name(organization=organization,
                                          project=project)
    wiki_params.project_id = project_id
    wiki_params.repository_id = repository_id
    if mapped_path:
        wiki_params.mapped_path = mapped_path
    if version:
        from azext_devops.devops_sdk.v5_0.wiki.models import GitVersionDescriptor
        version_descriptor = GitVersionDescriptor()
        version_descriptor.version = version
        wiki_params.version = version_descriptor
    return wiki_client.create_wiki(wiki_create_params=wiki_params,
                                   project=project)
Esempio n. 14
0
def _update_ref(name, locked, repository, organization, project, detect):
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    client = get_git_client(organization)
    ref_update = GitRefUpdate(is_locked=locked)
    return client.update_ref(new_ref_info=ref_update,
                             repository_id=repository,
                             filter=name,
                             project=project)
Esempio n. 15
0
def _update_ref(name, locked, repository, organization, project, detect):
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_git_client(organization)
        ref_update = GitRefUpdate(is_locked=locked)
        return client.update_ref(new_ref_info=ref_update,
                                 repository_id=repository,
                                 filter=name,
                                 project=project)
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 16
0
def list_refs(filter=None, repository=None, organization=None, project=None, detect=None):
    """List the references.
    :param str filter: A filter to apply to the refs (starts with). Example: head or heads/ for the branches.
    :param str repository: Name or ID of the repository.
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    client = get_git_client(organization)
    return client.get_refs(repository_id=repository,
                           project=project,
                           filter=filter)
def update_repo(repository,
                default_branch=None,
                name=None,
                organization=None,
                project=None,
                detect=None):
    """Update the Git repository.
    :param repository: Name or ID of the repository.
    :type repository: str
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the team project.
    :type project: str
    :param name: New name for the repository.
    :type name: str
    :param default_branch: Default branch to be set for the repository. Example: 'refs/heads/live' or 'live'.
    :type default_branch: str
    :param detect: Automatically detect organization, project and repository. Default is "on".
    :type detect: str
    """
    if not default_branch and not name:
        raise CLIError(
            "Either --default-branch or --name (for rename) must be provided to update repository."
        )
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            project_required=True,
            repo=repository)
        git_client = get_git_client(organization)
        # Get the repo to be updated
        repository = git_client.get_repository(project=project,
                                               repository_id=repository)
        if default_branch:
            default_branch = resolve_git_ref_heads(default_branch)
            repository.default_branch = default_branch
        if name:
            repository.name = name
        repository = git_client.update_repository(
            project=project,
            repository_id=repository.id,
            new_repository_info=repository)
        return repository
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 18
0
def create_import_request(git_source_url,
                          project=None,
                          repository=None,
                          organization=None,
                          detect=None):
    """Create a git import request (currently only supports import from public git source)
    :param project: Name or ID of the team project.
    :type project: str
    :param repository: Name or ID of the repository to create the import request in.
    :type repository: str
    :param git_source_url: Url of the source git repository
    :type git_source_url: str
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param detect: Automatically detect organization, project, repository if these values are not specified.
                   Default is "on".
    :type detect: str
    """
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_git_client(organization)
        gitImportGitSource = GitImportGitSource(overwrite=False,
                                                url=git_source_url)
        gitImportRequestParameter = GitImportRequestParameters(
            delete_service_endpoint_after_import_is_done=False,
            git_source=gitImportGitSource,
            service_endpoint_id=None,
            tfvc_source=None)
        gitImportRequest = GitImportRequest(
            parameters=gitImportRequestParameter)
        importRequest = client.create_import_request(
            import_request=gitImportRequest,
            project=project,
            repository_id=repository)
        return _wait_for_import_request(client, project, repository,
                                        importRequest.import_request_id)
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 19
0
def create_pull_request_status(pull_request_id, state, name, description=None, genre=None, target_url=None,
                               iteration_id=None, repository=None, organization=None, project=None, detect=None):
    """Create a pull request status.
    :param int pull_request_id: ID of the pull request.
    :param str state: State of the status, supported are ['notSet', 'pending', 'succeeded', 'failed', 'error']
    :param str name: Name identifier of the status, cannot be null or empty.
    :param str description: Status description. Typically describes current state of the status.
    :param str genre: Genre of the status. Typically name of the service/tool generating the status, can be empty.
    :param str target_url: URL with status details.
    :param int iteration_id: ID of the iteration to associate status with. Minimum value is 1.
    :param str repository: Name or ID of the repository.
    :param str organization: The URI for the AZDO account (https://dev.azure.com/<account>/)
    :param str project: Name or ID of the project.
    :param str detect: When 'On' unsupplied arg values will be detected from the current working directory's repo.
    """
    try:
        team_instance, project, repository = resolve_instance_project_and_repo(
                                                detect=detect,
                                                organization=organization,
                                                project=project,
                                                repo=repository)
        git_client = get_git_client(team_instance)
        context = GitStatusContext(genre=genre, name=name)
        status = GitPullRequestStatus(context=context,
                                      state=state,
                                      description=description,
                                      target_url=target_url)
        if iteration_id is not None:
            return git_client.create_pull_request_iteration_status(status=status,
                                                                   repository_id=repository,
                                                                   pull_request_id=pull_request_id,
                                                                   iteration_id=iteration_id,
                                                                   project=project)
        return git_client.create_pull_request_status(status=status,
                                                     repository_id=repository,
                                                     pull_request_id=pull_request_id,
                                                     project=project)
    except Exception as ex:
        raise ex
Esempio n. 20
0
def update_repo(repository,
                default_branch=None,
                name=None,
                organization=None,
                project=None,
                detect=None):
    """Update the Git repository.
    :param repository: Name or ID of the repository.
    :type repository: str
    :param name: New name for the repository.
    :type name: str
    :param default_branch: Default branch to be set for the repository. Example: 'refs/heads/live' or 'live'.
    :type default_branch: str
    """
    if not default_branch and not name:
        raise CLIError(
            "Either --default-branch or --name (for rename) must be provided to update repository."
        )
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        project_required=True,
        repo=repository)
    git_client = get_git_client(organization)
    # Get the repo to be updated
    repository = git_client.get_repository(project=project,
                                           repository_id=repository)
    if default_branch:
        default_branch = resolve_git_ref_heads(default_branch)
        repository.default_branch = default_branch
    if name:
        repository.name = name
    repository = git_client.update_repository(project=project,
                                              repository_id=repository.id,
                                              new_repository_info=repository)
    return repository
Esempio n. 21
0
def show_repo(repository,
              organization=None,
              project=None,
              detect=None,
              open=False):  # pylint: disable=redefined-builtin
    """Get the details of a Git repository.
    :param repository: Name or ID of the repository.
    :type repository: str
    :param open: Open the repository page in your web browser.
    :type open: bool
    :rtype: :class:`<GitRepository> <git.v4_0.models.GitRepository>`
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        project_required=True,
        repo=repository)
    git_client = get_git_client(organization)
    repository = git_client.get_repository(project=project,
                                           repository_id=repository)
    if open:
        _open_repository(repository, organization)
    return repository
Esempio n. 22
0
def list_refs(filter=None,
              repository=None,
              organization=None,
              project=None,
              detect=None):
    """List the references.
    :param str filter: A filter to apply to the refs (starts with). Example: head or heads/ for the branches.
    :param str repository: Name or ID of the repository.
    :param str organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :param str project: Name or ID of the project.
    :param str detect: Automatically detect organization and project. Default is "on".
    """
    try:
        organization, project, repository = resolve_instance_project_and_repo(
            detect=detect,
            organization=organization,
            project=project,
            repo=repository)
        client = get_git_client(organization)
        return client.get_refs(repository_id=repository,
                               project=project,
                               filter=filter)
    except VstsServiceError as ex:
        raise CLIError(ex)
Esempio n. 23
0
def create_pull_request(project=None,
                        repository=None,
                        source_branch=None,
                        target_branch=None,
                        title=None,
                        description=None,
                        auto_complete=False,
                        squash=False,
                        delete_source_branch=False,
                        bypass_policy=False,
                        bypass_policy_reason=None,
                        merge_commit_message=None,
                        reviewers=None,
                        work_items=None,
                        draft=None,
                        open=False,
                        organization=None,
                        detect=None,
                        transition_work_items=False):  # pylint: disable=redefined-builtin
    """Create a pull request.
    :param project: Name or ID of the team project.
    :type project: str
    :param repository: Name or ID of the repository to create the pull request in.
    :type repository: str
    :param source_branch: Name of the source branch. Example: "dev".
    :type source_branch: str
    :param target_branch: Name of the target branch. If not specified, defaults to the
                          default branch of the target repository.
    :type target_branch: str
    :param title: Title for the new pull request.
    :type title: str
    :param draft: Use this flag to create the pull request in draft/work in progress mode.
    :type draft: bool
    :param description: Description for the new pull request. Can include markdown.
                        Each value sent to this arg will be a new line.
                        For example: --description "First Line" "Second Line"
    :type description: list of str
    :param auto_complete: Set the pull request to complete automatically when all policies have passed and
                          the source branch can be merged into the target branch.
    :type auto_complete: bool
    :param squash: Squash the commits in the source branch when merging into the target branch.
    :type squash: bool
    :param delete_source_branch: Delete the source branch after the pull request has been completed
                                 and merged into the target branch.
    :type delete_source_branch: bool
    :param bypass_policy: Bypass required policies (if any) and completes the pull request once it
                          can be merged.
    :type bypass_policy: bool
    :param bypass_policy_reason: Reason for bypassing the required policies.
    :type bypass_policy_reason: str
    :param merge_commit_message: Message displayed when commits are merged.
    :type merge_commit_message: str
    :param reviewers: Additional users or groups to include as reviewers on the new pull request.
                      Space separated.
    :type reviewers: list of str
    :param work_items: IDs of the work items to link to the new pull request. Space separated.
    :type work_items: list of str
    :param open: Open the pull request in your web browser.
    :type open: bool
    :param transition_work_items: Transition any work items linked to the pull request into the next logical state.
                   (e.g. Active -> Resolved)
    :type transition_work_items: bool
    :rtype: :class:`GitPullRequest <v5_0.git.models.GitPullRequest>`
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository)
    source_branch, target_branch = _get_branches_for_pull_request(
        organization, project, repository, source_branch, target_branch,
        detect)
    client = get_git_client(organization)
    multi_line_description = None
    if description is not None:
        multi_line_description = '\n'.join(description)
    pr = GitPullRequest(description=multi_line_description,
                        source_ref_name=source_branch,
                        target_ref_name=target_branch)
    if draft is not None:
        pr.is_draft = draft
    if title is not None:
        pr.title = title
    else:
        pr.title = 'Merge ' + source_branch + ' to ' + target_branch
    pr.source_ref_name = resolve_git_ref_heads(source_branch)
    pr.target_ref_name = resolve_git_ref_heads(target_branch)
    if pr.source_ref_name == pr.target_ref_name:
        raise CLIError(
            'The source branch, "{}", can not be the same as the target branch.'
            .format(pr.source_ref_name))
    pr.reviewers = _resolve_reviewers_as_refs(reviewers, organization)
    if work_items is not None and work_items:
        resolved_work_items = []
        for work_item in work_items:
            resolved_work_items.append(ResourceRef(id=work_item))
        pr.work_item_refs = resolved_work_items
    pr = client.create_pull_request(git_pull_request_to_create=pr,
                                    project=project,
                                    repository_id=repository)
    title_from_commit = None
    if title is None:
        # if title wasn't specified and only one commit, we will set the PR title to the comment of that commit
        commits = client.get_pull_request_commits(
            repository_id=repository,
            pull_request_id=pr.pull_request_id,
            project=project)
        if len(commits) == 1:
            title_from_commit = commits[0].comment
    set_completion_options = (bypass_policy or bypass_policy_reason is not None
                              or squash or merge_commit_message is not None
                              or delete_source_branch or transition_work_items)
    if auto_complete or set_completion_options or title_from_commit is not None:
        pr_for_update = GitPullRequest()
        if auto_complete:
            # auto-complete will not get set on create, so a subsequent update is required.
            pr_for_update.auto_complete_set_by = IdentityRef(
                id=resolve_identity_as_id(ME, organization))
        if set_completion_options:
            completion_options = GitPullRequestCompletionOptions()
            completion_options.bypass_policy = bypass_policy
            completion_options.bypass_reason = bypass_policy_reason
            completion_options.delete_source_branch = delete_source_branch
            completion_options.squash_merge = squash
            completion_options.merge_commit_message = merge_commit_message
            completion_options.transition_work_items = transition_work_items
            pr_for_update.completion_options = completion_options
        if title_from_commit is not None:
            pr_for_update.title = title_from_commit
        pr = client.update_pull_request(
            git_pull_request_to_update=pr_for_update,
            project=pr.repository.project.id,
            repository_id=pr.repository.id,
            pull_request_id=pr.pull_request_id)
    if open:
        _open_pull_request(pr, organization)
    return pr
Esempio n. 24
0
def create_import_request(git_source_url, project=None, repository=None,
                          requires_authorization=False,
                          user_name=None,
                          git_service_endpoint_id=None,
                          organization=None, detect=None):
    """Create a git import request
    :param repository: Name or ID of the repository to create the import request in.
    :type repository: str
    :param git_source_url: Url of the source git repository.
    :type git_source_url: str
    :param requires_authorization: Flag to tell if source git repository is private.
    :type requires_authorization: bool
    :param user_name: User name in case source git repository is private.
    :type user_name: str
    :param git_service_endpoint_id: Service Endpoint for connection to external endpoint.
    :type git_service_endpoint_id: str
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository,
        repo_required=True)

    delete_se_after_import = False

    password = None
    import random
    import string
    import os
    if requires_authorization and git_service_endpoint_id is None:
        delete_se_after_import = True
        if GIT_SOURCE_PASSWORD_OR_PAT in os.environ:
            password = os.environ[GIT_SOURCE_PASSWORD_OR_PAT]
        else:
            error_message = 'Please specify target git password / PAT in ' + GIT_SOURCE_PASSWORD_OR_PAT +\
                            ' environment variable in non-interactive mode.'
            verify_is_a_tty_or_raise_error(error_message)
            password = prompt_pass('Git Password / PAT:', confirm=True)

        service_endpoint_authorization = EndpointAuthorization(
            parameters={'password': password, 'username': user_name},
            scheme='UsernamePassword')
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)),
            type='git',
            url=git_source_url)
        client = get_service_endpoint_client(organization)
        se_created = client.create_service_endpoint(service_endpoint_to_create, project)
        git_service_endpoint_id = se_created.id

    client = get_git_client(organization)
    gitImportGitSource = GitImportGitSource(overwrite=False, url=git_source_url)
    gitImportRequestParameter = GitImportRequestParameters(
        delete_service_endpoint_after_import_is_done=delete_se_after_import,
        git_source=gitImportGitSource,
        service_endpoint_id=git_service_endpoint_id,
        tfvc_source=None)
    gitImportRequest = GitImportRequest(parameters=gitImportRequestParameter)
    importRequest = client.create_import_request(import_request=gitImportRequest, project=project,
                                                 repository_id=repository)
    return _wait_for_import_request(client, project, repository, importRequest.import_request_id)
def pipeline_create(name,
                    description=None,
                    repository=None,
                    branch=None,
                    yml_path=None,
                    repository_type=None,
                    service_connection=None,
                    organization=None,
                    project=None,
                    detect=None,
                    queue_id=None,
                    skip_first_run=None):
    """Create a new Azure Pipeline (YAML based)
    :param name: Name of the new pipeline
    :type name: str
    :param description: Description for the new pipeline
    :type description: str
    :param repository: Repository for which the pipeline needs to be configured.
    Can be clone url of the git repository or name of the repository for a Azure Repos
    or Owner/RepoName in case of GitHub repository.
    If omitted it will be auto-detected from the remote url of local git repository.
    If name is mentioned instead of url, --repository-type argument is also required.
    :type repository: str
    :param branch: Branch name for which the pipeline will be configured. If omitted, it will be auto-detected
    from local repository
    :type branch: str
    :param yml_path: Path of the pipelines yaml file in the repo (if yaml is already present in the repo).
    :type yml_path: str
    :param repository_type: Type of repository. If omitted, it will be auto-detected from remote url
    of local repository. 'tfsgit' for Azure Repos, 'github' for GitHub repository.
    :type repository_type: str
    :param service_connection: Id of the Service connection created for the repository for GitHub repository.
    Use command az devops service-endpoint -h for creating/listing service_connections. Not required for Azure Repos.
    :type service_connection: str
    :param queue_id: Id of the queue in the available agent pools. Will be auto detected if not specified.
    :type queue_id: str
    :param skip_first_run: Specify this flag to prevent the first run being triggered by the command.
    Command will return a pipeline if run is skipped else it will output a pipeline run.
    :type skip_first_run: bool
    """
    repository_name = None
    if repository:
        organization, project = resolve_instance_and_project(
            detect=detect, organization=organization, project=project)
    else:
        organization, project, repository_name = resolve_instance_project_and_repo(
            detect=detect, organization=organization, project=project)
    # resolve repository if local repo for azure repo
    if repository_name:
        repository = repository_name
        repository_type = _AZURE_GIT_REPO_TYPE
    # resolve repository from local repo for github repo
    if not repository:
        repository = _get_repository_url_from_local_repo(detect=detect)
    if not repository:
        raise CLIError('The following arguments are required: --repository.')
    if not repository_type:
        repository_type = try_get_repository_type(repository)
    if not repository_type:
        raise CLIError(
            'The following arguments are required: --repository-type. '
            'Check command help for valid values.')
    if not branch and should_detect(detect):
        branch = get_current_branch_name()
    if not branch:
        raise CLIError('The following arguments are required: --branch.')
    # repository, repository-type, branch should be set by now
    if not repository_name and is_valid_url(repository):
        repository_name = _get_repo_name_from_repo_url(repository)
    else:
        repository_name = repository

    # Validate name availability so user does not face name conflicts after going through the whole process
    if not validate_name_is_available(name, organization, project):
        raise CLIError(
            'Pipeline with name {name} already exists.'.format(name=name))

    # Parse repository information according to repository type
    repo_id = None
    api_url = None
    repository_url = None
    if repository_type.lower() == _GITHUB_REPO_TYPE:
        repo_id = repository_name
        repository_url = 'https://github.com/' + repository_name
        api_url = get_github_repos_api_url(repository_name)
    if repository_type.lower() == _AZURE_GIT_REPO_TYPE:
        repo_id = _get_repository_id_from_name(organization, project,
                                               repository_name)

    if not service_connection and repository_type != _AZURE_GIT_REPO_TYPE:
        service_connection = get_github_service_endpoint(organization, project)

    new_cix_client = get_new_cix_client(organization=organization)
    # No yml path => find or recommend yml scenario
    queue_branch = branch
    if not yml_path:
        yml_path, queue_branch = _create_and_get_yml_path(
            new_cix_client, repository_type, repo_id, repository_name, branch,
            service_connection, project, organization)
    if not queue_id:
        queue_id = _get_agent_queue_by_heuristic(organization=organization,
                                                 project=project)
        if queue_id is None:
            logger.warning(
                'Cannot find a hosted pool queue in the project. Provide a --queue-id in command params.'
            )

    # Create build definition
    definition = _create_pipeline_build_object(
        name, description, repo_id, repository_name, repository_url, api_url,
        branch, service_connection, repository_type, yml_path, queue_id)
    client = get_new_pipeline_client(organization)
    created_definition = client.create_definition(definition=definition,
                                                  project=project)
    logger.warning('Successfully created a pipeline with Name: %s, Id: %s.',
                   created_definition.name, created_definition.id)
    if skip_first_run:
        return created_definition
    return client.queue_build(build=Build(definition=created_definition,
                                          source_branch=queue_branch),
                              project=project)