0

Please need help to how i can implement a solution on Azure Devops via Powershell or Api to verifying that there was Pull Request succeeded in merging to Develop Branch before make PR to Release Branch. When a devlopper will try to make a Pull Request on the release branch...a check must be made of existance of PR to the Develop branch .. otherwise the PR will be rejected.

After some research i found these solutions but no way to know the steps : -Build validation -Status ckecks -Powershell tasks Any détailed suggestion ?

anwar31dz
  • 1
  • 2

2 Answers2

0

Updated on 11/25

During my test, I have a workaround for your scenario.

Via Build Validation in Repo Policy. enter image description here enter image description here

You could create a powershell pipeline to run the rest api to query the completed pull requests history from Source Branch to Target Branche.

# Define organization base url, PAT and API version variables
$orgUrl = "https://dev.azure.com/{org}/{project}"
$pat = "{pat}"
$queryString = "searchCriteria.sourceRefName=refs/heads/{sourceBranche}&searchCriteria.status=completed&api-version=6.0"

# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = @{authorization = "Basic $token"}
# Get the list of all projects in the organization
$projectsUrl = "$orgUrl/_apis/git/repositories/{repoID}/pullrequests?$queryString"
$number = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header | ConvertTo-Json | ConvertFrom-Json | Select-Object -ExpandProperty count

write-host $number

if ($number -gt 0) {
    Write-Host "Check Succeeded"
}
else {
    Write-Host ("Check Failed")
    exit 1
}

This rest api will return the result like below. enter image description here

And the script will evaluate if the count is above 0 and then succeed the validation, else fail the validation.

enter image description here

Ceeno Qi-MSFT
  • 924
  • 1
  • 3
  • 5
0

After having investigated and tested more than one solution, I share with you the best one that fits my needs: In this Exemple

  • Source Branch = Unstable
  • Target Branch = Develop

Request : When I do a PR in the Develop branch, the Powershell script checks if the last commit in this branch was committed first in the unstable branch => if it is the case the build continues otherwise the build is stopped.

$tfsUrl = "$tfsBaseUrl/_apis"
$tfsFullUrl = "$tfsBaseUrl/_apis/git/repositories"

$strAdmAuth = ":$tfsToken"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($strAdmAuth)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }

############# Variables ############################

$reponame = $env:repositoryName
Write-Host "Repository name : $reponame"
$repoID = $env:repositoryID
Write-Host "Repository ID : $repoID"
$SourceBranch = $env:SourceBranch
Write-host "Source branch : $SourceBranch"
$pullRequestTargetBranch = $env:PRTargetBranch
Write-host "Pull request Target branch : $pullRequestTargetBranch"
$SourceBranch = $SourceBranch.Substring(10,($SourceBranch.Length-10))
$lastindexof = $sourceBranch.LastIndexOf("/")
 
$pullrequestID = $SourceBranch.Substring(0,($lastindexof))

$FullUri = "$tfsFullUrl/"+"$repoID"+'/pullrequests/'+"$pullrequestID"+'?api-version=6.0'


$SourceBranchName = (Invoke-RestMethod -Uri $FullUri -Method get -Headers $headers).sourceRefName

$indexof = $SourceBranchName.substring(5,($SourceBranchName.Length-5)).IndexOf("/")

$BranchFull = $SourceBranchName.Substring(6+$indexof,($SourceBranchName.Length-(6+$indexof)))


Write-host "$BranchFull"
$CommitExist = $false
$topCommit = "$"+"top=1"
$branchUnstable= "unstable"


Function Write-ErrorMessage
{
    [CmdletBinding(DefaultParameterSetName='ErrorMessage')]
      param
      (
           [Parameter(Position=0,ParameterSetName='ErrorMessage',ValueFromPipeline,Mandatory)][string]$errorMessage
           ,[Parameter(ParameterSetName='ErrorRecord',ValueFromPipeline)][System.Management.Automation.ErrorRecord]$errorRecord
           ,[Parameter(ParameterSetName='Exception',ValueFromPipeline)][Exception]$exception
      )

      switch($PsCmdlet.ParameterSetName)
      {
        'ErrorMessage'
        {
            $err = $errorMessage
        }
        'ErrorRecord'
        {
            $errorMessage = @($error)[0]
            $err = $errorRecord
        }
        'Exception'
        {
            $errorMessage = $exception.Message
            $err = $exception
        }
      }

    Write-Error -Message $err -ErrorAction SilentlyContinue
    $Host.UI.WriteErrorLine($errorMessage)
};

function encodeBranchName([string]$branchName)
{
    $branchName.Replace('#', '%23').Replace('+', '%2B').Replace('&', '%26')
}
 

###################################### All commits of unstable ###################################

 $commitUnstableURI = "$tfsFullUrl/${repoName}/commits?searchCriteria.itemVersion.version=${branchUnstable}&api-version=5.1"

 $listCommitUnstable = Invoke-RestMethod -Uri $commitUnstableURI -Method GET -ContentType "application/json" -Headers $headers

 $CommitunstableID = $listCommitUnstable.value.commitId


 ############################# Last commit of BranchFilter on Develop ###########################

 
 $branchNameEncoded = encodeBranchName $branchFull
 $branchFullversion= "version=$branchNameEncoded"
 
 $lastCommitURI = "$tfsFullUrl/${repoName}/commits?searchCriteria.itemVersion.$branchFullversion&searchCriteria.$topCommit&api-version=5.1"
 try
    {
        $lastCommit = Invoke-RestMethod -Uri $lastCommitURI -Method GET -ContentType "application/json; charset=utf-8" -Headers $headers
        write-host "Last commit : $LastCommit"
    }
    catch
    {
        Write-Error "No Commit exists for repo : $branchfull"
        Write-Error "[ERROR] $($_.Exception.Message)"
        exit 1
    }

    $branchLastCommitId = $lastCommit.value.commitId
    write-host "Last commit of branch : $branchLastCommitId"
 
 
  Foreach ($i in $CommitUnstableID) 
  {
          if ($i -eq $branchLastCommitId) 
          {
            $CommitExist = $true
            Write-Host "The last commit was deployed on Branch Unstable" 
          }
         
 }

 if ($CommitExist -eq $false)
 {
    #Write-Error "/!\ Commit does not exists on 'unstable' branch /!\"
    Write-ErrorMessage "/!\ Commit does not exists on 'unstable' branch /!\"
 }


anwar31dz
  • 1
  • 2