-
Notifications
You must be signed in to change notification settings - Fork 187
/
GitHubCodespaces.ps1
964 lines (753 loc) · 28.8 KB
/
GitHubCodespaces.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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
@{
GitHubCodespaceTypeName = 'GitHub.Codespace'
}.GetEnumerator() | ForEach-Object {
Set-Variable -Scope Script -Option ReadOnly -Name $_.Key -Value $_.Value
}
filter Get-GitHubCodespace
{
<#
.SYNOPSIS
Retrieves information about a Codespace or list of codespaces on GitHub.
.DESCRIPTION
Retrieves information about a Codespace or list of codespaces on GitHub.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the Codespace.
If not supplied here, the DefaultOwnerName configuration property value will be used.
.PARAMETER RepositoryName
Name of the repository.
If not supplied here, the DefaultRepositoryName configuration property value will be used.
.PARAMETER Uri
Uri for the Codespace.
The OwnerName and CodespaceName will be extracted from here instead of needing to provide
them individually.
.PARAMETER OrganizationName
Name of the Organization.
.PARAMETER UserName
The handle for the GitHub user account.
.PARAMETER CodespaceName
Name of the Codespace.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
GitHub.Project
GitHub.Repository
GitHub.User
.OUTPUTS
GitHub.Codespace
.EXAMPLE
Get-GitHubCodespace
Gets all codespaces for the current authenticated user.
.EXAMPLE
Get-GitHubCodespace -OwnerName octocat
Gets all of the codespaces for the user octocat
.EXAMPLE
Get-GitHubUser -UserName octocat | Get-GitHubCodespace
Gets all of the codespaces for the user octocat
.EXAMPLE
Get-GitHubCodespace -Uri https://github.com/microsoft/PowerShellForGitHub
Gets information about the microsoft/PowerShellForGitHub Codespace.
.EXAMPLE
$repo | Get-GitHubCodespace
You can pipe in a previous Codespace to get its refreshed information.
.EXAMPLE
Get-GitHubCodespace -OrganizationName PowerShell
Gets all of the codespaces in the PowerShell organization.
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#get-a-codespace-for-the-authenticated-user
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#list-codespaces-in-a-repository-for-the-authenticated-user
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#list-codespaces-for-the-authenticated-user
.LINK
https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#list-codespaces-for-the-organization
.LINK
https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#list-codespaces-for-a-user-in-organization
#>
[CmdletBinding(DefaultParameterSetName = 'AuthenticatedUser')]
[OutputType({ $script:GitHubCodespaceTypeName })]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'The Uri parameter is only referenced by Resolve-RepositoryElements which get access to it from the stack via Get-Variable -Scope 1.')]
param(
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Elements')]
[string] $OwnerName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Organization')]
[string] $OrganizationName,
[Parameter(
ValueFromPipelineByPropertyName,
ParameterSetName = 'Organization')]
[ValidateNotNullOrEmpty()]
[String] $UserName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'CodespaceName')]
[string] $CodespaceName,
[string] $AccessToken
)
Write-InvocationLog
$telemetryProperties = @{
UsageType = $PSCmdlet.ParameterSetName
}
$uriFragment = [String]::Empty
$description = [String]::Empty
switch ($PSCmdlet.ParameterSetName)
{
'AuthenticatedUser'
{
$uriFragment = 'user/codespaces'
$description = 'Getting codespaces for current authenticated user'
break
}
'CodespaceName'
{
$telemetryProperties['CodespaceName'] = Get-PiiSafeString -PlainText $CodespaceName
$uriFragment = "user/codespaces/$CodespaceName"
$description = "Getting user/codespaces/$CodespaceName"
break
}
'Organization'
{
$telemetryProperties['OrganizationName'] = Get-PiiSafeString -PlainText $OrganizationName
if ([string]::IsNullOrWhiteSpace($UserName))
{
$uriFragment = "orgs/$OrganizationName/codespaces"
$description = "Getting codespaces for $OrganizationName"
}
else
{
$telemetryProperties['UserName'] = Get-PiiSafeString -PlainText $UserName
$uriFragment = "orgs/$OrganizationName/members/$UserName/codespaces"
$description = "Getting codespaces for $OrganizationName"
}
break
}
{ $_ -in ('Elements', 'Uri') }
{
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties['OwnerName'] = Get-PiiSafeString -PlainText $OwnerName
$telemetryProperties['RepositoryName'] = Get-PiiSafeString -PlainText $RepositoryName
$uriFragment = "repos/$OwnerName/$RepositoryName/codespaces"
$description = "Getting $OwnerName/$RepositoryName/codespaces"
break
}
}
$params = @{
UriFragment = $uriFragment
Description = $description
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
$result = Invoke-GHRestMethodMultipleResult @params
if ($null -ne $result.codespaces)
{
$result = $result.codespaces
}
return ($result | Add-GitHubCodespaceAdditionalProperties)
}
function New-GitHubCodespace
{
<#
.SYNOPSIS
Creates a codespace.
.DESCRIPTION
Creates a codespace.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the Codespace.
If not supplied here, the DefaultOwnerName configuration property value will be used.
.PARAMETER RepositoryName
Name of the repository.
If not supplied here, the DefaultRepositoryName configuration property value will be used.
.PARAMETER Uri
Uri for the Codespace.
The OwnerName and CodespaceName will be extracted from here instead of needing to provide
them individually.
.PARAMETER PullRequest
The pull request number for this codespace.
.PARAMETER RepositoryId
The ID for a Repository. Only applicable when creating a codespace for the current authenticated user.
.PARAMETER Ref
Git ref (typically a branch name) for this codespace
.PARAMETER ClientIp
IP for geo auto-detection when proxying a request.
.PARAMETER DevContainerPath
Path to devcontainer.json config to use for this codespace.
.PARAMETER DisplayName
Display name for this codespace
.PARAMETER Geo
The geographic area for this codespace.
Assigned by IP if not provided.
.PARAMETER Machine
Machine type to use for this codespace.
.PARAMETER NoMultipleRepoPermissions
Whether to authorize requested permissions to other repos from devcontainer.json.
.PARAMETER IdleRetentionPeriodMinutes
Duration in minutes (up to 30 days) after codespace has gone idle in which it will be deleted.
.PARAMETER TimeoutMinutes
Time in minutes before codespace stops from inactivity.
.PARAMETER WorkingDirectory
Working directory for this codespace.
.PARAMETER Wait
If present will wait for the codespace to be available.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
GitHub.Project
GitHub.PullRequest
GitHub.Repository
.OUTPUTS
GitHub.Codespace
.EXAMPLE
New-GitHubCodespace -RepositoryId 582779513
Creates a new codespace for the current authenticated user in the specified repository.
.EXAMPLE
New-GitHubCodespace -RepositoryId 582779513 -PullRequest 508
Creates a new codespace for the current authenticated user in the specified repository from a pull request.
.EXAMPLE
New-GitHubCodespace -OwnerName marykay -RepositoryName one
Creates a codespace owned by the authenticated user in the specified repository.
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-for-the-authenticated-user
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-in-a-repository
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-from-a-pull-request
#>
[CmdletBinding(
SupportsShouldProcess,
DefaultParameterSetName = 'AuthenticatedUser')]
[OutputType({ $script:GitHubCodespaceTypeName })]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'The Uri parameter is only referenced by Resolve-RepositoryElements which get access to it from the stack via Get-Variable -Scope 1, and most of the others get dynamically accessed via $propertyMap.')]
param(
[Parameter(
Mandatory,
ParameterSetName = 'Elements')]
[Parameter(
Mandatory,
ParameterSetName = 'ElementsPullRequest')]
[string] $OwnerName,
[Parameter(
Mandatory,
ParameterSetName = 'Elements')]
[Parameter(
Mandatory,
ParameterSetName = 'ElementsPullRequest')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[Alias('PullRequestUrl')]
[string] $Uri,
[Parameter(ParameterSetName = 'AuthenticatedUser')]
[Parameter(
Mandatory,
ParameterSetName = 'ElementsPullRequest')]
[Alias('PullRequestNumber')]
[int64] $PullRequest,
[Parameter(
Mandatory,
ParameterSetName = 'AuthenticatedUser')]
[Int64] $RepositoryId,
[Parameter(ParameterSetName = 'AuthenticatedUser')]
[Parameter(ParameterSetName = 'Elements')]
[string] $Ref,
[string] $ClientIp,
[string] $DevContainerPath,
[string] $DisplayName,
[ValidateSet('EuropeWest', 'SoutheastAsia', 'UsEast', 'UsWest')]
[string] $Geo,
[string] $Machine,
[switch] $NoMultipleRepoPermissions,
[ValidateRange(0, 43200)]
[int] $IdleRetentionPeriodMinutes,
[ValidateRange(5, 240)]
[int] $TimeoutMinutes,
[string] $WorkingDirectory,
[switch] $Wait,
[string] $AccessToken
)
begin
{
Write-InvocationLog
$propertyMap = @{
ClientIp = 'client_ip'
DevContainerPath = 'devcontainer_path'
DisplayName = 'display_name'
Geo = 'geo'
Machine = 'machine'
Ref = 'ref'
IdleRetentionPeriodMinutes = 'retention_period_minutes'
TimeoutMinutes = 'idle_timeout_minutes'
WorkingDirectory = 'working_directory'
}
}
process
{
$telemetryProperties = @{
UsageType = $PSCmdlet.ParameterSetName
Wait = $Wait.IsPresent
}
$uriFragment = [String]::Empty
$description = [String]::Empty
if ($PSCmdlet.ParameterSetName -eq 'AuthenticatedUser')
{
$uriFragment = 'user/codespaces'
$description = 'Create a codespace for current authenticated user'
}
else
{
# ParameterSets: Elements, ElementsPullRequest, Uri
# ElementsPullRequest prevents Ref for /repos/{owner}/{repo}/pulls/{pull_number}/codespaces
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties['OwnerName'] = Get-PiiSafeString -PlainText $OwnerName
$telemetryProperties['RepositoryName'] = Get-PiiSafeString -PlainText $RepositoryName
if ($PSCmdlet.ParameterSetName -eq 'ElementsPullRequest')
{
$description = "Create a codespace from $OwnerName/$RepositoryName/pulls/$PullRequest"
$telemetryProperties['PullRequest'] = $PullRequest
$uriFragment = "repos/$OwnerName/$RepositoryName/pulls/$PullRequest/codespaces"
}
else
{
$description = "Create a codepace in $OwnerName/$RepositoryName"
$uriFragment = "repos/$OwnerName/$RepositoryName/codespaces"
}
}
$hashBody = @{
multi_repo_permissions_opt_out = $NoMultipleRepoPermissions.IsPresent
}
# Map params to hashBody properties
foreach ($p in $PSBoundParameters.GetEnumerator())
{
if ($propertyMap.ContainsKey($p.Key) -and (-not [string]::IsNullOrWhiteSpace($p.Value)))
{
$hashBody.Add($propertyMap[$p.Key], $p.Value)
}
}
if ($PSCmdlet.ParameterSetName -eq 'AuthenticatedUser')
{
if ($PSBoundParameters.ContainsKey('PullRequest'))
{
$hashBody.Add('pull_request',
[PSCustomObject]@{
pull_request_number = $PullRequest
repository_id = $RepositoryId
}
)
}
else
{
$hashBody.Add('repository_id', $RepositoryId)
}
}
$params = @{
UriFragment = $uriFragment
Body = (ConvertTo-Json -InputObject $hashBody -Depth 5)
Method = 'Post'
Description = $description
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
if (-not $PSCmdlet.ShouldProcess($RepositoryName, 'Create GitHub Codespace'))
{
return
}
$result = (Invoke-GHRestMethod @params | Add-GitHubCodespaceAdditionalProperties)
if ($Wait.IsPresent)
{
$waitParams = @{
CodespaceName = $result.CodespaceName
AccessToken = $AccessToken
}
$result = Wait-GitHubCodespaceAction @waitParams
}
return $result
}
}
filter Remove-GitHubCodespace
{
<#
.SYNOPSIS
Remove a Codespace.
.DESCRIPTION
Remove a Codespace.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OrganizationName
Name of the Organization.
.PARAMETER UserName
The handle for the GitHub user account.
.PARAMETER CodespaceName
Name of the Codespace.
.PARAMETER Force
If this switch is specified, you will not be prompted for confirmation of command execution.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
.OUTPUTS
None
.EXAMPLE
Get-GitHubCodespace -Name vercellone-effective-goggles-qrv997q6j9929jx8 | Remove-GitHubCodespace
.EXAMPLE
Remove-GitHubCodespace -Name vercellone-effective-goggles-qrv997q6j9929jx8
.EXAMPLE
Remove-GitHubCodespace -OrganizationName myorg -UserName jetsong -Name jetsong-button-masher-zzz788y6j8288xp1
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#delete-a-codespace-for-the-authenticated-user
.LINK
https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#delete-a-codespace-from-the-organization
#>
[CmdletBinding(
DefaultParameterSetName = 'AuthenticatedUser',
SupportsShouldProcess,
ConfirmImpact = 'High')]
[Alias('Delete-GitHubCodespace')]
param(
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Organization')]
[string] $OrganizationName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Organization')]
[ValidateNotNullOrEmpty()]
[String] $UserName,
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string] $CodespaceName,
[switch] $Force,
[string] $AccessToken
)
Write-InvocationLog
$telemetryProperties = @{
CodespaceName = Get-PiiSafeString -PlainText $CodespaceName
}
$uriFragment = [String]::Empty
if ($PSCmdlet.ParameterSetName -eq 'AuthenticatedUser')
{
$uriFragment = "user/codespaces/$CodespaceName"
}
else
{
$uriFragment = "orgs/$OrganizationName/members/$UserName/codespaces/$CodespaceName"
}
$params = @{
UriFragment = $uriFragment
Method = 'Delete'
Description = "Remove Codespace $CodespaceName"
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
if ($Force -and (-not $Confirm))
{
$ConfirmPreference = 'None'
}
if (-not $PSCmdlet.ShouldProcess($CodespaceName, "Remove Codespace $CodespaceName"))
{
return
}
Invoke-GHRestMethod @params | Out-Null
}
filter Start-GitHubCodespace
{
<#
.SYNOPSIS
Start a Codespace for the currently authenticated user.
.DESCRIPTION
Start a Codespace for the currently authenticated user.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER CodespaceName
Name of the Codespace.
.PARAMETER Wait
If present will wait for the codespace to start.
.PARAMETER PassThru
Returns the start action result. By default, this cmdlet does not generate any output.
You can use "Set-GitHubConfiguration -DefaultPassThru" to control the default behavior
of this switch.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
.OUTPUTS
GitHub.Codespace
.EXAMPLE
Start-GitHubCodespace -Name vercellone-effective-goggles-qrv997q6j9929jx8
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#start-a-codespace-for-the-authenticated-user
.NOTES
You must authenticate using an access token with the codespace scope to use this endpoint.
GitHub Apps must have write access to the codespaces_lifecycle_admin repository permission to use this endpoint.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'Low')]
[OutputType({ $script:GitHubCodespaceTypeName })]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'PassThru is accessed indirectly via Resolve-ParameterWithDefaultConfigurationValue')]
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string] $CodespaceName,
[switch] $Wait,
[switch] $PassThru,
[string] $AccessToken
)
Write-InvocationLog
$telemetryProperties = @{
CodespaceName = Get-PiiSafeString -PlainText $CodespaceName
Wait = $Wait.IsPresent
}
$params = @{
UriFragment = "user/codespaces/$CodespaceName/start"
Method = 'Post'
Description = "Start Codespace $CodespaceName"
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
if (-not $PSCmdlet.ShouldProcess($CodespaceName, "Start Codespace $CodespaceName"))
{
return
}
$result = (Invoke-GHRestMethod @params | Add-GitHubCodespaceAdditionalProperties)
if ($Wait.IsPresent)
{
$waitParams = @{
CodespaceName = $CodespaceName
AccessToken = $AccessToken
}
$result = Wait-GitHubCodespaceAction @waitParams
}
if (Resolve-ParameterWithDefaultConfigurationValue -Name PassThru -ConfigValueName DefaultPassThru)
{
return $result
}
}
filter Stop-GitHubCodespace
{
<#
.SYNOPSIS
Stop a Codespace for the currently authenticated user.
.DESCRIPTION
Stop a Codespace for the currently authenticated user.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER CodespaceName
Name of the Codespace.
.PARAMETER Wait
If present will wait for the codespace to stop.
.PARAMETER PassThru
Returns the updated GitHub Issue. By default, this cmdlet does not generate any output.
You can use "Set-GitHubConfiguration -DefaultPassThru" to control the default behavior
of this switch.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
.OUTPUTS
GitHub.Codespace
.EXAMPLE
Stop-GitHubCodespace -Name vercellone-effective-goggles-qrv997q6j9929jx8
.LINK
https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#stop-a-codespace-for-the-authenticated-user
.NOTES
You must authenticate using an access token with the codespace scope to use this endpoint.
GitHub Apps must have write access to the codespaces_lifecycle_admin repository permission to use this endpoint.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'Low')]
[OutputType({ $script:GitHubCodespaceTypeName })]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'PassThru is accessed indirectly via Resolve-ParameterWithDefaultConfigurationValue')]
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string] $CodespaceName,
[switch] $Wait,
[switch] $PassThru,
[string] $AccessToken
)
Write-InvocationLog
$telemetryProperties = @{
CodespaceName = Get-PiiSafeString -PlainText $CodespaceName
Wait = $Wait.IsPresent
}
$params = @{
UriFragment = "user/codespaces/$CodespaceName/stop"
Method = 'Post'
Description = "Stop Codespace $CodespaceName"
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
if (-not $PSCmdlet.ShouldProcess($CodespaceName, "Stop Codespace $CodespaceName"))
{
return
}
$result = (Invoke-GHRestMethod @params | Add-GitHubCodespaceAdditionalProperties)
if ($Wait.IsPresent)
{
$waitParams = @{
CodespaceName = $CodespaceName
AccessToken = $AccessToken
}
$result = Wait-GitHubCodespaceAction @waitParams
}
if (Resolve-ParameterWithDefaultConfigurationValue -Name PassThru -ConfigValueName DefaultPassThru)
{
return $result
}
}
function Wait-GitHubCodespaceAction
{
<#
.SYNOPSIS
Wait for a Codespace start or stop action.
.PARAMETER CodespaceName
Name of the Codespace.
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.
.INPUTS
GitHub.Codespace
.OUTPUTS
GitHub.Codespace
.EXAMPLE
Wait-GitHubCodespace -Name vercellone-effective-goggles-qrv997q6j9929jx8
.NOTES
Internal-only helper method.
#>
[CmdletBinding()]
[OutputType({ $script:GitHubCodespaceTypeName })]
param(
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string] $CodespaceName,
[string] $AccessToken
)
begin
{
$sleepSeconds = $(Get-GitHubConfiguration -Name 'StateChangeDelaySeconds')
# 2s minimum
if ($sleepSeconds -lt 2)
{
$sleepSeconds = 2
}
}
process
{
Write-InvocationLog
# Expected states for happy paths:
# Shutdown > Queued > Starting > Available
# Available > Queued > ShuttingDown > ShutDown
#
# To allow for unexpected results, loop until the state is something other than Queued or *ing
# All known states:
# *ings: Awaiting, Exporting, Provisioning, Rebuilding, ShuttingDown, Starting, Updating
# Other: Archived, Available, Created, Deleted, Failed, Moved, Queued, Shutdown, Unavailable, Unknown
do
{
Start-Sleep -Seconds $sleepSeconds
$codespace = (Get-GitHubCodespace @PSBoundParameters)
Write-Log -Message "[$CodespaceName] state is $($codespace.state)" -Level Verbose
}
until ($codespace.state -notmatch 'Queued|ing')
return $codespace
}
}
filter Add-GitHubCodespaceAdditionalProperties
{
<#
.SYNOPSIS
Adds type name and additional properties to ease pipelining to GitHub Repository objects.
.PARAMETER InputObject
The GitHub object to add additional properties to.
.PARAMETER TypeName
The type that should be assigned to the object.
.INPUTS
[PSCustomObject]
.OUTPUTS
GitHub.Codespace
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Internal helper that is definitely adding more than one property.")]
param(
[Parameter(
Mandatory,
ValueFromPipeline)]
[AllowNull()]
[AllowEmptyCollection()]
[PSCustomObject[]] $InputObject,
[ValidateNotNullOrEmpty()]
[string] $TypeName = $script:GitHubCodespaceTypeName
)
foreach ($item in $InputObject)
{
$item.PSObject.TypeNames.Insert(0, $TypeName)
if (-not (Get-GitHubConfiguration -Name DisablePipelineSupport))
{
if ($item.name)
{
Add-Member -InputObject $item -Name 'CodespaceUrl' -Value "user/codespaces/$($item.name)" -MemberType NoteProperty -Force
Add-Member -InputObject $item -Name 'CodespaceName' -Value $item.name -MemberType NoteProperty -Force
}
if ($null -ne $item.billable_owner)
{
$null = Add-GitHubUserAdditionalProperties -InputObject $item.billable_owner
}
if ($null -ne $item.owner)
{
$null = Add-GitHubUserAdditionalProperties -InputObject $item.owner
}
if ($null -ne $item.repository)
{
$null = Add-GitHubRepositoryAdditionalProperties -InputObject $item.repository
Add-Member -InputObject $item -Name 'RepositoryUrl' -Value $item.repository.RepositoryUrl -MemberType NoteProperty -Force
}
}
Write-Output $item
}
}