tasks/github.tasks.ps1

$CreateGitHubRelease = $false
$GitHubReleaseDryRunMode = $false       # used by the internal Pester tests
$GitHubReleaseArtefacts = @()
$PublishNuGetPackagesAsGitHubReleaseArtefacts = $false
$GitHubReleaseArtefactsManifestFilePath = "github-release-artefacts.log"

function _createGitHubRelease
{
    if (!$GitHubReleaseDryRunMode) {
        exec { & gh release create $($GitVersion.SemVer) --generate-notes }
    }
    else {
        Write-Host " Skipped due to GitHubReleaseDryRunMode=True"
    }
}

function _uploadReleaseArtefact
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [string] $Item
    )
    
    if (!$GitHubReleaseDryRunMode) {
        exec { & gh release upload --clobber $($GitVersion.SemVer) $Item }
    }
    else {
        Write-Host " Skipped due to GitHubReleaseDryRunMode=True"
    }
}

task PublishGitHubRelease -If { $CreateGitHubRelease } Init,EnsureGitHubCli,Version,{

    if ($PublishNuGetPackagesAsGitHubReleaseArtefacts) {
        # Evaluate the NuGet packages that need to be included in the GitHub release
        $evaluatedNugetPackagesToPublishGlob = Invoke-Expression "`"$($NugetPackageNamesToPublishGlob)$($NugetPackagesToPublishGlobSuffix)`""
        Write-Host "evaluatedNugetPackagesToPublishGlob: $evaluatedNugetPackagesToPublishGlob"
        $nugetPackagesToPublish = Get-ChildItem -Path "$here/_packages" -Filter $evaluatedNugetPackagesToPublishGlob
        Write-Host "nugetPackagesToPublish: $nugetPackagesToPublish"
        
        # Update list of GitHub release artefacts to include resolved NuGet packages
        $script:GitHubReleaseArtefacts += $nugetPackagesToPublish
        Write-Host "GitHubReleaseArtefacts: $GitHubReleaseArtefacts"
    }


    if ($GitHubReleaseArtefacts) {
        $existingRelease = exec { gh release list } |
                                ConvertFrom-Csv -Delimiter "`t" -Header @("TITLE","TYPE","TAG NAME","PUBLISHED") |
                                Where-Object { $_."TAG NAME" -eq $GitVersion.SemVer }

        if (!$existingRelease) {
            Write-Host "Creating new GitHub release: $($GitVersion.SemVer)"
            _createGitHubRelease
        }
        else {
            Write-Host "Updating existing GitHub release: $($GitVersion.SemVer)"
        }

        Set-Content -Path $GitHubReleaseArtefactsManifestFilePath -Value "" -NoNewline
        foreach ($releaseArtefact in $GitHubReleaseArtefacts) {
            if (Test-Path $releaseArtefact) {
                Write-Host "Uploading release artefact: $(Split-Path -Leaf $releaseArtefact)"
                Add-Content -Path $GitHubReleaseArtefactsManifestFilePath -Value $releaseArtefact
                _uploadReleaseArtefact $releaseArtefact    
            }
            else {
                Write-Warning "GitHub Release artefact not found, skipping: $releaseArtefact"
            }
        }
    }
}