Public/Publish-GithubRelease.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
function Publish-GithubRelease
{
    <#
    .SYNOPSIS
        Publish a new release on a Github repository
 
    .FUNCTIONALITY
        CI/CD
 
    .EXAMPLE
        Publish-GithubRelease -AccessToken $mySecretToken -TagName "v1.0"
 
        Create a new release for the tag "v1.0".
        The name of the repository is assumed to be the same as the BHProjectName.
 
    .EXAMPLE
        Publish-GithubRelease -AccessToken $mySecretToken -TagName "v0.1" -Name "Beta Version 0.1" -PreRelease
 
        Create a new pre-release for the tag "v0.1".
 
    .EXAMPLE
        Publish-GithubRelease -AccessToken $mySecretToken -TagName "v1.0" -Draft
 
        Create a draft for a release on tag "v1.0".
 
    .EXAMPLE
        $release = @{
            AccessToken = "00000000000000000000000"
            TagName = "v1.0"
            Name = "Version 1.0"
            ReleaseText = "First version of my cool thing"
            Draft = $true
            PreRelease = $false
            RepositoryName = "MyGithubRepository"
        }
        Publish-GithubRelease @release
 
        Create a new draft release by using splatting (more info at "about_splatting").
 
    .LINK
        https://developer.github.com/v3/repos/releases/
 
    .LINK
        https://blog.github.com/2013-05-16-personal-api-tokens/
    #>

    [CmdletBinding()]
    param(
        # Personal API Token for authentication
        #
        # This sha string must be generated by a user that has push access to
        # the repository.
        # More information can be found at:
        # https://blog.github.com/2013-05-16-personal-api-tokens/
        [Parameter( Mandatory )]
        [ValidateNotNullOrEmpty()]
        [String]
        $AccessToken,

        # Name of the Github user or organization hosting the repository
        [Parameter( Mandatory )]
        [ValidateNotNullOrEmpty()]
        [Alias('Owner')]
        [String]
        $RepositoryOwner,

        # Name of the Github repository
        #
        # Default: $env:BHProjectName
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String]
        $RepositoryName = (Get-ProjectName),

        # Name of the tag
        [Parameter( Mandatory )]
        [ValidateNotNullOrEmpty()]
        [String]
        $TagName,

        # Specifies the commitish value that determines where the Git tag is
        # created from. Can be any branch or commit SHA.
        #
        # Unused if the Git tag already exists.
        # Default: the repository's default branch (usually master).
        [Alias("Commit")]
        [String]
        $TargetCommit,

        # Name of the release
        [String]
        $Name,

        # Text describing the contents of the tag.
        [Alias('Body')]
        [String]
        $ReleaseText,

        # Create a draft (unpublished) release
        [Switch]
        $Draft,

        # Identify the release as a prerelease
        [Switch]
        $PreRelease,

        # Path to the artifact to upload to the release
        [Parameter( ValueFromPipeline, ValueFromPipelineByPropertyName )]
        [ValidateScript(
            {
                if (-not (Test-Path $_ -PathType Leaf))
                {
                    $exception = ([System.ArgumentException]"File not found")
                    $errorId = 'ParameterValue.FileNotFound'
                    $errorCategory = 'ObjectNotFound'
                    $errorTarget = $_
                    $errorItem = New-Object -TypeName System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $errorTarget
                    $errorItem.ErrorDetails = "No file could be found with the provided path '$_'."
                    $PSCmdlet.ThrowTerminatingError($errorItem)
                }
                return $true
            }
        )]
        [Alias('File', 'FullName', 'Path')]
        [String[]]
        $Artifact
    )

    begin
    {
        $body = @{ "tag_name" = $TagName }
        if ($PSBoundParameters.ContainsKey("TargetCommit"))
        {
            $body["target_commitish"] = $TargetCommit
        }
        if ($PSBoundParameters.ContainsKey("Name"))
        {
            $body["name"] = $Name
        }
        if ($PSBoundParameters.ContainsKey("ReleaseText"))
        {
            $body["body"] = $ReleaseText
        }
        if ($PSBoundParameters.ContainsKey("Draft"))
        {
            $body["draft"] = $true
        }
        if ($PSBoundParameters.ContainsKey("PreRelease"))
        {
            $body["prerelease"] = $true
        }

        $releaseParams = @{
            Uri         = "https://api.github.com/repos/{0}/{1}/releases" -f $RepositoryOwner, $RepositoryName
            Method      = 'POST'
            Headers     = @{
                Authorization = 'Basic ' + [Convert]::ToBase64String(
                    [Text.Encoding]::ASCII.GetBytes($AccessToken + ":x-oauth-basic")
                )
            }
            ContentType = 'application/json'
            Body        = $body | ConvertTo-Json
            ErrorAction = "Stop"
        }
        try {
            Set-TlsLevel -Tls12
            $release = Invoke-RestMethod @releaseParams
            $release
        }
        catch {
            throw $_
        }
        finally {
            Set-TlsLevel -Revert
        }
    }

    process
    {
        if ($Artifact)
        {
            foreach ($file in (Get-Item $Artifact))
            {
                $body = [System.IO.File]::ReadAllBytes($file.FullName)
                $uri = $release.upload_url -replace "\{\?name,label\}", "?name=$($file.Name)"

                $assetParams = @{
                    Uri         = $uri
                    Method      = 'POST'
                    Headers     = @{
                        Authorization = 'Basic ' + [Convert]::ToBase64String(
                            [Text.Encoding]::ASCII.GetBytes($AccessToken + ":x-oauth-basic")
                        )
                    }
                    ContentType = "application/octet-stream"
                    Body        = $body
                }

                try {
                    Set-TlsLevel -Tls12
                    Invoke-RestMethod @assetParams
                }
                catch {
                    throw $_
                }
                finally {
                    Set-TlsLevel -Revert
                }
            }
        }
    }
}