1 param(
2   [Parameter(Mandatory = $true)]
3   $RepoOwner,
4   # Use this if a pull request might have been opened from one repo against another.
5   # E.g Pull request opened from azure-sdk/azure-sdk prBranch --> Azure/azure-sdk baseBranch
6   $ForkRepoOwner,
7   [Parameter(Mandatory = $true)]
8   $RepoName,
9   [Parameter(Mandatory = $true)]
10   $BranchPrefix,
11   [Parameter(Mandatory = $true)]
12   $AuthToken
13 )
14 
15 . (Join-Path $PSScriptRoot common.ps1)
16 
17 LogDebug "Operating on Repo [ $RepoName ]"
18 try{
19   $branches = (Get-GitHubSourceReferences -RepoOwner $RepoOwner -RepoName $RepoName -Ref "heads/$BranchPrefix" -AuthToken $AuthToken).ref
20 }
21 catch {
22   LogError "Get-GitHubSourceReferences failed with exception:`n$_"
23   exit 1
24 }
25 
26 foreach ($branch in $branches)
27 {
28   try {
29     $branchName = $branch.Replace("refs/heads/","")
30     $head = "${RepoOwner}/${RepoName}:${branchName}"
31     LogDebug "Operating on branch [ $branchName ]"
32     $pullRequests = Get-GitHubPullRequests -RepoOwner $RepoOwner -RepoName $RepoName -State "all" -Head $head -AuthToken $AuthToken
33 
34     if ($ForkRepoOwner)
35     {
36       $pullRequests += Get-GitHubPullRequests -RepoOwner $ForkRepoOwner -RepoName $RepoName -State "all" -Head $head -AuthToken $AuthToken
37     }
38   }
39   catch
40   {
41     LogError "Get-GitHubPullRequests failed with exception:`n$_"
42     exit 1
43   }
44 
45   $openPullRequests = $pullRequests | ? { $_.State -eq "open" }
46   if ($openPullRequests.Count -gt 0)
47   {
48     LogDebug "Branch [ $branchName ] in repo [ $RepoName ] has open pull Requests. Skipping"
49     LogDebug $openPullRequests.url
50     continue
51   }
52 
53   LogDebug "Branch [ $branchName ] in repo [ $RepoName ] has no associated open Pull Request. Deleting Branch"
54   try{
55     Remove-GitHubSourceReferences -RepoOwner $RepoOwner -RepoName $RepoName -Ref ($branch.Remove(0,5)) -AuthToken $AuthToken
56   }
57   catch {
58     LogError "Remove-GitHubSourceReferences failed with exception:`n$_"
59     exit 1
60   }
61 }