MegaBites-AI/Windows-powershell
0372
1#requires -Version 6.02# Copyright (c) Microsoft Corporation.3# Licensed under the MIT License.4 5class CommitNode {6 [string] $Hash7 [string[]] $Parents8 [string] $AuthorName9 [string] $AuthorGitHubLogin10 [string] $AuthorEmail11 [string] $Subject12 [string] $Body13 [string] $PullRequest14 [string] $ChangeLogMessage15 [string] $ThankYouMessage16 [bool] $IsBreakingChange17 18 CommitNode($hash, $parents, $name, $email, $subject, $body) {19 $this.Hash = $hash20 $this.Parents = $parents21 $this.AuthorName = $name22 $this.AuthorEmail = $email23 $this.Subject = $subject24 $this.Body = $body25 $this.IsBreakingChange = $body -match "\[breaking change\]"26 27 if ($subject -match "\(#(\d+)\)$") {28 $this.PullRequest = $Matches[1]29 }30 }31}32 33# These powershell team members don't use 'microsoft.com' for Github email or choose to not show their emails.34# We have their names in this array so that we don't need to query GitHub to find out if they are powershell team members.35$Script:powershell_team = @(36 "Travis Plunk"37 "dependabot-preview[bot]"38 "dependabot[bot]"39 "github-actions[bot]"40 "Copilot"41 "Anam Navied"42 "Andrew Schwartzmeyer"43 "Jason Helmick"44 "Patrick Meinecke"45 "Steven Bucher"46 "PowerShell Team Bot"47 "Justin Chung"48)49 50# The powershell team members GitHub logins. We use them to decide if the original author of a backport PR is from the team.51$script:psteam_logins = @(52 'andyleejordan'53 'TravisEz13'54 'daxian-dbw'55 'adityapatwardhan'56 'SteveL-MSFT'57 'dependabot[bot]'58 'pwshBot'59 'jshigetomi'60 'SeeminglyScience'61 'anamnavi'62 'sdwheeler'63 'Copilot'64 'copilot-swe-agent'65 'app/copilot-swe-agent'66 'StevenBucher98'67 'alerickson'68 'tgauth'69)70 71# They are very active contributors, so we keep their email-login mappings here to save a few queries to Github.72$Script:community_login_map = @{73 "darpa@yandex.ru" = "iSazonov"74 "c.bergmeister@gmail.com" = "bergmeister"75 "github@markekraus.com" = "markekraus"76 "info@powercode-consulting.se" = "powercode"77}78 79##############################80#.SYNOPSIS81#In the release workflow, the release branch will be merged back to master after the release is done,82#and a merge commit will be created as the child of the release tag commit.83#This cmdlet takes a release tag or the corresponding commit hash, find its child merge commit, and84#return its metadata in this format: <merge-commit-hash>|<parent-commit-hashes>85#86#.PARAMETER LastReleaseTag87#The last release tag88#89#.PARAMETER CommitHash90#The commit hash of the last release tag91#92#.OUTPUTS93#Return the metadata of the child merge commit, in this format: <merge-commit-hash>|<parent-commit-hashes>94##############################95function Get-ChildMergeCommit96{97 [CmdletBinding(DefaultParameterSetName="TagName")]98 param(99 [Parameter(Mandatory, ParameterSetName="TagName")]100 [string]$LastReleaseTag,101 102 [Parameter(Mandatory, ParameterSetName="CommitHash")]103 [string]$CommitHash104 )105 106 $tag_hash = $CommitHash107 if ($PSCmdlet.ParameterSetName -eq "TagName") { $tag_hash = git rev-parse "$LastReleaseTag^0" }108 109 ## Get the merge commits that are reachable from 'HEAD' but not from the release tag110 $merge_commits_not_in_release_branch = git --no-pager log --merges "$tag_hash..HEAD" --format='%H||%P'111 ## Find the child merge commit, whose parent-commit-hashes contains the release tag hash112 $child_merge_commit = $merge_commits_not_in_release_branch | Select-String -SimpleMatch $tag_hash113 return $child_merge_commit.Line114}115 116##############################117#.SYNOPSIS118#Create a CommitNode instance to represent a commit.119#120#.PARAMETER CommitMetadata121#The commit metadata. It's in this format:122#<commit-hash>|<parent-hashes>|<author-name>|<author-email>|<commit-subject>123#124#.PARAMETER CommitMetadata125#The commit metadata, in this format:126#<commit-hash>|<parent-hashes>|<author-name>|<author-email>|<commit-subject>127#128#.OUTPUTS129#Return the 'CommitNode' object130##############################131function New-CommitNode132{133 param(134 [Parameter(ValueFromPipeline)]135 [ValidatePattern("^.+\|.+\|.+\|.+\|.+$")]136 [string]$CommitMetadata137 )138 139 Process {140 $hash, $parents, $name, $email, $subject = $CommitMetadata.Split("||")141 $body = (git --no-pager show $hash -s --format=%b) -join "`n"142 return [CommitNode]::new($hash, $parents, $name, $email, $subject, $body)143 }144}145 146##############################147#.SYNOPSIS148#Generate the draft change log.149#150#.PARAMETER LastReleaseTag151#The last release tag152#153#.PARAMETER HasCherryPick154#Indicate whether there are any commits in the last release branch that were cherry-picked from the master branch155#156#.PARAMETER Token157#The authentication token to use for retrieving the GitHub user log-in names for external contributors158#159#.OUTPUTS160#The generated change log draft.161##############################162function Get-ChangeLog163{164 param(165 [Parameter(Mandatory = $true)]166 [string]$LastReleaseTag,167 168 [Parameter(Mandatory = $true)]169 [string]$ThisReleaseTag,170 171 [Parameter(Mandatory = $false)]172 [string]$Token,173 174 [Parameter()]175 [switch]$HasCherryPick176 )177 178 if(-not $Token) {179 $Token = Get-GHDefaultAuthToken180 if(-not $Token) {181 throw "No GitHub Auth Token provided"182 }183 }184 185 $tag_hash = git rev-parse "$LastReleaseTag^0"186 $format = '%H||%P||%aN||%aE||%s'187 $header = @{"Authorization"="token $Token"}188 189 # Find the merge commit that merged the release branch to master.190 $child_merge_commit = Get-ChildMergeCommit -CommitHash $tag_hash191 if($child_merge_commit)192 {193 $commit_hash, $parent_hashes = $child_merge_commit.Split("||")194 }195 # Find the other parent of the merge commit, which represents the original head of master right before merging.196 $other_parent_hash = ($parent_hashes -replace $tag_hash).Trim()197 198 if ($HasCherryPick) {199 ## Sometimes we need to cherry-pick some commits from the master branch to the release branch during the release,200 ## and eventually merge the release branch back to the master branch. This will result in different commit nodes201 ## in master branch that actually represent same set of changes.202 ##203 ## In this case, we cannot simply use the revision range "$tag_hash..HEAD" because it will include the original204 ## commits in the master branch that were cherry-picked to the release branch -- they are reachable from 'HEAD'205 ## but not reachable from the last release tag. Instead, we need to exclude the commits that were cherry-picked,206 ## and only include the commits that are not in the last release into the change log.207 208 # Find the commits that were only in the original master, excluding those that were cherry-picked to release branch.209 $new_commits_from_other_parent = git --no-pager log --first-parent --cherry-pick --right-only "$tag_hash...$other_parent_hash" --format=$format | New-CommitNode210 # Find the commits that were only in the release branch, excluding those that were cherry-picked from master branch.211 $new_commits_from_last_release = git --no-pager log --first-parent --cherry-pick --left-only "$tag_hash...$other_parent_hash" --format=$format | New-CommitNode212 # Find the commits that are actually duplicate but having different patch-ids due to resolving conflicts during the cherry-pick.213 $duplicate_commits = $null214 if($new_commits_from_last_release -and $new_commits_from_other_parent)215 {216 $duplicate_commits = Compare-Object $new_commits_from_last_release $new_commits_from_other_parent -Property PullRequest -ExcludeDifferent -IncludeEqual -PassThru217 }218 if ($duplicate_commits) {219 $duplicate_pr_numbers = @($duplicate_commits | ForEach-Object -MemberName PullRequest)220 $new_commits_from_other_parent = $new_commits_from_other_parent | Where-Object PullRequest -NotIn $duplicate_pr_numbers221 }222 223 # Find the commits that were made after the merge commit.224 $new_commits_after_merge_commit = @(git --no-pager log --first-parent "$commit_hash..HEAD" --format=$format | New-CommitNode)225 $new_commits = $new_commits_after_merge_commit + $new_commits_from_other_parent226 } else {227 ## No cherry-pick was involved in the last release branch.228 ## Using a ref rang like "$tag_hash..HEAD" with 'git log' means getting the commits that are reachable from 'HEAD' but not reachable from the last release tag.229 230 ## We use '--first-parent' for 'git log'. It means for any merge node, only follow the parent node on the master branch side.231 ## In case we merge a branch to master for a PR, only the merge node will show up in this way, the individual commits from that branch will be ignored.232 ## This is what we want because the merge commit itself already represents the PR.233 234 ## First, we want to get all new commits merged during the last release235 $new_commits_during_last_release = @(git --no-pager log --first-parent "$tag_hash..$other_parent_hash" --format=$format | New-CommitNode)236 ## Then, we want to get all new commits merged after the last release237 $new_commits_after_last_release = @(git --no-pager log --first-parent "$commit_hash..HEAD" --format=$format | New-CommitNode)238 ## Last, we get the full list of new commits239 $new_commits = $new_commits_during_last_release + $new_commits_after_last_release240 }241 242 # Array of unlabled PRs.243 $unlabeledPRs = @()244 245 # Array of PRs with multiple labels. The label "CL-BreakingChange" is allowed with some other "CL-*" label.246 $multipleLabelsPRs = @()247 248 # Array of PRs tagged with 'CL-BreakingChange' label.249 $clBreakingChange = @()250 251 # Array of PRs tagged with 'CL-BuildPackaging' label.252 $clBuildPackage = @()253 254 # Array of PRs tagged with 'CL-CodeCleanup' label.255 $clCodeCleanup = @()256 257 # Array of PRs tagged with 'CL-Docs' label.258 $clDocs = @()259 260 # Array of PRs tagged with 'CL-Engine' label.261 $clEngine = @()262 263 # Array of PRs with general cmdlet changes.264 $clGeneral = @()265 266 # Array of PRs tagged with 'CL-Performance' label.267 $clPerformance = @()268 269 # Array of PRs tagged with 'CL-Test' label.270 $clTest = @()271 272 # Array of PRs tagged with 'CL-Tools' label.273 $clTools = @()274 275 # Array of PRs tagged with 'CL-Untagged' label.276 $clUntagged = @()277 278 # Array of PRs tagged with 'CL-Experimental' label.279 $clExperimental = @()280 281 foreach ($commit in $new_commits) {282 $commitSubject = $commit.Subject283 $prNumber = $commit.PullRequest284 Write-Verbose "subject: $commitSubject"285 Write-Verbose "authorname: $($commit.AuthorName)"286 287 try {288 $pr = Invoke-RestMethod `289 -Uri "https://api.github.com/repos/PowerShell/PowerShell/pulls/$prNumber" `290 -Headers $header `291 -ErrorAction Stop `292 -Verbose:$false ## Always disable verbose to avoid noise when we debug this function.293 } catch {294 ## A commit may not have corresponding GitHub PRs. In that case, we will get status code 404 (Not Found).295 ## Otherwise, let the error bubble up.296 if ($_.Exception.Response.StatusCode -ne 404) {297 throw298 }299 }300 301 if ($commitSubject -match '^\[release/v\d\.\d\] ') {302 ## The commit was from a backport PR. We need to get the real author in this case.303 if (-not $pr) {304 throw "The commit is from a backport PR (#$prNumber), but the PR cannot be found.`nPR Title: $commitSubject"305 }306 307 $userPattern = 'Triggered by @.+ on behalf of @(.+)'308 if ($pr.body -match $userPattern) {309 $commit.AuthorGitHubLogin = ($Matches.1).Trim()310 Write-Verbose "backport PR. real author login: $($commit.AuthorGitHubLogin)"311 } else {312 throw "The commit is from a backport PR (#$prNumber), but the PR description failed to match the pattern '$userPattern'. Was the template for backport PRs changed?`nPR Title: $commitSubject"313 }314 }315 316 if ($commit.AuthorGitHubLogin) {317 if ($script:psteam_logins -contains $commit.AuthorGitHubLogin) {318 $commit.ChangeLogMessage = "- {0}" -f (Get-ChangeLogMessage $commitSubject)319 } else {320 $commit.ChangeLogMessage = ("- {0} (Thanks @{1}!)" -f (Get-ChangeLogMessage $commitSubject), $commit.AuthorGitHubLogin)321 $commit.ThankYouMessage = ("@{0}" -f ($commit.AuthorGitHubLogin))322 }323 } elseif ($commit.AuthorEmail.EndsWith("@microsoft.com") -or $powershell_team -contains $commit.AuthorName) {324 $commit.ChangeLogMessage = "- {0}" -f (Get-ChangeLogMessage $commitSubject)325 } else {326 if ($community_login_map.ContainsKey($commit.AuthorEmail)) {327 $commit.AuthorGitHubLogin = $community_login_map[$commit.AuthorEmail]328 } else {329 try{330 ## Always disable verbose to avoid noise when we debug this function.331 $response = Invoke-RestMethod `332 -Uri "https://api.github.com/repos/PowerShell/PowerShell/commits/$($commit.Hash)" `333 -Headers $header `334 -ErrorAction Stop `335 -Verbose:$false336 } catch {337 ## A commit could be available in ADO only. In that case, we will get status code 422 (UnprocessableEntity).338 ## Otherwise, let the error bubble up.339 if ($_.Exception.Response.StatusCode -ne 422) {340 throw341 }342 }343 344 if($response)345 {346 $commit.AuthorGitHubLogin = $response.author.login347 $community_login_map[$commit.AuthorEmail] = $commit.AuthorGitHubLogin348 }349 }350 351 $commit.ChangeLogMessage = ("- {0} (Thanks @{1}!)" -f (Get-ChangeLogMessage $commitSubject), $commit.AuthorGitHubLogin)352 $commit.ThankYouMessage = ("@{0}" -f ($commit.AuthorGitHubLogin))353 }354 355 if ($commit.IsBreakingChange) {356 $commit.ChangeLogMessage = "{0} [Breaking Change]" -f $commit.ChangeLogMessage357 }358 359 ## Get the labels for the PR360 if($pr)361 {362 $clLabel = $pr.labels | Where-Object { $_.Name -match "^CL-"}363 }364 else {365 Write-Warning -Message "Tagging $($commit.Hash) by $($commit.AuthorName), as CL-BuildPackaging as it does not have a PR."366 $clLabel = [PSCustomObject]@{Name ='CL-BuildPackaging'}367 }368 369 if ($clLabel.count -gt 1 -and $clLabel.Name -notcontains 'CL-BreakingChange') {370 $multipleLabelsPRs += $pr371 }372 elseif ($clLabel.count -eq 0) {373 $unlabeledPRs += $pr374 }375 else {376 switch ($clLabel.Name) {377 "CL-BreakingChange" { $clBreakingChange += $commit }378 "CL-BuildPackaging" { $clBuildPackage += $commit }379 "CL-CodeCleanup" { $clCodeCleanup += $commit }380 "CL-Docs" { $clDocs += $commit }381 "CL-Engine" { $clEngine += $commit }382 "CL-Experimental" { $clExperimental += $commit }383 "CL-General" { $clGeneral += $commit }384 "CL-Performance" { $clPerformance += $commit }385 "CL-Test" { $clTest += $commit }386 "CL-Tools" { $clTools += $commit }387 "CL-Untagged" { $clUntagged += $commit }388 "CL-NotInBuild" { continue }389 Default { throw "unknown tag '$cLabel' for PR: '$prNumber'" }390 }391 }392 }393 394 if ($multipleLabelsPRs.count -gt 0) {395 Write-Error "PRs should not be tagged with multiple CL labels. PRs with multiple labels: $($multipleLabelsPRs.number -join ' ')"396 $shouldThrow = $true397 }398 399 if ($unlabeledPRs.count -gt 0) {400 Write-Error "PRs should have at least one CL label. PRs missing labels: $($unlabeledPRs.number -join ' ')"401 $shouldThrow = $true402 }403 404 if ($shouldThrow) {405 throw "Some PRs are tagged multiple times or have no tags."406 }407 408 # Write output409 410 $version = $ThisReleaseTag.TrimStart('v')411 412 Write-Output "## [${version}] - $(Get-Date -Format yyyy-MM-dd)`n"413 414 PrintChangeLog -clSection $clUntagged -sectionTitle 'UNTAGGED - Please classify'415 PrintChangeLog -clSection $clBreakingChange -sectionTitle 'Breaking Changes'416 PrintChangeLog -clSection $clEngine -sectionTitle 'Engine Updates and Fixes'417 PrintChangeLog -clSection $clExperimental -sectionTitle 'Experimental Features'418 PrintChangeLog -clSection $clPerformance -sectionTitle 'Performance'419 PrintChangeLog -clSection $clGeneral -sectionTitle 'General Cmdlet Updates and Fixes'420 PrintChangeLog -clSection $clCodeCleanup -sectionTitle 'Code Cleanup' -Compress421 PrintChangeLog -clSection $clTools -sectionTitle 'Tools'422 PrintChangeLog -clSection $clTest -sectionTitle 'Tests'423 PrintChangeLog -clSection $clBuildPackage -sectionTitle 'Build and Packaging Improvements' -Compress424 PrintChangeLog -clSection $clDocs -sectionTitle 'Documentation and Help Content'425 426 Write-Output "[${version}]: https://github.com/PowerShell/PowerShell/compare/${LastReleaseTag}...${ThisReleaseTag}`n"427}428 429function Get-GHDefaultAuthToken {430 $IsGHCLIInstalled = $false431 if (Get-command -CommandType Application -Name gh -ErrorAction SilentlyContinue) {432 $IsGHCLIInstalled = $true433 } else {434 Write-Error -Message "GitHub CLI is not installed. Please install it from https://cli.github.com/" -ErrorAction Stop435 }436 437 if ($IsGHCLIInstalled) {438 try {439 $Token = & gh auth token440 } catch {441 Write-Error -Message "Please login to GitHub CLI using 'gh auth login'"442 }443 }444 445 if (-not $Token) {446 $Token = Read-Host -Prompt "Enter GitHub Auth Token"447 }448 449 return $Token450}451 452function PrintChangeLog($clSection, $sectionTitle, [switch] $Compress) {453 if ($clSection.Count -gt 0) {454 "### $sectionTitle`n"455 456 if ($Compress) {457 $items = $clSection.ChangeLogMessage -join "`n"458 $thankYou = "We thank the following contributors!`n`n"459 $thankYou += ($clSection.ThankYouMessage | Select-Object -Unique | Where-Object { if($_) { return $true} return $false}) -join ", "460 461 "<details>`n"462 "<summary>`n"463 $thankYou | ConvertFrom-Markdown | Select-Object -ExpandProperty Html464 "</summary>`n"465 $items | ConvertFrom-Markdown | Select-Object -ExpandProperty Html466 "</details>"467 }468 else {469 $clSection | ForEach-Object -MemberName ChangeLogMessage470 }471 ""472 }473}474 475function Get-ChangeLogMessage476{477 param($OriginalMessage)478 479 switch -regEx ($OriginalMessage)480 {481 '^Merged PR (\d*): ' {482 return $OriginalMessage.replace($Matches.0,'') + " (Internal $($Matches.1))"483 }484 '^Build\(deps\): ' {485 return $OriginalMessage.replace($Matches.0,'')486 }487 '^\[release/v\d\.\d\] ' {488 return $OriginalMessage.replace($Matches.0,'')489 }490 default {491 return $OriginalMessage492 }493 }494}495 496##############################497#.SYNOPSIS498#Gets packages which have newer packages in nuget.org499#500#.PARAMETER Path501#The path to check for csproj files with packagse502#503#.PARAMETER IncludeAll504#Include packages that don't need to be updated505#506#.OUTPUTS507#Objects which represet the csproj package ref, with the current and new version508##############################509function Get-NewOfficalPackage510{511 param(512 [String]513 $Path = (Join-Path -Path $PSScriptRoot -ChildPath '..\src'),514 [Switch]515 $IncludeAll516 )517 # Calculate the filter to find the CSProj files518 $filter = Join-Path -Path $Path -ChildPath '*.csproj'519 $csproj = Get-ChildItem $filter -Recurse -Exclude 'PSGalleryModules.csproj'520 521 $csproj | ForEach-Object{522 $file = $_523 524 # parse the csproj525 [xml] $csprojXml = (Get-Content -Raw -Path $_)526 527 # get the package references528 $packages=$csprojXml.Project.ItemGroup.PackageReference529 530 # check to see if there is a newer package for each refernce531 foreach ($package in $packages)532 {533 # Get the name of the package534 $name = $package.Include535 536 if ($name)537 {538 # Get the current package from nuget539 $versions = Find-Package -Name $name -Source https://nuget.org/api/v2/ -ErrorAction SilentlyContinue -AllVersions |540 Add-Member -Type ScriptProperty -Name Published -Value { $this.Metadata['published']} -PassThru |541 Where-Object { Test-IncludePackageVersion -NewVersion $_.Version -Version $package.version}542 543 $revsionRegEx = Get-MatchingMajorMinorRegEx -Version $package.version544 $newPackage = $versions |545 Sort-Object -Descending |546 Select-Object -First 1547 548 # Get the newest matching revision549 $newRevision = $versions |550 Where-Object {$_.Version -match $revsionRegEx } |551 Sort-Object -Descending |552 Select-Object -First 1553 554 # If the current package has a different version from the version in the csproj, print the details555 if ($newRevision -and $newRevision.Version.ToString() -ne $package.version -or $newPackage -and $newPackage.Version.ToString() -ne $package.version -or $IncludeAll.IsPresent)556 {557 if ($newRevision)558 {559 $newRevisionString = $newRevision.Version560 }561 else562 {563 # We don't have a new Revision, report the current version564 $newRevisionString = $package.Version565 }566 567 if ($newPackage)568 {569 $newVersionString = $newPackage.Version570 }571 else572 {573 # We don't have a new Version, report the current version574 $newVersionString = $package.Version575 }576 577 [pscustomobject]@{578 Csproj = (Split-Path -Path $file -Leaf)579 PackageName = $name580 CsProjVersion = $Package.Version581 NuGetRevision = $newRevisionString582 NuGetVersion = $newVersionString583 }584 }585 }586 }587 }588}589 590##############################591#.SYNOPSIS592# Returns True if NewVersion is newer than Version593# Pre release are ignored if the current version is not pre-release594# If the current version is pre-release, this function only determines if the version portion is NewReleaseTag595# The calling function is responsible for sorting prelease version by publish date (as find-package gives them to you)596# and returning the newest.597#598#.PARAMETER Version599# The current Version600#601#.PARAMETER NewVersion602# The potention replacement version603#604#.OUTPUTS605# True if NewVersion should be considere as a replacement606##############################607function Test-IncludePackageVersion608{609 param(610 [string]611 $NewVersion,612 [string]613 $Version614 )615 616 $simpleCompare = $Version -notlike '*-*'617 618 if($simpleCompare -and $NewVersion -like '*-*')619 {620 # We are using a stable and the new version is pre-release621 return $false622 }623 elseif($simpleCompare -and [Version]$NewVersion -ge [Version] $Version)624 {625 # Simple comparison says the new version is newer626 return $true627 }628 elseif($simpleCompare)629 {630 # Simple comparison was done, but it was not newer631 return $false632 }633 elseif($NewVersion -notlike '*-*')634 {635 # Our current version is a pre-release but the new is not636 # make sure the new version is newer than the version part of the current version637 $versionOnly = ($Version -Split '\-')[0]638 if([Version]$NewVersion -ge [Version] $versionOnly)639 {640 return $true641 }642 else643 {644 return $false645 }646 }647 else648 {649 # Not sure, include it650 return $true651 }652}653 654##############################655#.SYNOPSIS656# Get a RegEx based on a version that will match the major and minor657#658#.PARAMETER Version659# The version to match660#661##############################662function Get-MatchingMajorMinorRegEx663{664 param(665 [Parameter(Mandatory)]666 $Version667 )668 669 $parts = $Version -split '\.'670 671 $regEx = "^$($parts[0])\.$($parts[1])\..*"672 return $regEx673}674 675##############################676#.SYNOPSIS677# Update the version number in code678#679#.PARAMETER NewReleaseTag680# The new Release Tag681#682#.PARAMETER NextReleaseTag683# The next Release Tag684#685#.PARAMETER Path686# The path to the root of where you want to update687#688##############################689function Update-PsVersionInCode690{691 param(692 [Parameter(Mandatory)]693 [ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")]694 [String]695 $NewReleaseTag,696 697 [Parameter(Mandatory)]698 [ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")]699 [String]700 $NextReleaseTag,701 702 [String]703 $Path = (Join-Path -Path $PSScriptRoot -ChildPath '..')704 )705 706 $metaDataPath = (Join-Path -Path $PSScriptRoot -ChildPath 'metadata.json')707 $metaData = Get-Content -Path $metaDataPath | ConvertFrom-Json708 $currentTag = $metaData.StableReleaseTag709 710 $currentVersion = $currentTag -replace '^v'711 $newVersion = $NewReleaseTag -replace '^v'712 $metaData.NextReleaseTag = $NextReleaseTag713 Set-Content -Path $metaDataPath -Encoding ascii -Force -Value ($metaData | ConvertTo-Json)714 715 Get-ChildItem -Path $Path -Recurse -File |716 Where-Object {$_.Extension -notin '.icns','.svg' -and $_.NAME -ne 'CHANGELOG.md' -and $_.DirectoryName -notmatch '[\\/]docs|demos[\\/]'} |717 Where-Object {$_ | Select-String -SimpleMatch $currentVersion -List} |718 ForEach-Object {719 $content = Get-Content -Path $_.FullName -Raw -ReadCount 0720 $newContent = $content.Replace($currentVersion,$newVersion)721 Set-Content -Path $_.FullName -Encoding ascii -Force -Value $newContent -NoNewline722 }723}724 725 726##############################727#.SYNOPSIS728# Test if the GithubCli is in the path729##############################730function Test-GitHubCli {731 $gitHubCli = Get-Command -Name 'gh' -ErrorAction SilentlyContinue732 733 if ($gitHubCli) {734 return $true735 } else {736 return $false737 }738}739 740##############################741#.SYNOPSIS742# Test if the GithubCli is the required version743##############################744function Test-GitHubCliVersion {745 param(746 [Parameter(Mandatory)]747 [System.Management.Automation.SemanticVersion]748 $RequiredVersion749 )750 [System.Management.Automation.SemanticVersion] $version = gh --version | ForEach-Object {751 if ($_ -match ' (\d+\.\d+\.\d+) ') {752 $matches[1]753 }754 }755 756 if ($version -ge $RequiredVersion) {757 return $true758 } else {759 return $false760 }761}762 763##############################764#.SYNOPSIS765# Gets a report of Backport PRs766#767#.PARAMETER Triage state768# The triage states of the PR. Consider, Approved or Done769#770#.PARAMETER Version771# The version of PowerShell the backport is targeting. 7.0, 7.2, 7.3, etc772#773#.PARAMETER Web774# A switch to open all the PRs in the browser775#776##############################777function Get-PRBackportReport {778 param(779 [ValidateSet('Consider', 'Approved', 'Done')]780 [String] $TriageState = 'Approved',781 [ValidatePattern('^\d+\.\d+$')]782 [string] $Version,783 [switch] $Web784 )785 786 if (!(Test-GitHubCli)) {787 throw "GitHub CLI is not installed. Please install it from https://cli.github.com/"788 }789 790 $requiredVersion = '2.17'791 if (!(Test-GitHubCliVersion -RequiredVersion $requiredVersion)) {792 throw "Please upgrade the GitHub CLI to version $requiredVersion. Please install it from https://cli.github.com/"793 }794 795 if (!(gh auth status 2>&1 | Select-String 'logged in')){796 throw "Please login to GitHub CLI using 'gh auth login'"797 }798 799 $prs = gh pr list --state merged --label "Backport-$Version.x-$TriageState" --json title,number,mergeCommit,mergedAt |800 ConvertFrom-Json |801 ForEach-Object {802 [PScustomObject]@{803 CommitId = $_.mergeCommit.oid804 Number = $_.number805 Title = $_.title806 MergedAt = $_.mergedAt807 }808 } | Sort-Object -Property MergedAt809 810 if ($Web) {811 $prs | ForEach-Object {812 gh pr view $_.Number --web813 }814 } else {815 $prs816 }817}818enum RemoteType {819 GitHub820 AzureRepo821}822 823function Get-UpstreamInfo {824 param(825 [Parameter(Mandatory=$true)]826 [string[]]$Upstream,827 828 [Parameter(Mandatory=$true)]829 [string]$UpstreamRemote830 )831 832 $upstreamName = '(powershell(core)?)(/_git)?/(powershell)'833 $pattern = "^$UpstreamRemote\s*(.*)\:(.*/([-\w.]+)/)?$upstreamName(\.git)?.*fetch"834 Write-Verbose -Verbose "searching for an upstream with regex: '$pattern'"835 $Upstream = $Upstream | Where-Object { $_ -match $pattern }836 837 Write-Verbose -Verbose "found $Upstream"838 839 if (!$Upstream) {840 throw "Please create an upstream remote that points to $upstreamName"841 }842 843 $matches | Format-Table | Out-String -Stream -Width 9999 | Write-Verbose844 $org = $matches[3]845 if ($org -ne 'github.com' -and $matches[1] -ne 'git@github.com') {846 Write-Verbose 'parsing Azure repo remote' -Verbose847 # Azure Repo remote848 $project = $matches[4]849 $repo = $matches[7]850 $upstreamHost = $matches[1]851 852 if ($upstreamHost -eq 'https') {853 $upstreamHost = $org854 }855 # matches everything but `.` ending in a `.`856 # in other word, matching the first part of a hostname.857 # like `www.microsoft.com` it would match `www.` with `www` in a capture group.858 if ($org -match '([^\..]*)\.') {859 $org = $Matches[1]860 }861 } else {862 Write-Verbose 'parsing github remote' -Verbose863 # GitHub Repo remote864 $org = $matches[4]865 $repo = $matches[7]866 $upstreamHost = 'github.com'867 $project = $upstreamHost868 }869 870 $remoteType = [RemoteType]::GitHub871 872 if ($upstreamHost -match '.*azure.com$' -or $upstreamHost -match '.*visualstudio.com$') {873 [RemoteType] $remoteType = [RemoteType]::AzureRepo874 }875 876 $upstreamMatchInfo = @{877 org = $org878 project = $project879 repo = $repo880 host = $upstreamHost881 remoteType = $remoteType882 }883 884 return $upstreamMatchInfo885}886 887# Backports a PR888# requires:889# * a remote called upstream pointing to powershell/powershell890# * the github cli installed and authenticated891# Usage:892# Invoke-PRBackport -PRNumber 1234 -Target release/v7.0.1893# To overwrite a local branch add -Overwrite894# To add an postfix to the branch name use -BranchPostFix <postfix>895function Invoke-PRBackport {896 [cmdletbinding(SupportsShouldProcess, ConfirmImpact = 'High')]897 param(898 [Parameter(Mandatory)]899 [string]900 $PrNumber,901 902 [Parameter(Mandatory)]903 [ValidateScript({$_ -match '^release/v\d+\.\d+(\.\d+)?'})]904 [string]905 $Target,906 907 [switch]908 $Overwrite,909 910 [string]911 $BranchPostFix,912 913 [string]914 $UpstreamRemote = 'upstream'915 )916 function script:Invoke-NativeCommand {917 param(918 [scriptblock] $ScriptBlock919 )920 &$ScriptBlock921 if ($LASTEXITCODE -ne 0) {922 throw "$ScriptBlock fail with $LASTEXITCODE"923 }924 }925 function script:Test-ShouldContinue {926 param (927 $Message928 )929 $continue = $false930 while(!$continue) {931 $value = Read-Host -Prompt ($Message + "`nType 'Yes<enter>' to continue 'No<enter>' to exit")932 switch($value) {933 'yes' {934 $continue= $true935 }936 'no' {937 throw "User abort"938 }939 }940 }941 }942 $ErrorActionPreference = 'stop'943 944 $pr = gh pr view $PrNumber --json 'mergeCommit,state,title' | ConvertFrom-Json945 946 $commitId = $pr.mergeCommit.oid947 $state = $pr.state948 $originaltitle = $pr.title949 $backportTitle = "[$Target]$originalTitle"950 951 Write-Verbose -Verbose "commitId: $commitId; state: $state"952 Write-Verbose -Verbose "title:$backportTitle"953 954 if ($state -ne 'MERGED') {955 throw "PR is not merged ($state)"956 }957 958 $upstream = Invoke-NativeCommand { git remote -v }959 $upstreamMatchInfo = Get-UpstreamInfo -Upstream $upstream -UpstreamRemote $UpstreamRemote960 $remoteType = $upstreamMatchInfo.remoteType961 962 Write-Verbose -Verbose "remotetype: $remoteType"963 $upstreamMatchInfo | Format-Table | Out-String -Stream -Width 9999 | Write-Verbose -Verbose964 965 Invoke-NativeCommand { git fetch $UpstreamRemote $Target }966 967 $switch = '-c'968 if ($Overwrite) {969 $switch = '-C'970 }971 972 $branchName = "backport-$PrNumber"973 if ($BranchPostFix) {974 $branchName += "-$BranchPostFix"975 }976 977 if ($PSCmdlet.ShouldProcess("Create branch $branchName from $UpstreamRemote/$Target")) {978 Invoke-NativeCommand { git switch $UpstreamRemote/$Target $switch $branchName }979 }980 981 try {982 $revParseParams = @(983 '--verify'984 "$commitId^{commit}"985 )986 Invoke-NativeCommand { git rev-parse --quiet $revParseParams }987 }988 catch {989 throw "Commit does not exist. Try fetching the upstream. (git rev-parse $revParseParams)"990 }991 992 993 try {994 Invoke-NativeCommand { git cherry-pick $commitId }995 }996 catch {997 Test-ShouldContinue -Message "Fix any conflicts with the cherry-pick."998 }999 1000 if ($PSCmdlet.ShouldProcess("Create the PR")) {1001 $body = "Backport #$PrNumber"1002 switch($remoteType) {1003 "AzureRepo" {1004 Write-Verbose -Verbose "Pushing branch to $UpstreamRemote"1005 git push --set-upstream $UpstreamRemote HEAD1006 $parameters = @(1007 'repos'1008 'pr'1009 'create'1010 )1011 # Open in the browser1012 $parameters += @(1013 '--open'1014 )1015 $parameters += @(1016 '--target-branch'1017 $Target1018 )1019 $parameters += @(1020 '--title'1021 $backportTitle1022 )1023 $parameters += @(1024 '--description'1025 $body1026 )1027 $parameters += @(1028 '--squash'1029 'true'1030 )1031 $parameters += @(1032 '--auto-complete'1033 'true'1034 )1035 $parameters += @(1036 '--delete-source-branch'1037 'true'1038 )1039 $parameters += @(1040 '--org'1041 "https://dev.azure.com/$($upstreamMatchInfo.org)"1042 )1043 $parameters += @(1044 '--project'1045 $upstreamMatchInfo.project1046 )1047 $parameters += @(1048 '--source-branch'1049 $branchName1050 )1051 $parameters += @(1052 '--repository'1053 $upstreamMatchInfo.repo1054 )1055 1056 Write-Verbose -Verbose "az $parameters"1057 $null = Invoke-NativeCommand { az $parameters }1058 }1059 "GitHub" {1060 Write-Verbose -Verbose "Creating PR using gh CLI"1061 gh pr create --base $Target --title $backportTitle --body $body --web1062 }1063 default {1064 throw "unknown remoteType: $remoteType"1065 }1066 }1067 }1068}1069 1070# Backport all approved backports1071# Usage:1072# Invoke-PRBackportApproved -Version 7.2.121073function Invoke-PRBackportApproved {1074 param(1075 [Parameter(Mandatory)]1076 [semver]1077 $Version1078 )1079 1080 $tagVersion = "$($Version.Major).$($Version.Minor)"1081 $target = "release/$ReleaseTag"1082 1083 Get-PRBackportReport -Version $tagVersion |1084 ForEach-Object {1085 $prNumber = $_.Number1086 Invoke-PRBackport -ErrorAction Stop -PrNumber $prNumber -Target $target1087 }1088}1089 1090Export-ModuleMember -Function Get-ChangeLog, Get-NewOfficalPackage, Update-PsVersionInCode, Get-PRBackportReport, Invoke-PRBackport, Invoke-PRBackportApproved, Get-UpstreamInfo1091 