-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-GitHubVariable.ps1
More file actions
374 lines (305 loc) · 13.8 KB
/
Copy pathRemove-GitHubVariable.ps1
File metadata and controls
374 lines (305 loc) · 13.8 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
function Remove-GitHubVariable
{
<#
.SYNOPSIS
Removes a GitHub configuration variable from an explicit repository, environment, or organization scope.
.DESCRIPTION
Removes a GitHub configuration variable. Scope selection is always explicit through the
required -Scope parameter.
Repository scope can omit -Repository and use the current Git repository's origin remote.
Environment and organization scopes require their matching target parameters.
The function prefers the GitHub CLI-backed API transport when `gh` is available and falls
back to direct REST API requests otherwise. Missing variables are treated as an idempotent
no-op.
.PARAMETER Name
The GitHub variable name to remove.
Configuration variable names:
- Can contain only letters, numbers, and underscores
- Cannot start with a number
- Cannot start with the GITHUB_ prefix
- Are case-insensitive when referenced by GitHub
.PARAMETER Scope
The GitHub variable scope. Valid values are Repository, Environment, and Organization.
Meanings:
- Repository: a repository-level variable for one repository
- Environment: an environment-level variable for one deployment environment in a repository
- Organization: an organization-level variable that can be shared with repositories
Companion parameter rules:
- Repository: use -Scope Repository; -Repository is optional
- Environment: use -Scope Environment; -Repository and -Environment are required
- Organization: use -Scope Organization; -Organization is required
.PARAMETER Repository
The target repository in OWNER/REPO or HOST/OWNER/REPO format.
Supported with -Scope Repository and -Scope Environment.
Repository variables are available within the specified repository. Environment variables
belong to a specific environment in the specified repository.
When -Scope Repository is used and -Repository is omitted, the function tries to resolve the
current Git repository's origin remote. If that cannot be determined, specify -Repository
explicitly.
Examples:
- octo-org/service-api
- github.example.com/platform/service-api
.PARAMETER Environment
The deployment environment name for environment variables.
Supported only with -Scope Environment and requires -Repository.
Environment variables belong to a single named environment within the repository and are
intended for jobs that reference that environment.
GitHub environment names:
- Are not case sensitive
- May not exceed 255 characters
- Must be unique within the repository
GitHub REST endpoints require environment names to be URL-encoded. This function handles
that automatically, so names containing spaces or `/` are supported.
.PARAMETER Organization
The target organization for organization variables.
Supported only with -Scope Organization.
Organization variables can be shared with repositories in the organization according to the
access policy configured on GitHub.
.PARAMETER Token
Optional GitHub personal access token as a SecureString.
If supplied, the token is used only for the outbound `gh` or REST request and is never
written to command output.
When omitted, the function checks the environment variable named by
-TokenEnvironmentVariableName. If the GitHub CLI is installed, its existing authenticated
session can also be used when no token is supplied. If `gh` is not available and the
function falls back to REST, a token or token environment variable is required.
.PARAMETER TokenEnvironmentVariableName
The environment variable name to check for a GitHub token when -Token is not supplied.
Defaults to GH_TOKEN.
This environment variable is read only when -Token is not supplied. It is used for `gh`
authentication and REST fallback.
.EXAMPLE
PS > Remove-GitHubVariable -Name 'DOTNET_VERSION' -Scope Repository
Removes a repository variable from the current Git repository.
.EXAMPLE
PS > Remove-GitHubVariable -Name 'DEPLOY_RING' -Scope Environment -Repository 'octo-org/service-api' -Environment 'Production'
Removes an environment variable.
.EXAMPLE
PS > Remove-GitHubVariable -Name 'REGION' -Scope Organization -Organization 'octo-org' -WhatIf
Shows what would happen before removing an organization variable.
.EXAMPLE
PS > Remove-GitHubVariable -Name 'PACKAGE_SOURCE' -Scope Organization -Organization 'octo-org' -TokenEnvironmentVariableName 'GITHUB_ADMIN_TOKEN'
Reads the GitHub token from a non-default environment variable.
.OUTPUTS
GitHub.VariableRemoveResult
Returns a summary object with status, target scope, transport used, and whether the variable
changed.
.NOTES
-Scope is required for all GitHub helper functions in this module family.
Variables prefer the GitHub CLI-backed transport and fall back to direct REST API requests.
If the variable does not exist, the function returns an AlreadyAbsent result instead of failing.
.LINK
https://cli.github.com/manual/gh_variable_delete
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Remove-GitHubVariable.ps1
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter(Mandatory, Position = 0)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ($_ -match '^(?i:GITHUB_)')
{
throw "GitHub variable names cannot start with the 'GITHUB_' prefix."
}
if ($_ -notmatch '^(?![0-9])[A-Za-z0-9_]+$')
{
throw 'GitHub variable names may only contain letters, numbers, or underscores, and cannot start with a number.'
}
$true
})]
[String]$Name,
[Parameter(Mandatory)]
[ValidateSet('Repository', 'Environment', 'Organization')]
[String]$Scope,
[Parameter()]
[String]$Repository,
[Parameter()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub environment names cannot be empty or whitespace.'
}
if ($_.Length -gt 255)
{
throw 'GitHub environment names may not exceed 255 characters.'
}
$true
})]
[String]$Environment,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$Organization,
[Parameter()]
[SecureString]$Token,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$TokenEnvironmentVariableName = 'GH_TOKEN'
)
begin
{
function Import-GitHubConfigurationHelpersIfNeeded
{
if (-not (Get-Variable -Name 'PwshProfileGitHubConfigurationHelpers' -Scope Script -ErrorAction SilentlyContinue))
{
$dependencyDirectory = Join-Path -Path $PSScriptRoot -ChildPath 'Private'
$dependencyPath = Join-Path -Path $dependencyDirectory -ChildPath 'GitHubConfigurationHelpers.ps1'
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (-not (Test-Path -LiteralPath $dependencyPath -PathType Leaf))
{
throw "Required dependency could not be found. Expected location: $dependencyPath"
}
try
{
. $dependencyPath
Write-Verbose "Loaded GitHub configuration helpers from: $dependencyPath"
}
catch
{
throw "Failed to load GitHub configuration helpers from '$dependencyPath': $($_.Exception.Message)"
}
}
}
Import-GitHubConfigurationHelpersIfNeeded
$helpers = $script:PwshProfileGitHubConfigurationHelpers
$maxRetryCount = $helpers.DefaultRetryCount
$initialRetryDelaySeconds = $helpers.DefaultInitialRetryDelaySeconds
$resolvedScope = $Scope
switch ($resolvedScope)
{
'Repository'
{
if ($PSBoundParameters.ContainsKey('Environment'))
{
throw 'Use -Scope Environment when specifying -Environment.'
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
throw 'Use -Scope Organization when specifying -Organization.'
}
}
'Environment'
{
if (-not $PSBoundParameters.ContainsKey('Repository'))
{
throw '-Scope Environment requires -Repository.'
}
if (-not $PSBoundParameters.ContainsKey('Environment'))
{
throw '-Scope Environment requires -Environment.'
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
throw '-Scope Environment does not support -Organization.'
}
}
'Organization'
{
if (-not $PSBoundParameters.ContainsKey('Organization'))
{
throw '-Scope Organization requires -Organization.'
}
if ($PSBoundParameters.ContainsKey('Repository'))
{
throw '-Scope Organization does not support -Repository.'
}
if ($PSBoundParameters.ContainsKey('Environment'))
{
throw '-Scope Organization does not support -Environment.'
}
}
}
$getVariableContextParams = @{
Scope = $resolvedScope
Repository = $Repository
Environment = $Environment
Organization = $Organization
}
$variableContext = & $helpers.GetVariableContext @getVariableContextParams
$transport = & $helpers.ResolveTransport
$resolveAuthContextParams = @{
Token = $Token
TokenEnvironmentVariableName = $TokenEnvironmentVariableName
RequireToken = ($transport.Name -ne 'GhCli')
}
$authContext = & $helpers.ResolveAuthContext @resolveAuthContextParams
$variablePath = & $helpers.GetSingleItemPath -CollectionPath $variableContext.CollectionPath -Name $Name
$tryGetGitHubResourceParams = @{
Path = $variablePath
BaseUri = $variableContext.ApiBaseUri
Transport = $transport
AuthContext = $authContext
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
Activity = "Get GitHub variable $Name"
}
$existingVariable = & $helpers.TryGetGitHubResource @tryGetGitHubResourceParams
}
process
{
if (-not $existingVariable.Found)
{
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableRemoveResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'AlreadyAbsent'
Changed = $false
Transport = $transport.Name
Authentication = $authContext.Source
Message = "Variable '$Name' does not exist for $($variableContext.DisplayTarget)."
}
}
if (-not $PSCmdlet.ShouldProcess("$($variableContext.DisplayTarget) :: $Name", 'Remove GitHub variable'))
{
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableRemoveResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'WhatIf'
Changed = $false
Transport = $transport.Name
Authentication = $authContext.Source
Message = 'Variable removal skipped by WhatIf.'
}
}
try
{
$invokeGitHubRequestParams = @{
Method = 'DELETE'
BaseUri = $variableContext.ApiBaseUri
Path = $variablePath
Transport = $transport
AuthContext = $authContext
Body = $null
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
Activity = "Remove GitHub variable $Name"
SensitiveValues = @()
}
$null = & $helpers.InvokeGitHubRequest @invokeGitHubRequestParams
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableRemoveResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'Removed'
Changed = $true
Transport = $transport.Name
Authentication = $authContext.Source
Message = "Variable '$Name' was removed."
}
}
catch
{
$getFriendlyErrorMessageParams = @{
Operation = 'remove variable'
Name = $Name
Target = $variableContext.DisplayTarget
Exception = $_.Exception
}
$friendlyMessage = & $helpers.GetFriendlyErrorMessage @getFriendlyErrorMessageParams
throw $friendlyMessage
}
}
}