Private/Invoke-CCWorkflowPullRequest.ps1

function Invoke-CCWorkflowPullRequest {
    <#
    .SYNOPSIS
        Writes the CodeCompass workflows on a branch of their own and opens a pull request, so
        that nothing lands on the default branch unreviewed. Honours -WhatIf.
    .DESCRIPTION
        Two purposes, and one way of working:

          Adopt A repository takes the workflows for the first time. Everything is written,
                  also over a file that is there (Install-CCReleaseWorkflow -PullRequest).
          Update The workflows are brought level with the templates. A file the repository
                  edited or adopted is left alone unless -Force
                  (Update-CCReleaseWorkflow -PullRequest, and the weekly freshness check).

        The work is done in a worktree of its own, from what the remote has on the default
        branch. The clone the command is run in keeps its branch, its index and its files.

        Nothing is opened where nothing would change, and nothing where a pull request from the
        branch is open: that one is left as it is, and the result names it. A branch of that
        name that is left on the remote from an earlier pull request is written over, where its
        name starts with codecompass/.
    .NOTES
        Requires an authenticated GitHub CLI (gh). Pushing a workflow file takes a login that may
        write workflows: a person's, or a token with contents, pull requests and workflows to
        write. The token a workflow run is given may not.
    #>

    param(
        [Parameter(Mandatory)][string]$Path,
        [string]$Branch = 'codecompass/adopt-release-workflows',
        [ValidateSet('Adopt', 'Update')][string]$Purpose = 'Adopt',
        [switch]$Force,
        [Parameter(Mandatory)][System.Management.Automation.PSCmdlet]$Cmdlet
    )

    $full = (Resolve-Path -LiteralPath $Path).Path
    $service = [CodeCompass.Core.Workflows.WorkflowService]::new()
    $forced = [bool]$Force -or $Purpose -eq 'Adopt'
    $writes = @('Created', 'Updated', 'WouldWrite')
    $describe = { param($outcomes) (@($outcomes) | ForEach-Object { '- {0}: {1}' -f $_.RelativePath, $_.Action }) -join "`n" }

    $doing = if ($Purpose -eq 'Adopt') { "Open a pull request ('$Branch') converging CodeCompass workflows" }
    else { "Open a pull request ('$Branch') that brings the CodeCompass workflows level with the templates" }
    if (-not $Cmdlet.ShouldProcess($full, $doing)) {
        # The plan is read from the files as they are here. The pull request is made from what
        # the remote has on the default branch, which is the same in a clone that is up to date.
        $plan = $service.Sync($full, 'CodeCompass.Release', $forced, $true)
        return [pscustomobject]@{ Branch = $Branch; Action = 'WouldOpenPR'; Plan = (& $describe $plan) }
    }

    $inside = Invoke-CCGit -Path $full -Arguments @('rev-parse', '--is-inside-work-tree')
    if (-not $inside.Ok) { throw "Not a git repository: $full" }

    $config = [CodeCompass.Core.Configuration.ConfigLoader]::new().LoadOrDefault($full)
    $base = if ($config.Ci -and -not [string]::IsNullOrWhiteSpace($config.Ci.DefaultBranch)) { $config.Ci.DefaultBranch } else { 'main' }
    $version = [CodeCompass.Core.Workflows.TemplateVersion]::Current

    $fetch = Invoke-CCGit -Path $full -Arguments @('fetch', '-q', 'origin', $base)
    if (-not $fetch.Ok) { throw "The branch '$base' could not be fetched from the remote 'origin' of ${full}: $($fetch.Output)" }
    $start = (Invoke-CCGit -Path $full -Arguments @('rev-parse', 'FETCH_HEAD')).Answer

    $tree = Join-Path ([IO.Path]::GetTempPath()) ('codecompass-pr-' + [guid]::NewGuid().ToString('N'))
    $added = Invoke-CCGit -Path $full -Arguments @('worktree', 'add', '-q', '--detach', $tree, $start)
    if (-not $added.Ok) { throw "A worktree for the pull request could not be made: $($added.Output)" }

    try {
        $pending = @($service.Sync($tree, 'CodeCompass.Release', $forced, $true) | Where-Object { "$($_.Action)" -in $writes })
        $result = [ordered]@{
            Action          = 'Current'
            Branch          = $Branch
            Base            = $base
            Number          = $null
            Url             = $null
            TemplateVersion = $version
            Files           = @($pending | ForEach-Object RelativePath)
        }
        if (-not $pending) { return [pscustomobject]$result }

        # One that is open is left as it is: a person may be reading it, or changing it.
        $open = Invoke-CCGh -Path $full -Arguments @('pr', 'list', '--head', $Branch, '--state', 'open', '--json', 'number,url')
        if (-not $open.Ok) { throw "GitHub could not be asked for the pull requests of '$Branch': $($open.Error) $($open.Output)".Trim() }
        $found = @(if ($open.Output) { $open.Output | ConvertFrom-Json })
        if ($found.Count) {
            $result.Action = 'AlreadyOpen'
            $result.Number = $found[0].number
            $result.Url = $found[0].url
            return [pscustomobject]$result
        }

        $outcomes = @($service.Sync($tree, 'CodeCompass.Release', $forced, $false))
        $written = @($outcomes | Where-Object { "$($_.Action)" -in $writes })
        $left = @($outcomes | Where-Object { "$($_.Action)" -in 'SkippedUserModified', 'SkippedAdopted' })

        $of = if ($version) { "the templates of CodeCompass.Core $version" } else { 'the current templates' }
        if ($Purpose -eq 'Adopt') {
            $title = 'Adopt CodeCompass release workflows'
            $body = "Adopts CodeCompass-managed release workflows via ``CodeCompass.Release``.`n`n## Changes`n`n$(& $describe $written)`n`nReview the diff and merge to bring this repo under CodeCompass governance."
        }
        else {
            $title = if ($version) { "Update the CodeCompass workflows to the templates of $version" } else { 'Update the CodeCompass workflows to the current templates' }
            $lines = [System.Collections.Generic.List[string]]::new()
            $lines.Add("The workflows CodeCompass manages in this repository were behind its templates. This brings them level with $of.")
            $lines.Add('')
            $lines.Add('## What changes')
            $lines.Add('')
            foreach ($file in $written) { $lines.Add("- ``$($file.RelativePath)``: $("$($file.Action)".ToLowerInvariant())") }
            if ($left) {
                $lines.Add('')
                $lines.Add('## What was left alone')
                $lines.Add('')
                foreach ($file in $left) { $lines.Add("- ``$($file.RelativePath)``: $($file.Message)") }
            }
            # A green check on this pull request ran only what starts on a pull request.
            $unrun = @($written | Where-Object {
                    $content = [IO.File]::ReadAllText((Join-Path $tree $_.RelativePath))
                    $content -notmatch '(?m)^\s+pull_request(_target)?:' -and $content -notmatch '(?m)^on:.*\bpull_request\b'
                })
            if ($unrun) {
                $lines.Add('')
                $lines.Add('## Before merging')
                $lines.Add('')
                $names = (@($unrun | ForEach-Object { '`' + (Split-Path $_.RelativePath -Leaf) + '`' })) -join ', '
                $lines.Add("The checks on this pull request do not run these, since they do not start on a pull request: $names. Their first run is after the merge. One that can be started by hand can be run on this branch first: ``gh workflow run <file> --ref $Branch``.")
            }
            $lines.Add('')
            $lines.Add('Opened by `Update-CCReleaseWorkflow -PullRequest`, which the weekly freshness check runs. It opens no second one while this is open.')
            $body = $lines -join "`n"
        }

        $paths = @($written | ForEach-Object RelativePath) + '.codecompass/manifest.yml'
        $step = Invoke-CCGit -Path $tree -Arguments (@('add', '--') + $paths)
        if ($step.Ok) {
            $message = if ($Purpose -eq 'Adopt') { 'Adopt CodeCompass release workflows' } else { "ci: $($title.Substring(0, 1).ToLowerInvariant())$($title.Substring(1))" }
            $step = Invoke-CCGit -Path $tree -Arguments @('commit', '-q', '-m', $message)
        }
        if (-not $step.Ok) { throw "The commit for the pull request could not be made: $($step.Output)" }

        # A branch of this name on the remote with no pull request open is what an earlier one
        # left behind. It is this tool's own branch, and only such a one is written over.
        $remote = Invoke-CCGit -Path $tree -Arguments @('ls-remote', '--heads', 'origin', $Branch)
        $push = @('push', '-q', 'origin', "HEAD:refs/heads/$Branch")
        if ($remote.Ok -and $remote.Answer) {
            if ($Branch -notlike 'codecompass/*') {
                throw "The branch '$Branch' is on the remote already and no pull request from it is open. Delete it there, or give another -Branch."
            }
            $push = @('push', '-q', '--force', 'origin', "HEAD:refs/heads/$Branch")
        }
        $step = Invoke-CCGit -Path $tree -Arguments $push
        if (-not $step.Ok) {
            throw "The branch '$Branch' could not be pushed. A workflow file is pushed only by a login that may write workflows: a token needs contents, pull requests and workflows to write.`n$($step.Output)"
        }

        $file = Join-Path ([IO.Path]::GetTempPath()) ('codecompass-pr-' + [guid]::NewGuid().ToString('N') + '.md')
        [IO.File]::WriteAllText($file, $body)
        try {
            $created = Invoke-CCGh -Path $full -Arguments @('pr', 'create', '--base', $base, '--head', $Branch, '--title', $title, '--body-file', $file)
        }
        finally { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue }
        if (-not $created.Ok) {
            throw "The branch '$Branch' is pushed and the pull request could not be opened: $($created.Error) $($created.Output)".Trim()
        }

        $url = @($created.Output -split "`n" | Where-Object { $_ -match '^https?://' }) | Select-Object -Last 1
        $result.Action = 'Opened'
        $result.Url = $url
        if ($url -match '/pull/(\d+)') { $result.Number = [int]$Matches[1] }
        $result.Files = @($written | ForEach-Object RelativePath)
        [pscustomobject]$result
    }
    finally {
        Invoke-CCGit -Path $full -Arguments @('worktree', 'remove', '--force', $tree) | Out-Null
        if (Test-Path -LiteralPath $tree) { Remove-Item -LiteralPath $tree -Recurse -Force -ErrorAction SilentlyContinue }
        Invoke-CCGit -Path $full -Arguments @('worktree', 'prune') | Out-Null
    }
}